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.

569 lines
22 KiB

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