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.

750 lines
30 KiB

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