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.

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