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.

767 lines
30 KiB

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