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.

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