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.

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