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.

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