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.

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