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.

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