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.

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