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.

748 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
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. // 用户收货地址
  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. if ($shippingType != Shipping::TYPE_SELF_TAKE) {
  252. $totalAmount = bcadd((string)$totalAmount, (string)$deliveryAmount);
  253. }
  254. $totalAmount = bcadd((string)$totalAmount, (string)$serviceMoney);
  255. $totalAmount = bcsub((string)$totalAmount, (string)$couponMoney, 2);
  256. // 校验订单总金额
  257. if ($totalAmount != $totalMoney) {
  258. throw new ErrorCodeException(ErrorCode::ORDER_TOTAL_AMOUNT_ERROR);
  259. }
  260. // 校验订单总金额是否满足起送
  261. $initDeliveryAmount = $this->initialDeliveryService->get();
  262. if ($orderAmount < $initDeliveryAmount) {
  263. throw new ErrorCodeException(ErrorCode::ORDER_NOT_ENOUGH_INITIAL_DELIVERY, "[{$initDeliveryAmount}]");
  264. }
  265. $dataMain = [
  266. 'shipping_type' => $shippingType,
  267. 'market_id' => $marketId,
  268. 'order_num' => $globalOrderId,
  269. 'global_order_id' => $globalOrderId,
  270. 'user_id' => $userId,
  271. 'type' => OrderType::ONLINE,
  272. 'money' => $totalAmount,
  273. 'total_money' => $orderAmount,
  274. 'services_money' => $serviceMoney,
  275. 'coupon_money' => $couponMoney,
  276. 'delivery_money' => $deliveryAmount,
  277. 'delivery_distance' => $deliveryDistance,
  278. 'state' => OrderState::UNPAID,
  279. 'tel' => $userAddr->tel,
  280. 'address' => $userAddr->address.$userAddr->doorplate,
  281. 'lat' => $userAddr->lat,
  282. 'lng' => $userAddr->lng,
  283. 'name' => $userAddr->user_name,
  284. 'plat' => $plat,
  285. 'delivery_time_note' => $deliveryTimeNote
  286. ];
  287. // 生成主订单
  288. $orderMain = OrderMain::query()->create($dataMain);
  289. // 处理子订单
  290. foreach ($dataChildren as $key => &$child) {
  291. $child['order_main_id'] = $globalOrderId;
  292. $orderChild = Order::query()->create($child);
  293. $orderChildId = $orderChild->id;
  294. foreach ($dataOrderGoods[$child['store_id']] as $k => &$orderGoods) {
  295. $orderGoods['order_id'] = $orderChildId;
  296. $orderGoods['created_at'] = $currentTime;
  297. $orderGoods['updated_at'] = $currentTime;
  298. }
  299. OrderGoods::query()->insert($dataOrderGoods[$child['store_id']]);
  300. }
  301. // 判断是否有购买多个特价商品
  302. $check = $this->goodsActivityService->checkOrderActivityCount($activityGoodsIds);
  303. if(!$check){
  304. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => '同一订单中有活动商品不可同时购买多款', 'data' => json_encode($dataOrderGoods)]);
  305. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_RESTRICT_LIMIT);
  306. }
  307. // 订单成功,做一些处理
  308. // 活动商品购买记录
  309. foreach ($dataOrderGoods as $key => &$goods) {
  310. foreach ($goods as $k => &$goodsItem) {
  311. if ($goodsItem['activity_type'] == 2) {
  312. $this->goodsActivityService->cacheRecord($goodsItem['goods_id'], $goodsItem['number'], $userId);
  313. }
  314. }
  315. }
  316. Db::commit();
  317. if (!empty($receiveCouponIds)) {
  318. $this->couponService->orderUseCoupons($globalOrderId, $canRealUseCoupons);
  319. }
  320. // 清除购物车
  321. $this->shopCartUpdateService->doClear($userId, $marketId);
  322. // 记录badge
  323. $this->badgeService->doByOrder($userId, array_values(array_column($dataChildren, 'store_id')), $orderMain->global_order_id, OrderState::UNPAID);
  324. // 支付
  325. return $this->paymentService->do($globalOrderId, $totalAmount, $userId, config('wechat.notify_url.online'));
  326. } catch (Exception $e) {
  327. Db::rollBack();
  328. if ($isCacheInventory) {
  329. // 释redis库存
  330. foreach ($carts as $k => &$cart) {
  331. // 拼接activity_type和goods_id
  332. $inventoryKey = 'goods_inventory_sold_'.$cart->activity_type.'_'.$cart->goods_id;
  333. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  334. if (!$redis->exists($inventoryKey)) {
  335. $redis->set($inventoryKey, 0);
  336. } else {
  337. $redis->decrBy($inventoryKey, intval($cart->num));
  338. }
  339. }
  340. }
  341. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => $e->getMessage()]);
  342. $message = '';
  343. if ($e instanceof ErrorCodeException) {
  344. $message = $e->getMessage();
  345. }
  346. throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_FAIL, $message);
  347. }
  348. }
  349. public function check($globalOrderId, $userId, $state): Model
  350. {
  351. $builder = OrderMain::query()
  352. ->where(['global_order_id' => $globalOrderId, 'user_id' => $userId]);
  353. if (is_array($state)) {
  354. $builder = $builder->whereIn('state', $state);
  355. } else {
  356. $builder = $builder->where(['state' => $state]);
  357. }
  358. $orderMain = $builder->first();
  359. if (empty($orderMain)) {
  360. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  361. }
  362. return $orderMain;
  363. }
  364. /**
  365. * @inheritDoc
  366. */
  367. public function undo($globalOrderId, $userId)
  368. {
  369. Db::beginTransaction();
  370. try {
  371. // 订单待支付
  372. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  373. $orderMain->state = OrderState::CANCELED;
  374. if (!$orderMain->save()) {
  375. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  376. }
  377. // 退还优惠券
  378. $this->couponService->orderRefundCoupons($globalOrderId);
  379. // 撤销活动商品购买记录
  380. $orders = Order::query()->where(['order_main_id' => $globalOrderId])->get()->toArray();
  381. $orderGoods = OrderGoods::query()
  382. // ->where('activity_type', 2)
  383. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  384. ->get()
  385. ->toArray();
  386. foreach ($orderGoods as $key => &$goods) {
  387. if ($goods['activity_type'] == 2) {
  388. $this->goodsActivityService->clearCacheRecord($goods['goods_id'], $goods['number'], $orderMain['user_id']);
  389. }
  390. }
  391. Db::commit();
  392. // 释redis库存
  393. $redis = ApplicationContext::getContainer()->get(Redis::class);
  394. foreach ($orderGoods as $k => &$goodsItem) {
  395. // 拼接activity_type和goods_id
  396. $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  397. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  398. if (!$redis->exists($inventoryKey)) {
  399. $redis->set($inventoryKey, 0);
  400. } else {
  401. $redis->decrBy($inventoryKey, intval($goodsItem['number']));
  402. }
  403. }
  404. // 记录badge
  405. $orderChildIds = array_values(array_column($orders, 'store_id'));
  406. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::CANCELED);
  407. return true;
  408. } catch (Exception $e) {
  409. Db::rollBack();
  410. throw new ErrorCodeException(ErrorCode::ORDER_CANCEL_FAIL, $e->getMessage());
  411. }
  412. }
  413. public function detailByUser($globalOrderId, $userId)
  414. {
  415. $orderMain = OrderMain::with(['market'])->where(['global_order_id' => $globalOrderId])->first();
  416. $orders = Order::query()
  417. ->where(['order_main_id' => $globalOrderId, 'user_id' => $userId])
  418. ->with([
  419. 'orderGoods',
  420. 'store'
  421. ])
  422. ->get()->toArray();
  423. return ['order_main' => $orderMain, 'orders' => $orders];
  424. }
  425. /**
  426. * @inheritDoc
  427. */
  428. public function doByPaid($globalOrderId)
  429. {
  430. Db::beginTransaction();
  431. try {
  432. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  433. // 查询订单
  434. $orderMain = OrderMain::query()
  435. ->where(['global_order_id' => $globalOrderId,'type' => OrderType::ONLINE])
  436. ->first();
  437. // 修改订单、子订单状态
  438. $currentTime = time();
  439. $orderMain->state = OrderState::PAID;
  440. $orderMain->pay_time = $currentTime;
  441. $orderMain->save();;
  442. // 更新商品库存和销量
  443. $orders = Order::query()
  444. ->where(['order_main_id' => $globalOrderId])
  445. ->get()
  446. ->toArray();
  447. // 更新商户销量
  448. $upStoreScore = Store::query()
  449. ->whereIn('id', array_values(array_column($orders, 'store_id')))
  450. ->update(['sales' => Db::raw('sales+1')]);
  451. $orderGoods = OrderGoods::query()
  452. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  453. ->get()
  454. ->toArray();
  455. foreach ($orderGoods as $key => &$goodsItem) {
  456. if ($goodsItem['activity_type'] == 2) { # 活动商品
  457. $goods = GoodsActivity::find($goodsItem['goods_id']);
  458. } else {
  459. $goods = Goods::find($goodsItem['goods_id']);
  460. }
  461. $goods->inventory = $goods->inventory - $goodsItem['number'];
  462. $goods->sales = $goods->sales + $goodsItem['number'];
  463. $goods->save();
  464. // 商品月销
  465. if (!$ssdb->exec('exists', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_'.$goods->id)) {
  466. $ssdb->exec('set', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  467. } else {
  468. $ssdb->exec('incr', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  469. }
  470. }
  471. Db::commit();
  472. // 释redis库存
  473. $redis = ApplicationContext::getContainer()->get(Redis::class);
  474. foreach ($orderGoods as $k => &$goodsItem) {
  475. // 拼接activity_type和goods_id
  476. $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  477. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  478. if (!$redis->exists($inventoryKey)) {
  479. $redis->set($inventoryKey, 0);
  480. } else {
  481. $redis->decrBy($inventoryKey, intval($goodsItem['number']));
  482. }
  483. }
  484. // 月销流水
  485. $statistics = [];
  486. foreach ($orders as $key => &$order) {
  487. $statistics[] = [
  488. 'money' => $order['money'],
  489. 'user_id' => $order['user_id'],
  490. 'store_id' => $order['store_id'],
  491. 'market_id' => $orderMain->market_id,
  492. 'order_id' => $order['id'],
  493. ];
  494. // 商户月销
  495. if (!$ssdb->exec('exists', SsdbKeys::STORE_MONTH_SALES . date('Ym').'_' . $order['store_id'])) {
  496. $ssdb->exec('set', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  497. } else {
  498. $ssdb->exec('incr', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  499. }
  500. }
  501. if (is_array($statistics) && !empty($statistics)) {
  502. $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics);
  503. }
  504. return true;
  505. } catch (Exception $e) {
  506. $this->log->event(LogLabel::ORDER_ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
  507. Db::rollBack();
  508. return false;
  509. }
  510. }
  511. /**
  512. * @inheritDoc
  513. */
  514. public function doPay($globalOrderId, $userId)
  515. {
  516. // 订单待支付
  517. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  518. return $this->paymentService->do(
  519. $orderMain->global_order_id,
  520. $orderMain->money,
  521. $orderMain->user_id,
  522. config('wechat.notify_url.online')
  523. );
  524. }
  525. /**
  526. * @inheritDoc
  527. * @throws Exception
  528. */
  529. public function doDel($globalOrderId, $userId)
  530. {
  531. // 订单完成
  532. $orderMain = $this->check($globalOrderId, $userId, OrderState::CAN_DEL);
  533. if (!$orderMain->delete()) {
  534. throw new ErrorCodeException(ErrorCode::ORDER_DELETE_FAIL);
  535. }
  536. return true;
  537. }
  538. /**
  539. * @inheritDoc
  540. */
  541. public function doApplyRefund($globalOrderId, $userId)
  542. {
  543. // 未接单
  544. $orderMain = $this->check($globalOrderId, $userId, OrderState::PAID);
  545. $orderMain->state = OrderState::REFUNDING;
  546. if (!$orderMain->save()) {
  547. throw new ErrorCodeException(ErrorCode::ORDER_APPLY_REFUND_FAIL);
  548. }
  549. // 记录badge
  550. $orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
  551. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::REFUNDING);
  552. return true;
  553. }
  554. /**
  555. * @inheritDoc
  556. */
  557. public function doComplete($globalOrderId, $userId)
  558. {
  559. $orderMain = $this->check($globalOrderId, $userId, OrderState::RECEIVING);
  560. $orderMain->state = OrderState::COMPLETED;
  561. if (!$orderMain->save()) {
  562. throw new ErrorCodeException(ErrorCode::ORDER_COMPLETE_FAIL);
  563. }
  564. // 记录badge
  565. $orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
  566. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::COMPLETED);
  567. return true;
  568. }
  569. /**
  570. * @inheritDoc
  571. */
  572. public function doRefund($globalOrderId, $userId)
  573. {
  574. $orderMain = $this->check($globalOrderId, $userId, OrderState::REFUNDING);
  575. $orderIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('id');
  576. $orderGoods = OrderGoods::query()->whereIn('order_id', $orderIds)->get()->toArray();
  577. // 释redis库存
  578. $redis = ApplicationContext::getContainer()->get(Redis::class);
  579. foreach ($orderGoods as $k => &$goodsItem) {
  580. // 拼接activity_type和goods_id
  581. $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  582. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  583. if (!$redis->exists($inventoryKey)) {
  584. $redis->set($inventoryKey, 0);
  585. } else {
  586. $redis->decrBy($inventoryKey, intval($goodsItem['number']));
  587. }
  588. }
  589. // 微信退款
  590. if ($orderMain->pay_type == Payment::WECHAT) {
  591. return $this->paymentService->undo($orderMain->global_order_id, $userId);
  592. }
  593. }
  594. public function autoCancel()
  595. {
  596. try {
  597. $orderMains = OrderMain::query()
  598. ->where(['state' => OrderState::UNPAID, 'type' => OrderType::ONLINE])
  599. ->where('created_at', '<', time()-600)
  600. ->orderBy('created_at', 'asc')
  601. ->limit(100)
  602. ->get();
  603. foreach ($orderMains as $key => &$orderMain) {
  604. // 订单取消
  605. OrderMain::query()->where(['id' => $orderMain->id])->update(['state' => OrderState::CANCELED]);
  606. // 退还优惠券
  607. $this->couponService->orderRefundCoupons($orderMain->global_order_id);
  608. // 撤销活动商品购买记录
  609. $orders = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->get()->toArray();
  610. $orderGoods = OrderGoods::query()
  611. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  612. ->get()
  613. ->toArray();
  614. foreach ($orderGoods as $key => &$goods) {
  615. if ($goods['activity_type'] == 2) {
  616. $this->goodsActivityService->clearCacheRecord($goods['goods_id'], $goods['number'], $orderMain->user_id);
  617. }
  618. }
  619. // 释redis库存
  620. $redis = ApplicationContext::getContainer()->get(Redis::class);
  621. foreach ($orderGoods as $k => &$goodsItem) {
  622. // 拼接activity_type和goods_id
  623. $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  624. // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  625. if (!$redis->exists($inventoryKey)) {
  626. $redis->set($inventoryKey, 0);
  627. } else {
  628. $redis->decrBy($inventoryKey, intval($goodsItem['number']));
  629. }
  630. }
  631. // 记录badge
  632. $orderChildIds = array_values(array_column($orders, 'store_id'));
  633. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::CANCELED);
  634. }
  635. } catch (Exception $e) {
  636. $this->log->event(LogLabel::ORDER_AUTO_CANCEL_FAIL_LOG, ['message' => $e->getMessage()]);
  637. }
  638. }
  639. }