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.

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