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.

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