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.

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