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.

984 lines
40 KiB

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