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.

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