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.

728 lines
29 KiB

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