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.

872 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
  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. $discountMoney = bcmul($orderAmount, $discountRate, 2);
  306. $couponMoney = bcsub($orderAmount, $discountMoney, 2);
  307. // $discountRate = bcdiv($coupon->coupon->discounts,10);
  308. // $discountRate = bcsub(1,$discountRate);
  309. // $discountMoney = bcmul($orderAmount, $discountRate);
  310. // $couponMoney = bcadd($couponMoney, $discountMoney, 2);
  311. }
  312. }
  313. }
  314. $orderAmount = bcadd((string)$orderAmount, '0', 2);
  315. $totalAmount = bcadd((string)$totalAmount, (string)$orderAmount);
  316. if ($shippingType != Shipping::TYPE_SELF_TAKE) {
  317. $totalAmount = bcadd((string)$totalAmount, (string)$deliveryAmount);
  318. }
  319. $totalAmount = bcadd((string)$totalAmount, (string)$serviceMoney);
  320. $totalAmount = bcsub((string)$totalAmount, (string)$couponMoney, 2);
  321. // 校验订单总金额
  322. if ($totalAmount != $totalMoney) {
  323. throw new ErrorCodeException(
  324. ErrorCode::ORDER_TOTAL_AMOUNT_ERROR,
  325. '',
  326. [
  327. 'total_amount' => $totalAmount,
  328. 'total_money' => $totalMoney,
  329. 'deliveryAmount' => $deliveryAmount,
  330. '$orderAmount' => $orderAmount,
  331. 'serviceMoney' => $serviceMoney,
  332. 'couponMoney' => $couponMoney,
  333. ]
  334. );
  335. }
  336. // 校验订单总金额是否满足起送
  337. $initDeliveryAmount = $this->initialDeliveryService->get();
  338. if ($orderAmount < $initDeliveryAmount) {
  339. throw new ErrorCodeException(ErrorCode::ORDER_NOT_ENOUGH_INITIAL_DELIVERY, "[{$initDeliveryAmount}]");
  340. }
  341. $dataMain = [
  342. 'shipping_type' => $shippingType,
  343. 'market_id' => $marketId,
  344. 'order_num' => $globalOrderId,
  345. 'global_order_id' => $globalOrderId,
  346. 'user_id' => $userId,
  347. 'type' => OrderType::ONLINE,
  348. 'money' => $totalAmount,
  349. 'total_money' => $orderAmount,
  350. 'services_money' => $serviceMoney,
  351. 'coupon_money' => $couponMoney,
  352. 'delivery_money' => $deliveryAmount,
  353. 'delivery_distance' => $deliveryDistance,
  354. 'state' => OrderState::UNPAID,
  355. 'tel' => $userAddr->tel ?? '',
  356. 'address' => ($userAddr->address ?? '').($userAddr->doorplate ?? ''),
  357. 'lat' => $userAddr->lat ?? '',
  358. 'lng' => $userAddr->lng ?? '',
  359. 'name' => $userAddr->user_name ?? '',
  360. 'plat' => $plat,
  361. 'delivery_time_note' => $deliveryTimeNote
  362. ];
  363. // 生成主订单
  364. $orderMain = OrderMain::query()->create($dataMain);
  365. // 处理子订单
  366. foreach ($dataChildren as $key => &$child) {
  367. $child['order_main_id'] = $globalOrderId;
  368. $orderChild = Order::query()->create($child);
  369. $orderChildId = $orderChild->id;
  370. foreach ($dataOrderGoods[$child['store_id']] as $k => &$orderGoods) {
  371. $orderGoods['order_id'] = $orderChildId;
  372. $orderGoods['created_at'] = $currentTime;
  373. $orderGoods['updated_at'] = $currentTime;
  374. }
  375. OrderGoods::query()->insert($dataOrderGoods[$child['store_id']]);
  376. }
  377. // 判断是否有购买多个特价商品
  378. $check = $this->goodsActivityService->checkOrderActivityCount($activityGoodsIds);
  379. if(!$check){
  380. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => '同一订单中有活动商品不可同时购买多款', 'data' => json_encode($dataOrderGoods)]);
  381. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_RESTRICT_LIMIT);
  382. }
  383. // 订单成功,做一些处理
  384. // 活动商品购买记录
  385. foreach ($dataOrderGoods as $key => &$goods) {
  386. foreach ($goods as $k => &$goodsItem) {
  387. if ($goodsItem['activity_type'] == 2) {
  388. $this->goodsActivityService->cacheRecord($goodsItem['goods_id'], $goodsItem['number'], $userId);
  389. }
  390. }
  391. }
  392. Db::commit();
  393. if (!empty($receiveCouponIds)) {
  394. $this->couponService->orderUseCoupons($globalOrderId, $canRealUseCoupons);
  395. }
  396. // 清除购物车
  397. $this->shopCartUpdateService->doClear($userId, $marketId, $shopcartIds);
  398. // 记录badge
  399. $this->badgeService->doByOrder($userId, array_values(array_column($dataChildren, 'store_id')), $orderMain->global_order_id, OrderState::UNPAID);
  400. // 支付
  401. return $this->paymentService->do($globalOrderId, $totalAmount, $userId, config('wechat.notify_url.online'));
  402. } catch (Exception $e) {
  403. Db::rollBack();
  404. if ($isCacheInventory) {
  405. // 释redis库存
  406. foreach ($carts as $k => &$cart) {
  407. // // 拼接activity_type和goods_id
  408. // $inventoryKey = 'goods_inventory_sold_'.$cart->activity_type.'_'.$cart->goods_id;
  409. // // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  410. // if (!$redis->exists($inventoryKey)) {
  411. // $redis->set($inventoryKey, 0);
  412. // } else {
  413. // $redis->decrBy($inventoryKey, intval($cart->num));
  414. // }
  415. $this->goodsInventoryService->undoSold($cart->activity_type, $cart->goods_id, $cart->num);
  416. }
  417. }
  418. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => $e->getMessage()]);
  419. $message = '';
  420. if ($e instanceof ErrorCodeException) {
  421. $message = $e->getMessage();
  422. }
  423. throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_FAIL, $message);
  424. }
  425. }
  426. public function check($globalOrderId, $userId, $state): Model
  427. {
  428. $builder = OrderMain::query()
  429. ->where(['global_order_id' => $globalOrderId, 'user_id' => $userId]);
  430. if (is_array($state)) {
  431. $builder = $builder->whereIn('state', $state);
  432. } else {
  433. $builder = $builder->where(['state' => $state]);
  434. }
  435. $orderMain = $builder->first();
  436. if (empty($orderMain)) {
  437. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  438. }
  439. return $orderMain;
  440. }
  441. /**
  442. * @inheritDoc
  443. */
  444. public function undo($globalOrderId, $userId)
  445. {
  446. Db::beginTransaction();
  447. try {
  448. // 订单待支付
  449. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  450. $orderMain->state = OrderState::CANCELED;
  451. if (!$orderMain->save()) {
  452. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  453. }
  454. // 退还优惠券
  455. $this->couponService->orderRefundCoupons($globalOrderId);
  456. // 撤销活动商品购买记录
  457. $orders = Order::query()->where(['order_main_id' => $globalOrderId])->get()->toArray();
  458. $orderGoods = OrderGoods::query()
  459. // ->where('activity_type', 2)
  460. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  461. ->get()
  462. ->toArray();
  463. foreach ($orderGoods as $key => &$goods) {
  464. if ($goods['activity_type'] == 2) {
  465. $this->goodsActivityService->clearCacheRecord($goods['goods_id'], $goods['number'], $orderMain['user_id']);
  466. }
  467. }
  468. Db::commit();
  469. // 释redis库存
  470. $redis = ApplicationContext::getContainer()->get(Redis::class);
  471. foreach ($orderGoods as $k => &$goodsItem) {
  472. // // 拼接activity_type和goods_id
  473. // $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  474. // // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  475. // if (!$redis->exists($inventoryKey)) {
  476. // $redis->set($inventoryKey, 0);
  477. // } else {
  478. // $redis->decrBy($inventoryKey, intval($goodsItem['number']));
  479. // }
  480. $this->goodsInventoryService->undoSold($goodsItem['activity_type'], $goodsItem['goods_id'], $goodsItem['number']);
  481. }
  482. // 记录badge
  483. $orderChildIds = array_values(array_column($orders, 'store_id'));
  484. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::CANCELED);
  485. return true;
  486. } catch (Exception $e) {
  487. Db::rollBack();
  488. throw new ErrorCodeException(ErrorCode::ORDER_CANCEL_FAIL, $e->getMessage());
  489. }
  490. }
  491. public function detailByUser($globalOrderId, $userId)
  492. {
  493. //主订单
  494. $orderMain = OrderMain::with(['market'])->where(['global_order_id' => $globalOrderId])->first();
  495. //子订单
  496. $orders = Order::query()
  497. ->where(['order_main_id' => $globalOrderId, 'user_id' => $userId])
  498. ->with([
  499. 'orderGoods',
  500. 'store'
  501. ])
  502. ->get()->toArray();
  503. //配送人员信息
  504. if($orderMain->horseman_id > 0) {
  505. $employees = Employees::query()->where('id', $orderMain->horseman_id)->first();
  506. }else{
  507. $employees = null;
  508. }
  509. return ['order_main' => $orderMain, 'orders' => $orders,'employees' => $employees];
  510. }
  511. /**
  512. * @inheritDoc
  513. */
  514. public function doByPaid($globalOrderId)
  515. {
  516. Db::beginTransaction();
  517. try {
  518. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  519. // 查询订单
  520. $orderMain = OrderMain::query()
  521. ->where(['global_order_id' => $globalOrderId,'type' => OrderType::ONLINE])
  522. ->first();
  523. // 修改订单、子订单状态
  524. $currentTime = time();
  525. $orderMain->state = OrderState::PAID;
  526. $orderMain->pay_time = $currentTime;
  527. $orderMain->save();;
  528. // 更新商品库存和销量
  529. $orders = Order::query()
  530. ->where(['order_main_id' => $globalOrderId])
  531. ->get()
  532. ->toArray();
  533. // 更新商户销量
  534. $upStoreScore = Store::query()
  535. ->whereIn('id', array_values(array_column($orders, 'store_id')))
  536. ->update(['sales' => Db::raw('sales+1')]);
  537. $orderGoods = OrderGoods::query()
  538. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  539. ->get()
  540. ->toArray();
  541. foreach ($orderGoods as $key => &$goodsItem) {
  542. if ($goodsItem['activity_type'] == 2) { # 活动商品
  543. $goods = GoodsActivity::find($goodsItem['goods_id']);
  544. } else {
  545. $goods = Goods::find($goodsItem['goods_id']);
  546. }
  547. $goods->inventory = $goods->inventory - $goodsItem['number'];
  548. $goods->sales = $goods->sales + $goodsItem['number'];
  549. $goods->save();
  550. // 商品月销
  551. if (!$ssdb->exec('exists', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_'.$goods->id)) {
  552. $ssdb->exec('set', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  553. } else {
  554. $ssdb->exec('incr', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  555. }
  556. }
  557. Db::commit();
  558. // 释redis库存
  559. $redis = ApplicationContext::getContainer()->get(Redis::class);
  560. foreach ($orderGoods as $k => &$goodsItem) {
  561. // // 拼接activity_type和goods_id
  562. // $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  563. // // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  564. // if (!$redis->exists($inventoryKey)) {
  565. // $redis->set($inventoryKey, 0);
  566. // } else {
  567. // $redis->decrBy($inventoryKey, intval($goodsItem['number']));
  568. // }
  569. $this->goodsInventoryService->undoSold($goodsItem['activity_type'], $goodsItem['goods_id'], $goodsItem['number']);
  570. }
  571. // 月销流水
  572. $statistics = [];
  573. foreach ($orders as $key => &$order) {
  574. $statistics[] = [
  575. 'money' => $order['money'],
  576. 'user_id' => $order['user_id'],
  577. 'store_id' => $order['store_id'],
  578. 'market_id' => $orderMain->market_id,
  579. 'order_id' => $order['id'],
  580. ];
  581. // 商户月销
  582. if (!$ssdb->exec('exists', SsdbKeys::STORE_MONTH_SALES . date('Ym').'_' . $order['store_id'])) {
  583. $ssdb->exec('set', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  584. } else {
  585. $ssdb->exec('incr', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  586. }
  587. }
  588. if (is_array($statistics) && !empty($statistics)) {
  589. $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics);
  590. }
  591. return true;
  592. } catch (Exception $e) {
  593. $this->log->event(LogLabel::ORDER_ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
  594. Db::rollBack();
  595. return false;
  596. }
  597. }
  598. /**
  599. * @inheritDoc
  600. */
  601. public function doPay($globalOrderId, $userId)
  602. {
  603. // 订单待支付
  604. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  605. return $this->paymentService->do(
  606. $orderMain->global_order_id,
  607. $orderMain->money,
  608. $orderMain->user_id,
  609. config('wechat.notify_url.online')
  610. );
  611. }
  612. /**
  613. * @inheritDoc
  614. * @throws Exception
  615. */
  616. public function doDel($globalOrderId, $userId)
  617. {
  618. // 订单完成
  619. $orderMain = $this->check($globalOrderId, $userId, OrderState::CAN_DEL);
  620. if (!$orderMain->delete()) {
  621. throw new ErrorCodeException(ErrorCode::ORDER_DELETE_FAIL);
  622. }
  623. return true;
  624. }
  625. /**
  626. * @inheritDoc
  627. */
  628. public function doApplyRefund($globalOrderId, $userId)
  629. {
  630. // 未接单
  631. $orderMain = $this->check($globalOrderId, $userId, OrderState::PAID);
  632. $orderMain->state = OrderState::REFUNDING;
  633. if (!$orderMain->save()) {
  634. throw new ErrorCodeException(ErrorCode::ORDER_APPLY_REFUND_FAIL);
  635. }
  636. // 记录badge
  637. $orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
  638. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::REFUNDING);
  639. return true;
  640. }
  641. /**
  642. * @inheritDoc
  643. */
  644. public function doComplete($globalOrderId, $userId)
  645. {
  646. $orderMain = $this->check($globalOrderId, $userId, OrderState::RECEIVING);
  647. $orderMain->state = OrderState::COMPLETED;
  648. $orderMain->complete_time = time();
  649. if (!$orderMain->save()) {
  650. throw new ErrorCodeException(ErrorCode::ORDER_COMPLETE_FAIL);
  651. }
  652. // 记录badge
  653. $orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
  654. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::COMPLETED);
  655. return true;
  656. }
  657. /**
  658. * @inheritDoc
  659. */
  660. public function doRefund($globalOrderId, $userId)
  661. {
  662. $orderMain = $this->check($globalOrderId, $userId, OrderState::REFUNDING);
  663. $orderIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('id');
  664. $orderGoods = OrderGoods::query()->whereIn('order_id', $orderIds)->get()->toArray();
  665. // 微信退款
  666. if ($orderMain->pay_type == Payment::WECHAT) {
  667. return $this->paymentService->undo($orderMain->global_order_id, $userId);
  668. }
  669. }
  670. public function autoCancel()
  671. {
  672. try {
  673. $orderMains = OrderMain::query()
  674. ->where(['state' => OrderState::UNPAID, 'type' => OrderType::ONLINE])
  675. ->where('created_at', '<', time()-600)
  676. ->orderBy('created_at', 'asc')
  677. ->limit(100)
  678. ->get();
  679. foreach ($orderMains as $key => &$orderMain) {
  680. // 订单取消
  681. OrderMain::query()->where(['id' => $orderMain->id])->update(['state' => OrderState::CANCELED]);
  682. // 退还优惠券
  683. $this->couponService->orderRefundCoupons($orderMain->global_order_id);
  684. // 撤销活动商品购买记录
  685. $orders = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->get()->toArray();
  686. $orderGoods = OrderGoods::query()
  687. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  688. ->get()
  689. ->toArray();
  690. foreach ($orderGoods as $key => &$goods) {
  691. if ($goods['activity_type'] == 2) {
  692. $this->goodsActivityService->clearCacheRecord($goods['goods_id'], $goods['number'], $orderMain->user_id);
  693. }
  694. }
  695. // 释redis库存
  696. $redis = ApplicationContext::getContainer()->get(Redis::class);
  697. foreach ($orderGoods as $k => &$goodsItem) {
  698. // // 拼接activity_type和goods_id
  699. // $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
  700. // // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
  701. // if (!$redis->exists($inventoryKey)) {
  702. // $redis->set($inventoryKey, 0);
  703. // } else {
  704. // $redis->decrBy($inventoryKey, intval($goodsItem['number']));
  705. // }
  706. $this->goodsInventoryService->undoSold($goodsItem['activity_type'], $goodsItem['goods_id'], $goodsItem['number']);
  707. }
  708. // 记录badge
  709. $orderChildIds = array_values(array_column($orders, 'store_id'));
  710. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::CANCELED);
  711. }
  712. } catch (Exception $e) {
  713. $this->log->event(LogLabel::ORDER_AUTO_CANCEL_FAIL_LOG, ['message' => $e->getMessage()]);
  714. }
  715. }
  716. /**
  717. * 校验用户今天是否买过x单[y,z]分钱的活动商品
  718. * @param $userId
  719. */
  720. public function checkIfBuyFlashGoodsToday($userId)
  721. {
  722. $mainTable = ApplicationContext::getContainer()->get(OrderMain::class)->getTable();
  723. $orderTable = ApplicationContext::getContainer()->get(Order::class)->getTable();
  724. $goodsTable = ApplicationContext::getContainer()->get(OrderGoods::class)->getTable();
  725. $limitPrices = explode(',', env('LIMIT_BUY_COUNT_GOODS_PRICES'));
  726. $limitCount = intval(env('LIMIT_BUY_COUNT'));
  727. $countToday = OrderMain::query()
  728. ->join($orderTable, $orderTable.'.order_main_id', '=', $mainTable.'.global_order_id')
  729. ->join($goodsTable, $goodsTable.'.order_id', '=', $orderTable.'.id')
  730. ->where($mainTable.'.updated_at', '>=', strtotime(date('Y-m-d 00:00:00')))
  731. ->where($mainTable.'.updated_at', '<=', strtotime(date('Y-m-d 23:59:59')))
  732. ->where([$goodsTable.'.activity_type' => 2])
  733. ->whereIn($mainTable.'.state', OrderState::LIMIT_BUY_COUNT)
  734. ->where([$mainTable.'.user_id' => $userId])
  735. ->whereIn($goodsTable.'.price', $limitPrices)
  736. ->count();
  737. if ($countToday >= $limitCount) {
  738. return false;
  739. }
  740. return true;
  741. }
  742. public function getOrderInfo($globalOrderId)
  743. {
  744. return OrderMain::query()->where('global_order_id',$globalOrderId)->with('market','orderGoods')->first();
  745. }
  746. public function completeForHorseman($globalOrderId)
  747. {
  748. return true;
  749. }
  750. }