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.

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