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.

766 lines
30 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
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\Shipping;
  10. use App\Constants\v3\SsdbKeys;
  11. use App\Exception\ErrorCodeException;
  12. use App\Model\v3\Coupon;
  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\Service\v3\Interfaces\BadgeServiceInterface;
  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\GoodsInventoryServiceInterface;
  26. use App\Service\v3\Interfaces\GoodsServiceInterface;
  27. use App\Service\v3\Interfaces\InitialDeliveryServiceInterface;
  28. use App\Service\v3\Interfaces\PaymentServiceInterface;
  29. use App\Service\v3\Interfaces\ShopCartUpdateServiceInterface;
  30. use App\Service\v3\Interfaces\UserAddressServiceInterface;
  31. use App\TaskWorker\SSDBTask;
  32. use Exception;
  33. use Hyperf\Database\Model\Model;
  34. use Hyperf\DbConnection\Db;
  35. use Hyperf\Di\Annotation\Inject;
  36. use App\Service\v3\Interfaces\OrderOnlineServiceInterface;
  37. use Hyperf\Redis\Redis;
  38. use Hyperf\Snowflake\IdGeneratorInterface;
  39. use Hyperf\Utils\ApplicationContext;
  40. class OrderOnlineService implements OrderOnlineServiceInterface
  41. {
  42. /**
  43. * @Inject
  44. * @var Log
  45. */
  46. protected $log;
  47. /**
  48. * @Inject
  49. * @var UserAddressServiceInterface
  50. */
  51. protected $userAddressService;
  52. /**
  53. * @Inject
  54. * @var CouponRecServiceInterface
  55. */
  56. protected $couponRecService;
  57. /**
  58. * @Inject
  59. * @var CouponServiceInterface
  60. */
  61. protected $couponService;
  62. /**
  63. * @Inject
  64. * @var GoodsActivityServiceInterface
  65. */
  66. protected $goodsActivityService;
  67. /**
  68. * @Inject
  69. * @var GoodsServiceInterface
  70. */
  71. protected $goodsService;
  72. /**
  73. * @Inject
  74. * @var PaymentServiceInterface
  75. */
  76. protected $paymentService;
  77. /**
  78. * @Inject
  79. * @var ShopCartUpdateServiceInterface
  80. */
  81. protected $shopCartUpdateService;
  82. /**
  83. * @Inject
  84. * @var BadgeServiceInterface
  85. */
  86. protected $badgeService;
  87. /**
  88. * @Inject
  89. * @var InitialDeliveryServiceInterface
  90. */
  91. protected $initialDeliveryService;
  92. /**
  93. * @Inject
  94. * @var GoodsInventoryServiceInterface
  95. */
  96. protected $goodsInventoryService;
  97. /**
  98. * 下单
  99. * @param $marketId
  100. * @param $userId
  101. * @param $userAddrId
  102. * @param $storeList
  103. * @param $totalMoney
  104. * @param string $deliveryTimeNote
  105. * @param int $serviceMoney
  106. * @param null $receiveCouponIds
  107. * @param string $plat
  108. * @param int $selfTake
  109. * @return array[]
  110. */
  111. public function do($marketId, $userId, $userAddrId, $storeList, $totalMoney, $deliveryTimeNote='尽快送达', $serviceMoney=0, $receiveCouponIds=null, $plat='', $selfTake=0){
  112. $redis = ApplicationContext::getContainer()->get(Redis::class);
  113. $isCacheInventory = false;
  114. $carts = [];
  115. Db::beginTransaction();
  116. try {
  117. // 获取分布式全局ID
  118. $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
  119. $globalOrderId = $generator->generate();
  120. $mainTable = ApplicationContext::getContainer()->get(OrderMain::class)->getTable();
  121. $childTable = ApplicationContext::getContainer()->get(Order::class)->getTable();
  122. $currentTime = time();
  123. bcscale(6);
  124. $userAddr = (object)[];
  125. $deliveryAmount = 0;
  126. $deliveryDistance = 0;
  127. $shippingType = Shipping::TYPE_SELF_TAKE;
  128. // 如果非自提,则通过用户地址计算相关数据和费用
  129. // if ($selfTake != 1) {
  130. // 用户收货地址
  131. // 获取配送费用
  132. $userAddrAndDPrice = $this->userAddressService->getAddressAndDistributionPrice($userAddrId, $marketId);
  133. $userAddr = $userAddrAndDPrice['address']['address'];
  134. $deliveryAmount = $userAddrAndDPrice['distribution_price'];
  135. $deliveryDistance = $userAddrAndDPrice['delivery_distance'];
  136. // $shippingType = Shipping::TYPE_LANZU;
  137. // }
  138. if ($selfTake != 1) {
  139. $shippingType = Shipping::TYPE_LANZU;
  140. }
  141. // 优惠券数据,当前订单可用个优惠券
  142. $couponRecs = $this->couponRecService->allForOnlineOrderAvailable($userId, $marketId);
  143. $canRealUseCoupons = $couponRecs['available'];
  144. $canRealUseCouponRecIds = array_values(array_column($canRealUseCoupons, 'id'));
  145. if (!empty(array_diff($receiveCouponIds, $canRealUseCouponRecIds))) {
  146. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => '订单中有不能使用优惠券的商品', 'data' => json_encode([
  147. 'all_user_coupons_rec' => json_encode($couponRecs),
  148. 'can_real_user_coupons' => json_encode($canRealUseCoupons),
  149. 'receive_coupon_ids' => json_encode($canRealUseCouponRecIds),
  150. ])]);
  151. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_CANNOT_USE_COUPON);
  152. }
  153. // 处理购物车数据,计算订单金额、子订单数据处理等
  154. $totalAmount = 0; # 实付金额
  155. $orderAmount = 0; # 订单金额
  156. $dataMain = []; # 主订单
  157. $dataChildren = []; # 子订单
  158. $dataOrderGoods = []; # 订单商品
  159. $storeTypeIds = []; # 订单中的商户类型,用于校验红包
  160. $activityGoodsIds = []; # 活动商品IDs
  161. $shopcartIds = [];
  162. foreach ($storeList as $key => &$storeItem) {
  163. $storeId = $storeItem->store_id;
  164. // 子订单金额
  165. $subAmount = 0;
  166. // 店铺分类
  167. $storeType = Store::query()->where(['id' => $storeId])->value('category_id');
  168. $storeTypeIds[] = (string)$storeType;
  169. // 店铺今天的订单数
  170. $count = Order::query()
  171. ->join($mainTable, ''.$mainTable.'.global_order_id', '=', ''.$childTable.'.order_main_id')
  172. ->where([''.$childTable.'.store_id' => $storeId, ''.$mainTable.'.type' => OrderType::ONLINE])
  173. ->whereBetween(''.$childTable.'.created_at', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))])
  174. ->count();
  175. // 用户购物车数据
  176. $cartIds = explode(',', $storeItem->cart_ids);
  177. $shopcartIds = array_merge($shopcartIds, $cartIds);
  178. $carts = ShoppingCart::query()->whereIn('id', $cartIds)->where(['market_id' => $marketId, 'user_id' => $userId])->get();
  179. foreach ($carts as $k => &$cart) {
  180. // 查个商品,做商品有效的判断检查
  181. $goods = [];
  182. if ($cart->activity_type == 1) {
  183. $goods = Goods::query()->lockForUpdate()->with('store')->find($cart->goods_id);
  184. if (empty($goods)) {
  185. throw new ErrorCodeException(ErrorCode::GOODS_NOT_EXISTS, '['.$cart->goods_id.']');
  186. }
  187. $check = $this->goodsService->check($goods, $cart->num);
  188. if (true !== $check) {
  189. throw new ErrorCodeException($check, '['.$goods->name.']');
  190. }
  191. } elseif ($cart->activity_type == 2) {
  192. $goods = GoodsActivity::query()->lockForUpdate()->with('store')->find($cart->goods_id);
  193. if (empty($goods)) {
  194. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_NOT_EXISTS, '['.$cart->goods_id.']');
  195. }
  196. $check = $this->goodsActivityService->check($goods, $cart->num, $userId);
  197. if (true !== $check) {
  198. throw new ErrorCodeException($check, '['.$goods->name.']');
  199. }
  200. }
  201. // 压redis库存
  202. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  203. // $inventoryKey = 'goods_inventory_sold_'.$cart->activity_type.'_'.$cart->goods_id; // 拼接activity_type和goods_id
  204. // if (!$redis->exists($inventoryKey)) {
  205. // $redis->set($inventoryKey, $cart->num);
  206. // } else {
  207. // $redis->incrBy($inventoryKey, intval($cart->num));
  208. // }
  209. $this->goodsInventoryService->doSold($cart->activity_type, $cart->goods_id, $cart->num);
  210. $isCacheInventory = true;
  211. if ($cart->activity_type == 2) {
  212. $activityGoodsIds[] = $cart->goods_id;
  213. }
  214. // 算金额
  215. $goodsAmount = bcmul((string)$goods->price, (string)$cart->num); # 当前商品的金额
  216. $subAmount = bcadd((string)$subAmount, (string)$goodsAmount); # 当前店铺子订单的金额
  217. // 订单商品数据
  218. $dataOrderGoods[$storeId][] = [
  219. 'order_id' => 0,
  220. 'goods_id' => $cart->goods_id,
  221. 'activity_type' => $cart->activity_type,
  222. 'number' => $cart->num,
  223. 'price' => $goods->price,
  224. 'original_price' => $goods->original_price,
  225. 'vip_price' => $goods->vip_price,
  226. 'name' => $goods->name ?: '',
  227. 'goods_unit' => $goods->goods_unit ?: '',
  228. 'cover_img' => $goods->cover_img ?: '',
  229. 'spec' => json_encode($goods->spec),
  230. ];
  231. }
  232. // 子订单数据
  233. $dataChildren[] = [
  234. 'order_main_id' => 0,
  235. 'user_id' => $userId,
  236. 'store_id' => $storeId,
  237. 'money' => bcadd((string)$subAmount, '0', 2),
  238. 'oid' => $count + 1,
  239. 'order_num' => date('YmdHis').mt_rand(1000, 9999),
  240. 'note' => $storeItem->note
  241. ];
  242. // 订单金额
  243. $orderAmount = bcadd((string)$orderAmount, (string)$subAmount);
  244. }
  245. // 优惠券的使用
  246. $couponMoney = 0;
  247. if (!empty($receiveCouponIds)) {
  248. // 计算红包折扣金额
  249. foreach ($canRealUseCoupons as $key => &$coupon) {
  250. if (!in_array($coupon->id, $receiveCouponIds)) {
  251. unset($canRealUseCoupons[$key]);
  252. continue;
  253. }
  254. if ($coupon->coupon->discount_type == Coupon::DISCOUNT_TYPE_CASH) {
  255. $couponMoney = bcadd($couponMoney, $coupon->coupon->discounts, 2);
  256. } elseif ($coupon->coupon->discount_type == Coupon::DISCOUNT_TYPE_RATE) {
  257. $discountRate = bcdiv($coupon->coupon->discounts,10);
  258. $discountRate = bcsub(1,$discountRate);
  259. $discountMoney = bcmul($orderAmount, $discountRate);
  260. $couponMoney = bcadd($couponMoney, $discountMoney, 2);
  261. }
  262. }
  263. }
  264. $orderAmount = bcadd((string)$orderAmount, '0', 2);
  265. $totalAmount = bcadd((string)$totalAmount, (string)$orderAmount);
  266. if ($shippingType != Shipping::TYPE_SELF_TAKE) {
  267. $totalAmount = bcadd((string)$totalAmount, (string)$deliveryAmount);
  268. }
  269. $totalAmount = bcadd((string)$totalAmount, (string)$serviceMoney);
  270. $totalAmount = bcsub((string)$totalAmount, (string)$couponMoney, 2);
  271. // 校验订单总金额
  272. if ($totalAmount != $totalMoney) {
  273. throw new ErrorCodeException(
  274. ErrorCode::ORDER_TOTAL_AMOUNT_ERROR,
  275. '',
  276. [
  277. 'total_amount' => $totalAmount,
  278. 'total_money' => $totalMoney,
  279. 'deliveryAmount' => $deliveryAmount,
  280. '$orderAmount' => $orderAmount,
  281. 'serviceMoney' => $serviceMoney,
  282. 'couponMoney' => $couponMoney,
  283. ]
  284. );
  285. }
  286. // 校验订单总金额是否满足起送
  287. $initDeliveryAmount = $this->initialDeliveryService->get();
  288. if ($orderAmount < $initDeliveryAmount) {
  289. throw new ErrorCodeException(ErrorCode::ORDER_NOT_ENOUGH_INITIAL_DELIVERY, "[{$initDeliveryAmount}]");
  290. }
  291. $dataMain = [
  292. 'shipping_type' => $shippingType,
  293. 'market_id' => $marketId,
  294. 'order_num' => $globalOrderId,
  295. 'global_order_id' => $globalOrderId,
  296. 'user_id' => $userId,
  297. 'type' => OrderType::ONLINE,
  298. 'money' => $totalAmount,
  299. 'total_money' => $orderAmount,
  300. 'services_money' => $serviceMoney,
  301. 'coupon_money' => $couponMoney,
  302. 'delivery_money' => $deliveryAmount,
  303. 'delivery_distance' => $deliveryDistance,
  304. 'state' => OrderState::UNPAID,
  305. 'tel' => $userAddr->tel ?? '',
  306. 'address' => ($userAddr->address ?? '').($userAddr->doorplate ?? ''),
  307. 'lat' => $userAddr->lat ?? '',
  308. 'lng' => $userAddr->lng ?? '',
  309. 'name' => $userAddr->user_name ?? '',
  310. 'plat' => $plat,
  311. 'delivery_time_note' => $deliveryTimeNote
  312. ];
  313. // 生成主订单
  314. $orderMain = OrderMain::query()->create($dataMain);
  315. // 处理子订单
  316. foreach ($dataChildren as $key => &$child) {
  317. $child['order_main_id'] = $globalOrderId;
  318. $orderChild = Order::query()->create($child);
  319. $orderChildId = $orderChild->id;
  320. foreach ($dataOrderGoods[$child['store_id']] as $k => &$orderGoods) {
  321. $orderGoods['order_id'] = $orderChildId;
  322. $orderGoods['created_at'] = $currentTime;
  323. $orderGoods['updated_at'] = $currentTime;
  324. }
  325. OrderGoods::query()->insert($dataOrderGoods[$child['store_id']]);
  326. }
  327. // 判断是否有购买多个特价商品
  328. $check = $this->goodsActivityService->checkOrderActivityCount($activityGoodsIds);
  329. if(!$check){
  330. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => '同一订单中有活动商品不可同时购买多款', 'data' => json_encode($dataOrderGoods)]);
  331. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_RESTRICT_LIMIT);
  332. }
  333. // 订单成功,做一些处理
  334. // 活动商品购买记录
  335. foreach ($dataOrderGoods as $key => &$goods) {
  336. foreach ($goods as $k => &$goodsItem) {
  337. if ($goodsItem['activity_type'] == 2) {
  338. $this->goodsActivityService->cacheRecord($goodsItem['goods_id'], $goodsItem['number'], $userId);
  339. }
  340. }
  341. }
  342. Db::commit();
  343. if (!empty($receiveCouponIds)) {
  344. $this->couponService->orderUseCoupons($globalOrderId, $canRealUseCoupons);
  345. }
  346. // 清除购物车
  347. $this->shopCartUpdateService->doClear($userId, $marketId, $shopcartIds);
  348. // 记录badge
  349. $this->badgeService->doByOrder($userId, array_values(array_column($dataChildren, 'store_id')), $orderMain->global_order_id, OrderState::UNPAID);
  350. // 支付
  351. return $this->paymentService->do($globalOrderId, $totalAmount, $userId, config('wechat.notify_url.online'));
  352. } catch (Exception $e) {
  353. Db::rollBack();
  354. if ($isCacheInventory) {
  355. // 释redis库存
  356. foreach ($carts as $k => &$cart) {
  357. // // 拼接activity_type和goods_id
  358. // $inventoryKey = 'goods_inventory_sold_'.$cart->activity_type.'_'.$cart->goods_id;
  359. // // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  360. // if (!$redis->exists($inventoryKey)) {
  361. // $redis->set($inventoryKey, 0);
  362. // } else {
  363. // $redis->decrBy($inventoryKey, intval($cart->num));
  364. // }
  365. $this->goodsInventoryService->undoSold($cart->activity_type, $cart->goods_id, $cart->num);
  366. }
  367. }
  368. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => $e->getMessage()]);
  369. $message = '';
  370. if ($e instanceof ErrorCodeException) {
  371. $message = $e->getMessage();
  372. }
  373. throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_FAIL, $message);
  374. }
  375. }
  376. public function check($globalOrderId, $userId, $state): Model
  377. {
  378. $builder = OrderMain::query()
  379. ->where(['global_order_id' => $globalOrderId, 'user_id' => $userId]);
  380. if (is_array($state)) {
  381. $builder = $builder->whereIn('state', $state);
  382. } else {
  383. $builder = $builder->where(['state' => $state]);
  384. }
  385. $orderMain = $builder->first();
  386. if (empty($orderMain)) {
  387. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  388. }
  389. return $orderMain;
  390. }
  391. /**
  392. * @inheritDoc
  393. */
  394. public function undo($globalOrderId, $userId)
  395. {
  396. Db::beginTransaction();
  397. try {
  398. // 订单待支付
  399. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  400. $orderMain->state = OrderState::CANCELED;
  401. if (!$orderMain->save()) {
  402. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  403. }
  404. // 退还优惠券
  405. $this->couponService->orderRefundCoupons($globalOrderId);
  406. // 撤销活动商品购买记录
  407. $orders = Order::query()->where(['order_main_id' => $globalOrderId])->get()->toArray();
  408. $orderGoods = OrderGoods::query()
  409. // ->where('activity_type', 2)
  410. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  411. ->get()
  412. ->toArray();
  413. foreach ($orderGoods as $key => &$goods) {
  414. if ($goods['activity_type'] == 2) {
  415. $this->goodsActivityService->clearCacheRecord($goods['goods_id'], $goods['number'], $orderMain['user_id']);
  416. }
  417. }
  418. Db::commit();
  419. // 释redis库存
  420. $redis = ApplicationContext::getContainer()->get(Redis::class);
  421. foreach ($orderGoods as $k => &$goodsItem) {
  422. // // 拼接activity_type和goods_id
  423. // $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  424. // // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  425. // if (!$redis->exists($inventoryKey)) {
  426. // $redis->set($inventoryKey, 0);
  427. // } else {
  428. // $redis->decrBy($inventoryKey, intval($goodsItem['number']));
  429. // }
  430. $this->goodsInventoryService->undoSold($goodsItem['activity_type'], $goodsItem['goods_id'], $goodsItem['number']);
  431. }
  432. // 记录badge
  433. $orderChildIds = array_values(array_column($orders, 'store_id'));
  434. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::CANCELED);
  435. return true;
  436. } catch (Exception $e) {
  437. Db::rollBack();
  438. throw new ErrorCodeException(ErrorCode::ORDER_CANCEL_FAIL, $e->getMessage());
  439. }
  440. }
  441. public function detailByUser($globalOrderId, $userId)
  442. {
  443. $orderMain = OrderMain::with(['market'])->where(['global_order_id' => $globalOrderId])->first();
  444. $orders = Order::query()
  445. ->where(['order_main_id' => $globalOrderId, 'user_id' => $userId])
  446. ->with([
  447. 'orderGoods',
  448. 'store'
  449. ])
  450. ->get()->toArray();
  451. return ['order_main' => $orderMain, 'orders' => $orders];
  452. }
  453. /**
  454. * @inheritDoc
  455. */
  456. public function doByPaid($globalOrderId)
  457. {
  458. Db::beginTransaction();
  459. try {
  460. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  461. // 查询订单
  462. $orderMain = OrderMain::query()
  463. ->where(['global_order_id' => $globalOrderId,'type' => OrderType::ONLINE])
  464. ->first();
  465. // 修改订单、子订单状态
  466. $currentTime = time();
  467. $orderMain->state = OrderState::PAID;
  468. $orderMain->pay_time = $currentTime;
  469. $orderMain->save();;
  470. // 更新商品库存和销量
  471. $orders = Order::query()
  472. ->where(['order_main_id' => $globalOrderId])
  473. ->get()
  474. ->toArray();
  475. // 更新商户销量
  476. $upStoreScore = Store::query()
  477. ->whereIn('id', array_values(array_column($orders, 'store_id')))
  478. ->update(['sales' => Db::raw('sales+1')]);
  479. $orderGoods = OrderGoods::query()
  480. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  481. ->get()
  482. ->toArray();
  483. foreach ($orderGoods as $key => &$goodsItem) {
  484. if ($goodsItem['activity_type'] == 2) { # 活动商品
  485. $goods = GoodsActivity::find($goodsItem['goods_id']);
  486. } else {
  487. $goods = Goods::find($goodsItem['goods_id']);
  488. }
  489. $goods->inventory = $goods->inventory - $goodsItem['number'];
  490. $goods->sales = $goods->sales + $goodsItem['number'];
  491. $goods->save();
  492. // 商品月销
  493. if (!$ssdb->exec('exists', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_'.$goods->id)) {
  494. $ssdb->exec('set', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  495. } else {
  496. $ssdb->exec('incr', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  497. }
  498. }
  499. Db::commit();
  500. // 释redis库存
  501. $redis = ApplicationContext::getContainer()->get(Redis::class);
  502. foreach ($orderGoods as $k => &$goodsItem) {
  503. // // 拼接activity_type和goods_id
  504. // $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  505. // // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  506. // if (!$redis->exists($inventoryKey)) {
  507. // $redis->set($inventoryKey, 0);
  508. // } else {
  509. // $redis->decrBy($inventoryKey, intval($goodsItem['number']));
  510. // }
  511. $this->goodsInventoryService->undoSold($goodsItem['activity_type'], $goodsItem['goods_id'], $goodsItem['number']);
  512. }
  513. // 月销流水
  514. $statistics = [];
  515. foreach ($orders as $key => &$order) {
  516. $statistics[] = [
  517. 'money' => $order['money'],
  518. 'user_id' => $order['user_id'],
  519. 'store_id' => $order['store_id'],
  520. 'market_id' => $orderMain->market_id,
  521. 'order_id' => $order['id'],
  522. ];
  523. // 商户月销
  524. if (!$ssdb->exec('exists', SsdbKeys::STORE_MONTH_SALES . date('Ym').'_' . $order['store_id'])) {
  525. $ssdb->exec('set', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  526. } else {
  527. $ssdb->exec('incr', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  528. }
  529. }
  530. if (is_array($statistics) && !empty($statistics)) {
  531. $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics);
  532. }
  533. return true;
  534. } catch (Exception $e) {
  535. $this->log->event(LogLabel::ORDER_ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
  536. Db::rollBack();
  537. return false;
  538. }
  539. }
  540. /**
  541. * @inheritDoc
  542. */
  543. public function doPay($globalOrderId, $userId)
  544. {
  545. // 订单待支付
  546. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  547. return $this->paymentService->do(
  548. $orderMain->global_order_id,
  549. $orderMain->money,
  550. $orderMain->user_id,
  551. config('wechat.notify_url.online')
  552. );
  553. }
  554. /**
  555. * @inheritDoc
  556. * @throws Exception
  557. */
  558. public function doDel($globalOrderId, $userId)
  559. {
  560. // 订单完成
  561. $orderMain = $this->check($globalOrderId, $userId, OrderState::CAN_DEL);
  562. if (!$orderMain->delete()) {
  563. throw new ErrorCodeException(ErrorCode::ORDER_DELETE_FAIL);
  564. }
  565. return true;
  566. }
  567. /**
  568. * @inheritDoc
  569. */
  570. public function doApplyRefund($globalOrderId, $userId)
  571. {
  572. // 未接单
  573. $orderMain = $this->check($globalOrderId, $userId, OrderState::PAID);
  574. $orderMain->state = OrderState::REFUNDING;
  575. if (!$orderMain->save()) {
  576. throw new ErrorCodeException(ErrorCode::ORDER_APPLY_REFUND_FAIL);
  577. }
  578. // 记录badge
  579. $orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
  580. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::REFUNDING);
  581. return true;
  582. }
  583. /**
  584. * @inheritDoc
  585. */
  586. public function doComplete($globalOrderId, $userId)
  587. {
  588. $orderMain = $this->check($globalOrderId, $userId, OrderState::RECEIVING);
  589. $orderMain->state = OrderState::COMPLETED;
  590. if (!$orderMain->save()) {
  591. throw new ErrorCodeException(ErrorCode::ORDER_COMPLETE_FAIL);
  592. }
  593. // 记录badge
  594. $orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
  595. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::COMPLETED);
  596. return true;
  597. }
  598. /**
  599. * @inheritDoc
  600. */
  601. public function doRefund($globalOrderId, $userId)
  602. {
  603. $orderMain = $this->check($globalOrderId, $userId, OrderState::REFUNDING);
  604. $orderIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('id');
  605. $orderGoods = OrderGoods::query()->whereIn('order_id', $orderIds)->get()->toArray();
  606. // 微信退款
  607. if ($orderMain->pay_type == Payment::WECHAT) {
  608. return $this->paymentService->undo($orderMain->global_order_id, $userId);
  609. }
  610. }
  611. public function autoCancel()
  612. {
  613. try {
  614. $orderMains = OrderMain::query()
  615. ->where(['state' => OrderState::UNPAID, 'type' => OrderType::ONLINE])
  616. ->where('created_at', '<', time()-600)
  617. ->orderBy('created_at', 'asc')
  618. ->limit(100)
  619. ->get();
  620. foreach ($orderMains as $key => &$orderMain) {
  621. // 订单取消
  622. OrderMain::query()->where(['id' => $orderMain->id])->update(['state' => OrderState::CANCELED]);
  623. // 退还优惠券
  624. $this->couponService->orderRefundCoupons($orderMain->global_order_id);
  625. // 撤销活动商品购买记录
  626. $orders = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->get()->toArray();
  627. $orderGoods = OrderGoods::query()
  628. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  629. ->get()
  630. ->toArray();
  631. foreach ($orderGoods as $key => &$goods) {
  632. if ($goods['activity_type'] == 2) {
  633. $this->goodsActivityService->clearCacheRecord($goods['goods_id'], $goods['number'], $orderMain->user_id);
  634. }
  635. }
  636. // 释redis库存
  637. $redis = ApplicationContext::getContainer()->get(Redis::class);
  638. foreach ($orderGoods as $k => &$goodsItem) {
  639. // // 拼接activity_type和goods_id
  640. // $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  641. // // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  642. // if (!$redis->exists($inventoryKey)) {
  643. // $redis->set($inventoryKey, 0);
  644. // } else {
  645. // $redis->decrBy($inventoryKey, intval($goodsItem['number']));
  646. // }
  647. $this->goodsInventoryService->undoSold($goodsItem['activity_type'], $goodsItem['goods_id'], $goodsItem['number']);
  648. }
  649. // 记录badge
  650. $orderChildIds = array_values(array_column($orders, 'store_id'));
  651. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::CANCELED);
  652. }
  653. } catch (Exception $e) {
  654. $this->log->event(LogLabel::ORDER_AUTO_CANCEL_FAIL_LOG, ['message' => $e->getMessage()]);
  655. }
  656. }
  657. }