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.

588 lines
22 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
  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\SsdbKeys;
  10. use App\Exception\ErrorCodeException;
  11. use App\Model\v3\Coupon;
  12. use App\Model\v3\Goods;
  13. use App\Model\v3\GoodsActivity;
  14. use App\Model\v3\Order;
  15. use App\Model\v3\OrderGoods;
  16. use App\Model\v3\OrderMain;
  17. use App\Model\v3\OrderSalesStatistic;
  18. use App\Model\v3\ShoppingCart;
  19. use App\Model\v3\Store;
  20. use App\Service\v3\Interfaces\BadgeServiceInterface;
  21. use App\Service\v3\Interfaces\CouponRecServiceInterface;
  22. use App\Service\v3\Interfaces\CouponServiceInterface;
  23. use App\Service\v3\Interfaces\GoodsActivityServiceInterface;
  24. use App\Service\v3\Interfaces\GoodsServiceInterface;
  25. use App\Service\v3\Interfaces\InitialDeliveryServiceInterface;
  26. use App\Service\v3\Interfaces\PaymentServiceInterface;
  27. use App\Service\v3\Interfaces\ShopCartUpdateServiceInterface;
  28. use App\Service\v3\Interfaces\UserAddressServiceInterface;
  29. use App\TaskWorker\SSDBTask;
  30. use Exception;
  31. use Hyperf\Database\Model\Model;
  32. use Hyperf\DbConnection\Db;
  33. use Hyperf\Di\Annotation\Inject;
  34. use App\Service\v3\Interfaces\OrderOnlineServiceInterface;
  35. use Hyperf\Snowflake\IdGeneratorInterface;
  36. use Hyperf\Utils\ApplicationContext;
  37. class OrderOnlineService implements OrderOnlineServiceInterface
  38. {
  39. /**
  40. * @Inject
  41. * @var Log
  42. */
  43. protected $log;
  44. /**
  45. * @Inject
  46. * @var UserAddressServiceInterface
  47. */
  48. protected $userAddressService;
  49. /**
  50. * @Inject
  51. * @var CouponRecServiceInterface
  52. */
  53. protected $couponRecService;
  54. /**
  55. * @Inject
  56. * @var CouponServiceInterface
  57. */
  58. protected $couponService;
  59. /**
  60. * @Inject
  61. * @var GoodsActivityServiceInterface
  62. */
  63. protected $goodsActivityService;
  64. /**
  65. * @Inject
  66. * @var GoodsServiceInterface
  67. */
  68. protected $goodsService;
  69. /**
  70. * @Inject
  71. * @var PaymentServiceInterface
  72. */
  73. protected $paymentService;
  74. /**
  75. * @Inject
  76. * @var ShopCartUpdateServiceInterface
  77. */
  78. protected $shopCartUpdateService;
  79. /**
  80. * @Inject
  81. * @var BadgeServiceInterface
  82. */
  83. protected $badgeService;
  84. /**
  85. * @Inject
  86. * @var InitialDeliveryServiceInterface
  87. */
  88. protected $initialDeliveryService;
  89. /**
  90. * 下单
  91. * @param $marketId
  92. * @param $userId
  93. * @param $userAddrId
  94. * @param $storeList
  95. * @param $totalMoney
  96. * @param string $deliveryTimeNote
  97. * @param int $serviceMoney
  98. * @param null $receiveCouponIds
  99. * @param string $plat
  100. * @return array[]
  101. */
  102. public function do($marketId, $userId, $userAddrId, $storeList, $totalMoney, $deliveryTimeNote='尽快送达', $serviceMoney=0, $receiveCouponIds=null, $plat=''){
  103. Db::beginTransaction();
  104. try {
  105. $currentTime = time();
  106. bcscale(6);
  107. // 用户收货地址
  108. // 获取配送费用
  109. $userAddrAndDPrice = $this->userAddressService->getAddressAndDistributionPrice($userAddrId, $marketId);
  110. $userAddr = $userAddrAndDPrice['address']['address'];
  111. $deliveryAmount = $userAddrAndDPrice['distribution_price'];
  112. $deliveryDistance = $userAddrAndDPrice['delivery_distance'];
  113. // 优惠券数据,当前订单可用个优惠券
  114. $couponRecs = $this->couponRecService->allForOnlineOrderAvailable($userId, $marketId);
  115. $canRealUseCoupons = $couponRecs['available'];
  116. $canRealUseCouponRecIds = array_values(array_column($canRealUseCoupons, 'id'));
  117. if (!empty(array_diff($receiveCouponIds, $canRealUseCouponRecIds))) {
  118. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => '订单中有不能使用优惠券的商品', 'data' => json_encode([
  119. 'all_user_coupons_rec' => json_encode($couponRecs),
  120. 'can_real_user_coupons' => json_encode($canRealUseCoupons),
  121. 'receive_coupon_ids' => json_encode($canRealUseCouponRecIds),
  122. ])]);
  123. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_CANNOT_USE_COUPON);
  124. }
  125. // 处理购物车数据,计算订单金额、子订单数据处理等
  126. $totalAmount = 0; # 实付金额
  127. $orderAmount = 0; # 订单金额
  128. $dataMain = []; # 主订单
  129. $dataChildren = []; # 子订单
  130. $dataOrderGoods = []; # 订单商品
  131. $storeTypeIds = []; # 订单中的商户类型,用于校验红包
  132. foreach ($storeList as $key => &$storeItem) {
  133. $storeId = $storeItem->store_id;
  134. // 子订单金额
  135. $subAmount = 0;
  136. // 店铺分类
  137. $storeType = Store::query()->where(['id' => $storeId])->value('category_id');
  138. $storeTypeIds[] = (string)$storeType;
  139. // 店铺今天的订单数
  140. $count = Order::query()
  141. ->join('lanzu_order_main as main', 'main.id', '=', 'lanzu_order.order_main_id')
  142. ->where(['lanzu_order.store_id' => $storeId, 'main.type' => OrderType::ONLINE])
  143. ->whereBetween('lanzu_order.created_at', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))])
  144. ->count();
  145. // 用户购物车数据
  146. $cartIds = explode(',', $storeItem->cart_ids);
  147. $carts = ShoppingCart::query()->whereIn('id', $cartIds)->where(['market_id' => $marketId, 'user_id' => $userId])->get();
  148. foreach ($carts as $k => &$cart) {
  149. // 查个商品,做商品有效的判断检查
  150. $goods = [];
  151. if ($cart->activity_type == 1) {
  152. $goods = Goods::query()->lockForUpdate()->with('store')->find($cart->goods_id);
  153. if (empty($goods)) {
  154. throw new ErrorCodeException(ErrorCode::GOODS_NOT_EXISTS, '['.$cart->goods_id.']');
  155. }
  156. $check = $this->goodsService->check($goods, $cart->num);
  157. if (true !== $check) {
  158. throw new ErrorCodeException($check, '['.$goods->name.'/'.$goods->goods_unit.']');
  159. }
  160. } elseif ($cart->activity_type == 2) {
  161. $goods = GoodsActivity::query()->lockForUpdate()->with('store')->find($cart->goods_id);
  162. if (empty($goods)) {
  163. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_NOT_EXISTS, '['.$cart->goods_id.']');
  164. }
  165. $check = $this->goodsActivityService->check($goods, $cart->num, $userId);
  166. if (true !== $check) {
  167. throw new ErrorCodeException($check, '['.$goods->name.'/'.$goods->goods_unit.']');
  168. }
  169. }
  170. // 算金额
  171. $goodsAmount = bcmul((string)$goods->price, (string)$cart->num); # 当前商品的金额
  172. $subAmount = bcadd((string)$subAmount, (string)$goodsAmount); # 当前店铺子订单的金额
  173. // 订单商品数据
  174. $dataOrderGoods[$storeId][] = [
  175. 'order_id' => 0,
  176. 'goods_id' => $cart->goods_id,
  177. 'activity_type' => $cart->activity_type,
  178. 'number' => $cart->num,
  179. 'price' => $goods->price,
  180. 'original_price' => $goods->original_price,
  181. 'vip_price' => $goods->vip_price,
  182. 'name' => $goods->name,
  183. 'goods_unit' => $goods->goods_unit,
  184. 'cover_img' => $goods->cover_img,
  185. 'spec' => json_encode($goods->spec),
  186. ];
  187. }
  188. // 子订单数据
  189. $dataChildren[] = [
  190. 'order_main_id' => 0,
  191. 'user_id' => $userId,
  192. 'store_id' => $storeId,
  193. 'money' => bcadd((string)$subAmount, '0', 2),
  194. 'oid' => $count + 1,
  195. 'order_num' => date('YmdHis').mt_rand(1000, 9999),
  196. 'note' => $storeItem->note
  197. ];
  198. // 订单金额
  199. $orderAmount = bcadd((string)$orderAmount, (string)$subAmount);
  200. }
  201. // 优惠券的使用
  202. $couponMoney = 0;
  203. if (!empty($receiveCouponIds)) {
  204. // 计算红包折扣金额
  205. foreach ($canRealUseCoupons as $key => &$coupon) {
  206. if (!in_array($coupon['id'], $receiveCouponIds)) {
  207. unset($coupon);
  208. continue;
  209. }
  210. if ($coupon['coupon']['discount_type'] == Coupon::DISCOUNT_TYPE_CASH) {
  211. $couponMoney = bcadd($couponMoney, $coupon['coupon']['discounts'], 2);
  212. } elseif ($coupon['coupon']['discount_type'] == Coupon::DISCOUNT_TYPE_RATE) {
  213. $discountRate = bcdiv($coupon['coupon']['discounts'],10);
  214. $discountRate = bcsub(1,$discountRate);
  215. $discountMoney = bcmul($orderAmount, $discountRate);
  216. $couponMoney = bcadd($couponMoney, $discountMoney, 2);
  217. }
  218. }
  219. }
  220. // 获取分布式全局ID
  221. $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
  222. $globalOrderId = $generator->generate();
  223. $orderAmount = bcadd((string)$orderAmount, '0', 2);
  224. $totalAmount = bcadd((string)$totalAmount, (string)$orderAmount);
  225. $totalAmount = bcadd((string)$totalAmount, (string)$deliveryAmount);
  226. $totalAmount = bcadd((string)$totalAmount, (string)$serviceMoney);
  227. $totalAmount = bcsub((string)$totalAmount, (string)$couponMoney, 2);
  228. // 校验订单总金额
  229. if ($totalAmount != $totalMoney) {
  230. throw new ErrorCodeException(ErrorCode::ORDER_TOTAL_AMOUNT_ERROR);
  231. }
  232. // 校验订单总金额是否满足起送
  233. $initDeliveryAmount = $this->initialDeliveryService->get();
  234. if ($orderAmount < $initDeliveryAmount) {
  235. throw new ErrorCodeException(ErrorCode::ORDER_NOT_ENOUGH_INITIAL_DELIVERY, "[{$initDeliveryAmount}]");
  236. }
  237. $dataMain = [
  238. 'market_id' => $marketId,
  239. 'order_num' => $globalOrderId,
  240. 'global_order_id' => $globalOrderId,
  241. 'user_id' => $userId,
  242. 'type' => OrderType::ONLINE,
  243. 'money' => $totalAmount,
  244. 'total_money' => $orderAmount,
  245. 'services_money' => $serviceMoney,
  246. 'coupon_money' => $couponMoney,
  247. 'delivery_money' => $deliveryAmount,
  248. 'delivery_distance' => $deliveryDistance,
  249. 'state' => OrderState::UNPAID,
  250. 'tel' => $userAddr->tel,
  251. 'address' => $userAddr->address.$userAddr->doorplate,
  252. 'lat' => $userAddr->lat,
  253. 'lng' => $userAddr->lng,
  254. 'name' => $userAddr->user_name,
  255. 'plat' => $plat,
  256. 'delivery_time_note' => $deliveryTimeNote
  257. ];
  258. // 生成主订单
  259. $orderMain = OrderMain::query()->create($dataMain);
  260. // 处理子订单
  261. foreach ($dataChildren as $key => &$child) {
  262. $child['order_main_id'] = $globalOrderId;
  263. $orderChild = Order::query()->create($child);
  264. $orderChildId = $orderChild->id;
  265. foreach ($dataOrderGoods[$child['store_id']] as $k => &$orderGoods) {
  266. $orderGoods['order_id'] = $orderChildId;
  267. $orderGoods['created_at'] = $currentTime;
  268. $orderGoods['updated_at'] = $currentTime;
  269. }
  270. OrderGoods::query()->insert($dataOrderGoods[$child['store_id']]);
  271. }
  272. // 判断是否有购买多个特价商品
  273. $check = $this->goodsActivityService->checkOrderActivityCount($dataOrderGoods);
  274. if(!$check){
  275. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => '订单中有活动商品超过限购数量', 'data' => json_encode($dataOrderGoods)]);
  276. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_RESTRICT_LIMIT);
  277. }
  278. // 订单成功,做一些处理
  279. // 活动商品购买记录
  280. foreach ($dataOrderGoods as $key => &$goods) {
  281. foreach ($goods as $k => &$goodsItem)
  282. if ($goodsItem['activity_type'] == 2) {
  283. $this->goodsActivityService->cacheRecord($goodsItem['goods_id'], $goodsItem['number'], $userId);
  284. }
  285. }
  286. // 优惠券红包使用记录
  287. $this->couponService->orderUseCoupons($globalOrderId, $canRealUseCoupons);
  288. Db::commit();
  289. // 清除购物车
  290. $this->shopCartUpdateService->doClear($userId, $marketId);
  291. // 记录badge
  292. $this->badgeService->doByOrder($userId, array_values(array_column($dataChildren, 'store_id')), $orderMain->global_order_id, OrderState::UNPAID);
  293. // 支付
  294. return $this->paymentService->do($globalOrderId, $totalAmount, $userId, config('wechat.notify_url.online'));
  295. } catch (Exception $e) {
  296. Db::rollBack();
  297. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => $e->getMessage()]);
  298. throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_FAIL, $e->getMessage());
  299. }
  300. }
  301. public function check($globalOrderId, $userId, $state): Model
  302. {
  303. $builder = OrderMain::query()
  304. ->where(['global_order_id' => $globalOrderId, 'user_id' => $userId]);
  305. if (is_array($state)) {
  306. $builder = $builder->whereIn('state', $state);
  307. } else {
  308. $builder = $builder->where(['state' => $state]);
  309. }
  310. $orderMain = $builder->first();
  311. if (empty($orderMain)) {
  312. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  313. }
  314. return $orderMain;
  315. }
  316. /**
  317. * @inheritDoc
  318. */
  319. public function undo($globalOrderId, $userId)
  320. {
  321. Db::beginTransaction();
  322. try {
  323. // 订单待支付
  324. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  325. $orderMain->state = OrderState::CANCELED;
  326. if (!$orderMain->save()) {
  327. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  328. }
  329. // 退还优惠券
  330. $this->couponService->orderRefundCoupons($globalOrderId);
  331. // 撤销活动商品购买记录
  332. $orders = Order::query()->where(['order_main_id' => $globalOrderId])->get()->toArray();
  333. $orderGoods = OrderGoods::query()
  334. ->where('activity_type', 2)
  335. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  336. ->get();
  337. foreach ($orderGoods as $key => &$goods) {
  338. $this->goodsActivityService->clearCacheRecord($goods->goods_id, $goods->number, $orderMain->user_id);
  339. }
  340. Db::commit();
  341. // 记录badge
  342. $orderChildIds = array_values(array_column($orders, 'store_id'));
  343. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::CANCELED);
  344. return true;
  345. } catch (Exception $e) {
  346. Db::rollBack();
  347. throw new ErrorCodeException(ErrorCode::ORDER_CANCEL_FAIL, $e->getMessage());
  348. }
  349. }
  350. public function detailByUser($globalOrderId, $userId)
  351. {
  352. $orderMain = OrderMain::with(['market'])->where(['global_order_id' => $globalOrderId])->first();
  353. $orders = Order::query()
  354. ->where(['order_main_id' => $globalOrderId, 'user_id' => $userId])
  355. ->with([
  356. 'orderGoods',
  357. 'store'
  358. ])
  359. ->get()->toArray();
  360. return ['order_main' => $orderMain, 'orders' => $orders];
  361. }
  362. /**
  363. * @inheritDoc
  364. */
  365. public function doByPaid($globalOrderId)
  366. {
  367. Db::beginTransaction();
  368. try {
  369. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  370. // 查询订单
  371. $orderMain = OrderMain::query()
  372. ->where(['global_order_id' => $globalOrderId,'type' => OrderType::ONLINE])
  373. ->first();
  374. // 修改订单、子订单状态
  375. $currentTime = time();
  376. $orderMain->state = OrderState::PAID;
  377. $orderMain->pay_time = $currentTime;
  378. $orderMain->save();;
  379. // 更新商品库存和销量
  380. $orders = Order::query()
  381. ->where(['order_main_id' => $globalOrderId])
  382. ->get()
  383. ->toArray();
  384. // 更新商户销量
  385. $upStoreScore = Store::query()
  386. ->whereIn('id', array_values(array_column($orders, 'store_id')))
  387. ->update(['sales' => Db::raw('sales+1')]);
  388. $orderGoods = OrderGoods::query()
  389. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  390. ->get()
  391. ->toArray();
  392. foreach ($orderGoods as $key => &$goodsItem) {
  393. if ($goodsItem['activity_type'] == 2) { # 活动商品
  394. $goods = GoodsActivity::find($goodsItem['goods_id']);
  395. } else {
  396. $goods = Goods::find($goodsItem['goods_id']);
  397. }
  398. $goods->inventory = $goods->inventory - $goodsItem['number'];
  399. $goods->sales = $goods->sales + $goodsItem['number'];
  400. $goods->save();
  401. // 商品月销
  402. if (!$ssdb->exec('exists', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_'.$goods->id)) {
  403. $ssdb->exec('set', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  404. } else {
  405. $ssdb->exec('incr', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  406. }
  407. }
  408. Db::commit();
  409. // 月销流水
  410. $statistics = [];
  411. foreach ($orders as $key => &$order) {
  412. $statistics[] = [
  413. 'money' => $order['money'],
  414. 'user_id' => $order['user_id'],
  415. 'store_id' => $order['store_id'],
  416. 'market_id' => $orderMain->market_id,
  417. 'order_id' => $order['id'],
  418. ];
  419. // 商户月销
  420. if (!$ssdb->exec('exists', SsdbKeys::STORE_MONTH_SALES . date('Ym').'_' . $order['store_id'])) {
  421. $ssdb->exec('set', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  422. } else {
  423. $ssdb->exec('incr', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  424. }
  425. }
  426. if (is_array($statistics) && !empty($statistics)) {
  427. $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics);
  428. }
  429. return true;
  430. } catch (Exception $e) {
  431. $this->log->event(LogLabel::ORDER_ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
  432. Db::rollBack();
  433. return false;
  434. }
  435. }
  436. /**
  437. * @inheritDoc
  438. */
  439. public function doPay($globalOrderId, $userId)
  440. {
  441. // 订单待支付
  442. $orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
  443. return $this->paymentService->do(
  444. $orderMain->global_order_id,
  445. $orderMain->money,
  446. $orderMain->user_id,
  447. config('wechat.notify_url.online')
  448. );
  449. }
  450. /**
  451. * @inheritDoc
  452. * @throws Exception
  453. */
  454. public function doDel($globalOrderId, $userId)
  455. {
  456. // 订单完成
  457. $orderMain = $this->check($globalOrderId, $userId, OrderState::CAN_DEL);
  458. if (!$orderMain->delete()) {
  459. throw new ErrorCodeException(ErrorCode::ORDER_DELETE_FAIL);
  460. }
  461. return true;
  462. }
  463. /**
  464. * @inheritDoc
  465. */
  466. public function doApplyRefund($globalOrderId, $userId)
  467. {
  468. // 未接单
  469. $orderMain = $this->check($globalOrderId, $userId, OrderState::PAID);
  470. $orderMain->state = OrderState::REFUNDING;
  471. if (!$orderMain->save()) {
  472. throw new ErrorCodeException(ErrorCode::ORDER_APPLY_REFUND_FAIL);
  473. }
  474. // 记录badge
  475. $orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
  476. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::REFUNDING);
  477. return true;
  478. }
  479. /**
  480. * @inheritDoc
  481. */
  482. public function doComplete($globalOrderId, $userId)
  483. {
  484. $orderMain = $this->check($globalOrderId, $userId, OrderState::RECEIVING);
  485. $orderMain->state = OrderState::COMPLETED;
  486. if (!$orderMain->save()) {
  487. throw new ErrorCodeException(ErrorCode::ORDER_COMPLETE_FAIL);
  488. }
  489. // 记录badge
  490. $orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
  491. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::COMPLETED);
  492. return true;
  493. }
  494. /**
  495. * @inheritDoc
  496. */
  497. public function doRefund($globalOrderId, $userId)
  498. {
  499. $orderMain = $this->check($globalOrderId, $userId, OrderState::REFUNDING);
  500. // 微信退款
  501. if ($orderMain->pay_type == Payment::WECHAT) {
  502. return $this->paymentService->undo($orderMain->global_order_id, $userId);
  503. }
  504. }
  505. }