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.

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