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.

768 lines
31 KiB

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