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.

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