You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

559 lines
21 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. <?php
  2. namespace App\Service\v3\Implementations;
  3. use App\Commons\Log;
  4. use App\Constants\v3\ErrorCode;
  5. use App\Constants\v3\LogLabel;
  6. use App\Constants\v3\OrderState;
  7. use App\Constants\v3\OrderType;
  8. use App\Constants\v3\Payment;
  9. use App\Constants\v3\SsdbKeys;
  10. use App\Exception\ErrorCodeException;
  11. use App\Model\v3\Coupon;
  12. use App\Model\v3\CouponRec;
  13. use App\Model\v3\Goods;
  14. use App\Model\v3\GoodsActivity;
  15. use App\Model\v3\Order;
  16. use App\Model\v3\OrderGoods;
  17. use App\Model\v3\OrderMain;
  18. use App\Model\v3\OrderSalesStatistic;
  19. use App\Model\v3\ShoppingCart;
  20. use App\Model\v3\Store;
  21. use App\Model\v3\UserAddress;
  22. use App\Service\v3\Interfaces\CouponRecServiceInterface;
  23. use App\Service\v3\Interfaces\CouponServiceInterface;
  24. use App\Service\v3\Interfaces\GoodsActivityServiceInterface;
  25. use App\Service\v3\Interfaces\GoodsServiceInterface;
  26. use App\Service\v3\Interfaces\PaymentServiceInterface;
  27. use App\Service\v3\Interfaces\ShopCartUpdateServiceInterface;
  28. use App\Service\v3\Interfaces\UserAddressServiceInterface;
  29. use App\TaskWorker\SSDBTask;
  30. use Exception;
  31. use Hyperf\Database\Model\Model;
  32. use Hyperf\DbConnection\Db;
  33. use Hyperf\Di\Annotation\Inject;
  34. use App\Service\v3\Interfaces\OrderOnlineServiceInterface;
  35. use Hyperf\Snowflake\IdGeneratorInterface;
  36. use Hyperf\Utils\ApplicationContext;
  37. class OrderOnlineService implements OrderOnlineServiceInterface
  38. {
  39. /**
  40. * @Inject
  41. * @var Log
  42. */
  43. protected $log;
  44. /**
  45. * @Inject
  46. * @var UserAddressServiceInterface
  47. */
  48. protected $userAddressService;
  49. /**
  50. * @Inject
  51. * @var CouponRecServiceInterface
  52. */
  53. protected $couponRecService;
  54. /**
  55. * @Inject
  56. * @var CouponServiceInterface
  57. */
  58. protected $couponService;
  59. /**
  60. * @Inject
  61. * @var GoodsActivityServiceInterface
  62. */
  63. protected $goodsActivityService;
  64. /**
  65. * @Inject
  66. * @var GoodsServiceInterface
  67. */
  68. protected $goodsService;
  69. /**
  70. * @Inject
  71. * @var PaymentServiceInterface
  72. */
  73. protected $paymentService;
  74. /**
  75. * @Inject
  76. * @var ShopCartUpdateServiceInterface
  77. */
  78. protected $shopCartUpdateService;
  79. /**
  80. * 下单
  81. * @param $marketId
  82. * @param $userId
  83. * @param $userAddrId
  84. * @param $storeList
  85. * @param $totalMoney
  86. * @param string $deliveryTimeNote
  87. * @param int $serviceMoney
  88. * @param null $receiveCouponIds
  89. * @param string $plat
  90. * @return array[]
  91. */
  92. public function do($marketId, $userId, $userAddrId, $storeList, $totalMoney, $deliveryTimeNote='尽快送达', $serviceMoney=0, $receiveCouponIds=null, $plat=''){
  93. Db::beginTransaction();
  94. try {
  95. $currentTime = time();
  96. bcscale(6);
  97. // 用户收货地址
  98. // 获取配送费用
  99. $userAddrAndDPrice = $this->userAddressService->getAddressAndDistributionPrice($userAddrId, $marketId);
  100. $userAddr = $userAddrAndDPrice['address'];
  101. $deliveryAmount = $userAddrAndDPrice['distribution_price'];
  102. // 优惠券数据,当前订单可用个优惠券
  103. $couponRecs = $this->couponRecService->allForOnlineOrderAvailable($userId, $marketId);
  104. $canRealUseCoupons = $couponRecs['available'];
  105. $canRealUseCouponRecIds = array_values(array_column($canRealUseCoupons, 'id'));
  106. if (!empty(array_diff($receiveCouponIds, $canRealUseCouponRecIds))) {
  107. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_CANNOT_USE_COUPON, '[优惠券不可用]'.$receiveCouponIds.'_'.$canRealUseCouponRecIds);
  108. }
  109. // 处理购物车数据,计算订单金额、子订单数据处理等
  110. $totalAmount = 0; # 实付金额
  111. $orderAmount = 0; # 订单金额
  112. $dataMain = []; # 主订单
  113. $dataChildren = []; # 子订单
  114. $dataOrderGoods = []; # 订单商品
  115. $storeTypeIds = []; # 订单中的商户类型,用于校验红包
  116. foreach ($storeList as $key => &$storeItem) {
  117. $storeId = $storeItem->store_id;
  118. // 子订单金额
  119. $subAmount = 0;
  120. // 店铺分类
  121. $storeType = Store::query()->where(['id' => $storeId])->value('category_id');
  122. $storeTypeIds[] = (string)$storeType;
  123. // 店铺今天的订单数
  124. $count = Order::query()
  125. ->join('lanzu_order_main as main', 'main.id', '=', 'lanzu_order.order_main_id')
  126. ->where(['lanzu_order.store_id' => $storeId, 'main.type' => OrderType::ONLINE])
  127. ->whereBetween('lanzu_order.created_at', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))])
  128. ->count();
  129. // 用户购物车数据
  130. $cartIds = explode(',', $storeItem->cart_ids);
  131. $carts = ShoppingCart::query()->whereIn('id', $cartIds)->where(['market_id' => $marketId, 'user_id' => $userId])->get();
  132. foreach ($carts as $k => &$cart) {
  133. // 查个商品,做商品有效的判断检查
  134. $goods = [];
  135. if ($cart->activity_type == 1) {
  136. $goods = Goods::query()->lockForUpdate()->with('store')->find($cart->goods_id);
  137. if (empty($goods)) {
  138. throw new ErrorCodeException(ErrorCode::ORDER_GOODS_NOT_AVAILABLE, '[商品失效1]'.$cart->goods_id);
  139. }
  140. $check = $this->goodsService->check($goods, $cart->num);
  141. if (true !== $check) {
  142. throw new ErrorCodeException($check, '[商品失效2]'.$cart->goods_id);
  143. }
  144. } elseif ($cart->activity_type == 2) {
  145. $goods = GoodsActivity::query()->lockForUpdate()->with('store')->find($cart->goods_id);
  146. if (empty($goods)) {
  147. throw new ErrorCodeException(ErrorCode::ORDER_GOODS_NOT_AVAILABLE, '[商品失效3]'.$cart->goods_id);
  148. }
  149. $check = $this->goodsActivityService->check($goods, $cart->num, $userId);
  150. if (true !== $check) {
  151. throw new ErrorCodeException($check, '[商品失效4]'.$cart->goods_id);
  152. }
  153. }
  154. // 算金额
  155. $goodsAmount = bcmul((string)$goods->price, (string)$cart->num); # 当前商品的金额
  156. $subAmount = bcadd((string)$subAmount, (string)$goodsAmount); # 当前店铺子订单的金额
  157. // 订单商品数据
  158. $dataOrderGoods[$storeId][] = [
  159. 'order_id' => 0,
  160. 'goods_id' => $cart->goods_id,
  161. 'activity_type' => $cart->activity_type,
  162. 'number' => $cart->num,
  163. 'price' => $goods->price,
  164. 'original_price' => $goods->original_price,
  165. 'vip_price' => $goods->vip_price,
  166. 'name' => $goods->name,
  167. 'goods_unit' => $goods->goods_unit,
  168. 'cover_img' => $goods->cover_img,
  169. 'spec' => json_encode($goods->spec),
  170. ];
  171. }
  172. // 子订单数据
  173. $dataChildren[] = [
  174. 'order_main_id' => 0,
  175. 'user_id' => $userId,
  176. 'store_id' => $storeId,
  177. 'money' => bcadd((string)$subAmount, '0', 2),
  178. 'oid' => $count + 1,
  179. 'order_num' => date('YmdHis').mt_rand(1000, 9999),
  180. 'note' => $storeItem->note
  181. ];
  182. // 订单金额
  183. $orderAmount = bcadd((string)$orderAmount, (string)$subAmount);
  184. }
  185. // 优惠券的使用
  186. $couponMoney = 0;
  187. if (!empty($receiveCouponIds)) {
  188. // 计算红包折扣金额
  189. foreach ($canRealUseCoupons as $key => &$coupon) {
  190. if (!in_array($coupon['id'], $receiveCouponIds)) {
  191. unset($coupon);
  192. continue;
  193. }
  194. if ($coupon['coupon']['discount_type'] == Coupon::DISCOUNT_TYPE_CASH) {
  195. $couponMoney = bcadd($couponMoney, $coupon['coupon']['discounts'], 2);
  196. } elseif ($coupon['coupon']['discount_type'] == Coupon::DISCOUNT_TYPE_RATE) {
  197. $discountRate = bcdiv($coupon['coupon']['discounts'],10);
  198. $discountRate = bcsub(1,$discountRate);
  199. $discountMoney = bcmul($orderAmount, $discountRate);
  200. $couponMoney = bcadd($couponMoney, $discountMoney, 2);
  201. }
  202. }
  203. }
  204. // 获取分布式全局ID
  205. $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
  206. $globalOrderId = $generator->generate();
  207. $orderAmount = bcadd((string)$orderAmount, '0', 2);
  208. $totalAmount = bcadd((string)$totalAmount, (string)$orderAmount);
  209. $totalAmount = bcadd((string)$totalAmount, (string)$deliveryAmount);
  210. $totalAmount = bcadd((string)$totalAmount, (string)$serviceMoney);
  211. $totalAmount = bcsub((string)$totalAmount, (string)$couponMoney, 2);
  212. // 校验订单总金额
  213. if ($totalAmount != $totalMoney) {
  214. throw new ErrorCodeException(ErrorCode::ORDER_TOTAL_AMOUNT_ERROR);
  215. }
  216. $dataMain = [
  217. 'market_id' => $marketId,
  218. 'order_num' => $globalOrderId,
  219. 'global_order_id' => $globalOrderId,
  220. 'user_id' => $userId,
  221. 'type' => OrderType::ONLINE,
  222. 'money' => $totalAmount,
  223. 'total_money' => $orderAmount,
  224. 'services_money' => $serviceMoney,
  225. 'coupon_money' => $couponMoney,
  226. 'delivery_money' => $deliveryAmount,
  227. 'state' => OrderState::UNPAID,
  228. 'tel' => $userAddr->tel,
  229. 'address' => $userAddr->address.$userAddr->doorplate,
  230. 'lat' => $userAddr->lat,
  231. 'lng' => $userAddr->lng,
  232. 'name' => $userAddr->user_name,
  233. 'plat' => $plat,
  234. 'delivery_time_note' => $deliveryTimeNote
  235. ];
  236. // 生成主订单
  237. $orderMain = OrderMain::query()->create($dataMain);
  238. // 处理子订单
  239. foreach ($dataChildren as $key => &$child) {
  240. $child['order_main_id'] = $globalOrderId;
  241. $orderChild = Order::query()->create($child);
  242. $orderChildId = $orderChild->id;
  243. foreach ($dataOrderGoods[$child['store_id']] as $k => &$orderGoods) {
  244. $orderGoods['order_id'] = $orderChildId;
  245. $orderGoods['created_at'] = $currentTime;
  246. $orderGoods['updated_at'] = $currentTime;
  247. }
  248. OrderGoods::query()->insert($dataOrderGoods[$child['store_id']]);
  249. }
  250. // 判断是否有购买多个特价商品
  251. $check = $this->goodsActivityService->checkOrderActivityCount($dataOrderGoods);
  252. if(!$check){
  253. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_RESTRICT_LIMIT, '[同一订单同种类型活动商品]'.json_encode($dataOrderGoods));
  254. }
  255. // 订单成功,做一些处理
  256. // 活动商品购买记录
  257. foreach ($dataOrderGoods as $key => &$goods) {
  258. foreach ($goods as $k => &$goodsItem)
  259. if ($goodsItem['activity_type'] == 2) {
  260. $this->goodsActivityService->cacheRecord($goodsItem['goods_id'], $goodsItem['number'], $userId);
  261. }
  262. }
  263. // 优惠券红包使用记录
  264. $this->couponService->orderUseCoupons($globalOrderId, $canRealUseCoupons);
  265. Db::commit();
  266. // 清除购物车
  267. $this->shopCartUpdateService->doClear($userId, $marketId);
  268. // 记录用户中心的badge
  269. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  270. $ssdb->exec('hincr', SsdbKeys::USER_ORDER_BADGE.$userId, 'unpaid', 1);
  271. // 支付
  272. return $this->paymentService->do($globalOrderId, $totalAmount, $userId, config('wechat.notify_url.online'));
  273. } catch (Exception $e) {
  274. Db::rollBack();
  275. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['exception_msg' => $e->getMessage()]);
  276. throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_FAIL, $e->getMessage());
  277. }
  278. }
  279. public function check($globalOrderId, $userId, $state): Model
  280. {
  281. $builder = OrderMain::query()
  282. ->where(['global_order_id' => $globalOrderId, 'user_id' => $userId]);
  283. if (is_array($state)) {
  284. $builder = $builder->whereIn('state', $state);
  285. } else {
  286. $builder = $builder->where(['state' => $state]);
  287. }
  288. $orderMain = $builder->first();
  289. if (empty($orderMain)) {
  290. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  291. }
  292. return $orderMain;
  293. }
  294. /**
  295. * @inheritDoc
  296. */
  297. public function undo($globalOrderId, $userId)
  298. {
  299. Db::beginTransaction();
  300. try {
  301. // 订单待支付
  302. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  303. $orderMain->state = OrderState::CANCELED;
  304. if (!$orderMain->save()) {
  305. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  306. }
  307. // 退还优惠券
  308. $this->couponService->orderRefundCoupons($globalOrderId);
  309. // 撤销活动商品购买记录
  310. $orders = Order::query()->where(['order_main_id' => $globalOrderId])->get()->toArray();
  311. $orderGoods = OrderGoods::query()
  312. ->where('activity_type', 2)
  313. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  314. ->get();
  315. foreach ($orderGoods as $key => &$goods) {
  316. $this->goodsActivityService->clearCacheRecord($goods->goods_id, $goods->number, $orderMain->user_id);
  317. }
  318. Db::commit();
  319. return true;
  320. } catch (Exception $e) {
  321. Db::rollBack();
  322. throw new ErrorCodeException(ErrorCode::ORDER_CANCEL_FAIL, $e->getMessage());
  323. }
  324. }
  325. public function detailByUser($globalOrderId, $userId)
  326. {
  327. $orderMain = OrderMain::with(['market'])->where(['global_order_id' => $globalOrderId])->first();
  328. $orders = Order::query()
  329. ->where(['order_main_id' => $globalOrderId, 'user_id' => $userId])
  330. ->with([
  331. 'orderGoods',
  332. 'store'
  333. ])
  334. ->get()->toArray();
  335. return ['order_main' => $orderMain, 'orders' => $orders];
  336. }
  337. /**
  338. * @inheritDoc
  339. */
  340. public function doByPaid($globalOrderId)
  341. {
  342. Db::beginTransaction();
  343. try {
  344. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  345. // 查询订单
  346. $orderMain = OrderMain::query()
  347. ->where(['global_order_id' => $globalOrderId,'type' => OrderType::ONLINE])
  348. ->first();
  349. // 修改订单、子订单状态
  350. $currentTime = time();
  351. $orderMain->state = OrderState::PAID;
  352. $orderMain->pay_time = $currentTime;
  353. $orderMain->save();;
  354. // 更新商品库存和销量
  355. $orders = Order::query()
  356. ->where(['order_main_id' => $globalOrderId])
  357. ->get()
  358. ->toArray();
  359. // 更新商户销量
  360. $upStoreScore = Store::query()
  361. ->whereIn('id', array_values(array_column($orders, 'store_id')))
  362. ->update(['sales' => Db::raw('sales+1')]);
  363. $orderGoods = OrderGoods::query()
  364. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  365. ->get()
  366. ->toArray();
  367. foreach ($orderGoods as $key => &$goodsItem) {
  368. if ($goodsItem['activity_type'] == 2) { # 活动商品
  369. $goods = GoodsActivity::find($goodsItem['goods_id']);
  370. } else {
  371. $goods = Goods::find($goodsItem['goods_id']);
  372. }
  373. $goods->inventory = $goods->inventory - $goodsItem['number'];
  374. $goods->sales = $goods->sales + $goodsItem['number'];
  375. $goods->save();
  376. // 商品月销
  377. if (!$ssdb->exec('exists', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_'.$goods->id)) {
  378. $ssdb->exec('set', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  379. } else {
  380. $ssdb->exec('incr', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  381. }
  382. }
  383. // 月销流水
  384. $statistics = [];
  385. foreach ($orders as $key => &$order) {
  386. $statistics[] = [
  387. 'money' => $order['money'],
  388. 'user_id' => $order['user_id'],
  389. 'store_id' => $order['store_id'],
  390. 'market_id' => $orderMain->market_id,
  391. 'order_id' => $order['id'],
  392. 'createtime' => $orderMain->pay_time,
  393. ];
  394. // 商户月销
  395. if (!$ssdb->exec('exists', SsdbKeys::STORE_MONTH_SALES . date('Ym').'_' . $order['store_id'])) {
  396. $ssdb->exec('set', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  397. } else {
  398. $ssdb->exec('incr', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  399. }
  400. }
  401. if (is_array($statistics) && !empty($statistics)) {
  402. $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics);
  403. }
  404. Db::commit();
  405. // 记录用户中心的badge
  406. $ssdb->exec('hincr', SsdbKeys::USER_ORDER_BADGE.$orderMain->user_id, 'receiving', 1);
  407. return true;
  408. } catch (Exception $e) {
  409. $this->log->event(LogLabel::ORDER_ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
  410. Db::rollBack();
  411. return false;
  412. }
  413. }
  414. /**
  415. * @inheritDoc
  416. */
  417. public function doPay($globalOrderId, $userId)
  418. {
  419. // 订单待支付
  420. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  421. return $this->paymentService->do(
  422. $orderMain->global_order_id,
  423. $orderMain->money,
  424. $orderMain->user_id,
  425. config('wechat.notify_url.online')
  426. );
  427. }
  428. /**
  429. * @inheritDoc
  430. * @throws Exception
  431. */
  432. public function doDel($globalOrderId, $userId)
  433. {
  434. // 订单完成
  435. $orderMain = $this->check($globalOrderId, $userId, OrderState::CAN_DEL);
  436. if (!$orderMain->delete()) {
  437. throw new ErrorCodeException(ErrorCode::ORDER_DELETE_FAIL);
  438. }
  439. return true;
  440. }
  441. /**
  442. * @inheritDoc
  443. */
  444. public function doApplyRefund($globalOrderId, $userId)
  445. {
  446. // 未接单
  447. $orderMain = $this->check($globalOrderId, $userId, OrderState::PAID);
  448. $orderMain->state = OrderState::REFUNDING;
  449. if (!$orderMain->save()) {
  450. throw new ErrorCodeException(ErrorCode::ORDER_APPLY_REFUND_FAIL);
  451. }
  452. // 记录badge
  453. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  454. $ssdb->exec('hincr', SsdbKeys::USER_ORDER_BADGE.$orderMain->user_id, 'refund', 1);
  455. return true;
  456. }
  457. /**
  458. * @inheritDoc
  459. */
  460. public function doComplete($globalOrderId, $userId)
  461. {
  462. $orderMain = $this->check($globalOrderId, $userId, OrderState::RECEIVING);
  463. $orderMain->state = OrderState::COMPLETED;
  464. if (!$orderMain->save()) {
  465. throw new ErrorCodeException(ErrorCode::ORDER_COMPLETE_FAIL);
  466. }
  467. // 记录badge
  468. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  469. $ssdb->exec('hincr', SsdbKeys::USER_ORDER_BADGE.$orderMain->user_id, 'completed', 1);
  470. return true;
  471. }
  472. /**
  473. * @inheritDoc
  474. */
  475. public function doRefund($globalOrderId, $userId)
  476. {
  477. $orderMain = $this->check($globalOrderId, $userId, OrderState::REFUNDING);
  478. // 微信退款
  479. if ($orderMain->pay_type == Payment::WECHAT) {
  480. return $this->paymentService->undo($orderMain->global_order_id, $userId);
  481. }
  482. }
  483. }