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.

868 lines
35 KiB

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