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.

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