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.

754 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
  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(ErrorCode::ORDER_TOTAL_AMOUNT_ERROR);
  265. }
  266. // 校验订单总金额是否满足起送
  267. $initDeliveryAmount = $this->initialDeliveryService->get();
  268. if ($orderAmount < $initDeliveryAmount) {
  269. throw new ErrorCodeException(ErrorCode::ORDER_NOT_ENOUGH_INITIAL_DELIVERY, "[{$initDeliveryAmount}]");
  270. }
  271. $dataMain = [
  272. 'shipping_type' => $shippingType,
  273. 'market_id' => $marketId,
  274. 'order_num' => $globalOrderId,
  275. 'global_order_id' => $globalOrderId,
  276. 'user_id' => $userId,
  277. 'type' => OrderType::ONLINE,
  278. 'money' => $totalAmount,
  279. 'total_money' => $orderAmount,
  280. 'services_money' => $serviceMoney,
  281. 'coupon_money' => $couponMoney,
  282. 'delivery_money' => $deliveryAmount,
  283. 'delivery_distance' => $deliveryDistance,
  284. 'state' => OrderState::UNPAID,
  285. 'tel' => $userAddr->tel ?? '',
  286. 'address' => ($userAddr->address ?? '').($userAddr->doorplate ?? ''),
  287. 'lat' => $userAddr->lat ?? '',
  288. 'lng' => $userAddr->lng ?? '',
  289. 'name' => $userAddr->user_name ?? '',
  290. 'plat' => $plat,
  291. 'delivery_time_note' => $deliveryTimeNote
  292. ];
  293. // 生成主订单
  294. $orderMain = OrderMain::query()->create($dataMain);
  295. // 处理子订单
  296. foreach ($dataChildren as $key => &$child) {
  297. $child['order_main_id'] = $globalOrderId;
  298. $orderChild = Order::query()->create($child);
  299. $orderChildId = $orderChild->id;
  300. foreach ($dataOrderGoods[$child['store_id']] as $k => &$orderGoods) {
  301. $orderGoods['order_id'] = $orderChildId;
  302. $orderGoods['created_at'] = $currentTime;
  303. $orderGoods['updated_at'] = $currentTime;
  304. }
  305. OrderGoods::query()->insert($dataOrderGoods[$child['store_id']]);
  306. }
  307. // 判断是否有购买多个特价商品
  308. $check = $this->goodsActivityService->checkOrderActivityCount($activityGoodsIds);
  309. if(!$check){
  310. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => '同一订单中有活动商品不可同时购买多款', 'data' => json_encode($dataOrderGoods)]);
  311. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_RESTRICT_LIMIT);
  312. }
  313. // 订单成功,做一些处理
  314. // 活动商品购买记录
  315. foreach ($dataOrderGoods as $key => &$goods) {
  316. foreach ($goods as $k => &$goodsItem) {
  317. if ($goodsItem['activity_type'] == 2) {
  318. $this->goodsActivityService->cacheRecord($goodsItem['goods_id'], $goodsItem['number'], $userId);
  319. }
  320. }
  321. }
  322. Db::commit();
  323. if (!empty($receiveCouponIds)) {
  324. $this->couponService->orderUseCoupons($globalOrderId, $canRealUseCoupons);
  325. }
  326. // 清除购物车
  327. $this->shopCartUpdateService->doClear($userId, $marketId);
  328. // 记录badge
  329. $this->badgeService->doByOrder($userId, array_values(array_column($dataChildren, 'store_id')), $orderMain->global_order_id, OrderState::UNPAID);
  330. // 支付
  331. return $this->paymentService->do($globalOrderId, $totalAmount, $userId, config('wechat.notify_url.online'));
  332. } catch (Exception $e) {
  333. Db::rollBack();
  334. if ($isCacheInventory) {
  335. // 释redis库存
  336. foreach ($carts as $k => &$cart) {
  337. // 拼接activity_type和goods_id
  338. $inventoryKey = 'goods_inventory_sold_'.$cart->activity_type.'_'.$cart->goods_id;
  339. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  340. if (!$redis->exists($inventoryKey)) {
  341. $redis->set($inventoryKey, 0);
  342. } else {
  343. $redis->decrBy($inventoryKey, intval($cart->num));
  344. }
  345. }
  346. }
  347. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => $e->getMessage()]);
  348. $message = '';
  349. if ($e instanceof ErrorCodeException) {
  350. $message = $e->getMessage();
  351. }
  352. throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_FAIL, $message);
  353. }
  354. }
  355. public function check($globalOrderId, $userId, $state): Model
  356. {
  357. $builder = OrderMain::query()
  358. ->where(['global_order_id' => $globalOrderId, 'user_id' => $userId]);
  359. if (is_array($state)) {
  360. $builder = $builder->whereIn('state', $state);
  361. } else {
  362. $builder = $builder->where(['state' => $state]);
  363. }
  364. $orderMain = $builder->first();
  365. if (empty($orderMain)) {
  366. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  367. }
  368. return $orderMain;
  369. }
  370. /**
  371. * @inheritDoc
  372. */
  373. public function undo($globalOrderId, $userId)
  374. {
  375. Db::beginTransaction();
  376. try {
  377. // 订单待支付
  378. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  379. $orderMain->state = OrderState::CANCELED;
  380. if (!$orderMain->save()) {
  381. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  382. }
  383. // 退还优惠券
  384. $this->couponService->orderRefundCoupons($globalOrderId);
  385. // 撤销活动商品购买记录
  386. $orders = Order::query()->where(['order_main_id' => $globalOrderId])->get()->toArray();
  387. $orderGoods = OrderGoods::query()
  388. // ->where('activity_type', 2)
  389. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  390. ->get()
  391. ->toArray();
  392. foreach ($orderGoods as $key => &$goods) {
  393. if ($goods['activity_type'] == 2) {
  394. $this->goodsActivityService->clearCacheRecord($goods['goods_id'], $goods['number'], $orderMain['user_id']);
  395. }
  396. }
  397. Db::commit();
  398. // 释redis库存
  399. $redis = ApplicationContext::getContainer()->get(Redis::class);
  400. foreach ($orderGoods as $k => &$goodsItem) {
  401. // 拼接activity_type和goods_id
  402. $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  403. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  404. if (!$redis->exists($inventoryKey)) {
  405. $redis->set($inventoryKey, 0);
  406. } else {
  407. $redis->decrBy($inventoryKey, intval($goodsItem['number']));
  408. }
  409. }
  410. // 记录badge
  411. $orderChildIds = array_values(array_column($orders, 'store_id'));
  412. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::CANCELED);
  413. return true;
  414. } catch (Exception $e) {
  415. Db::rollBack();
  416. throw new ErrorCodeException(ErrorCode::ORDER_CANCEL_FAIL, $e->getMessage());
  417. }
  418. }
  419. public function detailByUser($globalOrderId, $userId)
  420. {
  421. $orderMain = OrderMain::with(['market'])->where(['global_order_id' => $globalOrderId])->first();
  422. $orders = Order::query()
  423. ->where(['order_main_id' => $globalOrderId, 'user_id' => $userId])
  424. ->with([
  425. 'orderGoods',
  426. 'store'
  427. ])
  428. ->get()->toArray();
  429. return ['order_main' => $orderMain, 'orders' => $orders];
  430. }
  431. /**
  432. * @inheritDoc
  433. */
  434. public function doByPaid($globalOrderId)
  435. {
  436. Db::beginTransaction();
  437. try {
  438. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  439. // 查询订单
  440. $orderMain = OrderMain::query()
  441. ->where(['global_order_id' => $globalOrderId,'type' => OrderType::ONLINE])
  442. ->first();
  443. // 修改订单、子订单状态
  444. $currentTime = time();
  445. $orderMain->state = OrderState::PAID;
  446. $orderMain->pay_time = $currentTime;
  447. $orderMain->save();;
  448. // 更新商品库存和销量
  449. $orders = Order::query()
  450. ->where(['order_main_id' => $globalOrderId])
  451. ->get()
  452. ->toArray();
  453. // 更新商户销量
  454. $upStoreScore = Store::query()
  455. ->whereIn('id', array_values(array_column($orders, 'store_id')))
  456. ->update(['sales' => Db::raw('sales+1')]);
  457. $orderGoods = OrderGoods::query()
  458. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  459. ->get()
  460. ->toArray();
  461. foreach ($orderGoods as $key => &$goodsItem) {
  462. if ($goodsItem['activity_type'] == 2) { # 活动商品
  463. $goods = GoodsActivity::find($goodsItem['goods_id']);
  464. } else {
  465. $goods = Goods::find($goodsItem['goods_id']);
  466. }
  467. $goods->inventory = $goods->inventory - $goodsItem['number'];
  468. $goods->sales = $goods->sales + $goodsItem['number'];
  469. $goods->save();
  470. // 商品月销
  471. if (!$ssdb->exec('exists', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_'.$goods->id)) {
  472. $ssdb->exec('set', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  473. } else {
  474. $ssdb->exec('incr', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  475. }
  476. }
  477. Db::commit();
  478. // 释redis库存
  479. $redis = ApplicationContext::getContainer()->get(Redis::class);
  480. foreach ($orderGoods as $k => &$goodsItem) {
  481. // 拼接activity_type和goods_id
  482. $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  483. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  484. if (!$redis->exists($inventoryKey)) {
  485. $redis->set($inventoryKey, 0);
  486. } else {
  487. $redis->decrBy($inventoryKey, intval($goodsItem['number']));
  488. }
  489. }
  490. // 月销流水
  491. $statistics = [];
  492. foreach ($orders as $key => &$order) {
  493. $statistics[] = [
  494. 'money' => $order['money'],
  495. 'user_id' => $order['user_id'],
  496. 'store_id' => $order['store_id'],
  497. 'market_id' => $orderMain->market_id,
  498. 'order_id' => $order['id'],
  499. ];
  500. // 商户月销
  501. if (!$ssdb->exec('exists', SsdbKeys::STORE_MONTH_SALES . date('Ym').'_' . $order['store_id'])) {
  502. $ssdb->exec('set', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  503. } else {
  504. $ssdb->exec('incr', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  505. }
  506. }
  507. if (is_array($statistics) && !empty($statistics)) {
  508. $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics);
  509. }
  510. return true;
  511. } catch (Exception $e) {
  512. $this->log->event(LogLabel::ORDER_ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
  513. Db::rollBack();
  514. return false;
  515. }
  516. }
  517. /**
  518. * @inheritDoc
  519. */
  520. public function doPay($globalOrderId, $userId)
  521. {
  522. // 订单待支付
  523. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  524. return $this->paymentService->do(
  525. $orderMain->global_order_id,
  526. $orderMain->money,
  527. $orderMain->user_id,
  528. config('wechat.notify_url.online')
  529. );
  530. }
  531. /**
  532. * @inheritDoc
  533. * @throws Exception
  534. */
  535. public function doDel($globalOrderId, $userId)
  536. {
  537. // 订单完成
  538. $orderMain = $this->check($globalOrderId, $userId, OrderState::CAN_DEL);
  539. if (!$orderMain->delete()) {
  540. throw new ErrorCodeException(ErrorCode::ORDER_DELETE_FAIL);
  541. }
  542. return true;
  543. }
  544. /**
  545. * @inheritDoc
  546. */
  547. public function doApplyRefund($globalOrderId, $userId)
  548. {
  549. // 未接单
  550. $orderMain = $this->check($globalOrderId, $userId, OrderState::PAID);
  551. $orderMain->state = OrderState::REFUNDING;
  552. if (!$orderMain->save()) {
  553. throw new ErrorCodeException(ErrorCode::ORDER_APPLY_REFUND_FAIL);
  554. }
  555. // 记录badge
  556. $orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
  557. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::REFUNDING);
  558. return true;
  559. }
  560. /**
  561. * @inheritDoc
  562. */
  563. public function doComplete($globalOrderId, $userId)
  564. {
  565. $orderMain = $this->check($globalOrderId, $userId, OrderState::RECEIVING);
  566. $orderMain->state = OrderState::COMPLETED;
  567. if (!$orderMain->save()) {
  568. throw new ErrorCodeException(ErrorCode::ORDER_COMPLETE_FAIL);
  569. }
  570. // 记录badge
  571. $orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
  572. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::COMPLETED);
  573. return true;
  574. }
  575. /**
  576. * @inheritDoc
  577. */
  578. public function doRefund($globalOrderId, $userId)
  579. {
  580. $orderMain = $this->check($globalOrderId, $userId, OrderState::REFUNDING);
  581. $orderIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('id');
  582. $orderGoods = OrderGoods::query()->whereIn('order_id', $orderIds)->get()->toArray();
  583. // 释redis库存
  584. $redis = ApplicationContext::getContainer()->get(Redis::class);
  585. foreach ($orderGoods as $k => &$goodsItem) {
  586. // 拼接activity_type和goods_id
  587. $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  588. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  589. if (!$redis->exists($inventoryKey)) {
  590. $redis->set($inventoryKey, 0);
  591. } else {
  592. $redis->decrBy($inventoryKey, intval($goodsItem['number']));
  593. }
  594. }
  595. // 微信退款
  596. if ($orderMain->pay_type == Payment::WECHAT) {
  597. return $this->paymentService->undo($orderMain->global_order_id, $userId);
  598. }
  599. }
  600. public function autoCancel()
  601. {
  602. try {
  603. $orderMains = OrderMain::query()
  604. ->where(['state' => OrderState::UNPAID, 'type' => OrderType::ONLINE])
  605. ->where('created_at', '<', time()-600)
  606. ->orderBy('created_at', 'asc')
  607. ->limit(100)
  608. ->get();
  609. foreach ($orderMains as $key => &$orderMain) {
  610. // 订单取消
  611. OrderMain::query()->where(['id' => $orderMain->id])->update(['state' => OrderState::CANCELED]);
  612. // 退还优惠券
  613. $this->couponService->orderRefundCoupons($orderMain->global_order_id);
  614. // 撤销活动商品购买记录
  615. $orders = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->get()->toArray();
  616. $orderGoods = OrderGoods::query()
  617. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  618. ->get()
  619. ->toArray();
  620. foreach ($orderGoods as $key => &$goods) {
  621. if ($goods['activity_type'] == 2) {
  622. $this->goodsActivityService->clearCacheRecord($goods['goods_id'], $goods['number'], $orderMain->user_id);
  623. }
  624. }
  625. // 释redis库存
  626. $redis = ApplicationContext::getContainer()->get(Redis::class);
  627. foreach ($orderGoods as $k => &$goodsItem) {
  628. // 拼接activity_type和goods_id
  629. $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  630. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  631. if (!$redis->exists($inventoryKey)) {
  632. $redis->set($inventoryKey, 0);
  633. } else {
  634. $redis->decrBy($inventoryKey, intval($goodsItem['number']));
  635. }
  636. }
  637. // 记录badge
  638. $orderChildIds = array_values(array_column($orders, 'store_id'));
  639. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::CANCELED);
  640. }
  641. } catch (Exception $e) {
  642. $this->log->event(LogLabel::ORDER_AUTO_CANCEL_FAIL_LOG, ['message' => $e->getMessage()]);
  643. }
  644. }
  645. }