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.

554 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\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. // 支付
  289. return $this->paymentService->do($globalOrderId, $totalAmount, $userId, config('wechat.notify_url.online'));
  290. } catch (Exception $e) {
  291. Db::rollBack();
  292. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['exception_msg' => $e->getMessage()]);
  293. throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_FAIL, $e->getMessage());
  294. }
  295. }
  296. public function check($orderMainId, $userId, $state): Model
  297. {
  298. $builder = OrderMain::query()
  299. ->where(['id' => $orderMainId, 'user_id' => $userId]);
  300. if (is_array($state)) {
  301. $builder = $builder->whereIn('state', $state);
  302. } else {
  303. $builder = $builder->where(['state' => $state]);
  304. }
  305. $orderMain = $builder->first();
  306. if (empty($orderMain)) {
  307. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  308. }
  309. return $orderMain;
  310. }
  311. /**
  312. * @inheritDoc
  313. */
  314. public function undo($orderMainId, $userId)
  315. {
  316. Db::beginTransaction();
  317. try {
  318. // 订单待支付
  319. $orderMain = $this->check($orderMainId, $userId, OrderState::UNPAID);
  320. $orderMain->state = OrderState::CANCELED;
  321. if (!$orderMain->save()) {
  322. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  323. }
  324. // 退还优惠券
  325. $this->couponService->orderRefundCoupons($orderMainId);
  326. // 撤销活动商品购买记录
  327. $orders = Order::query()->where(['order_main_id' => $orderMainId])->get()->toArray();
  328. $orderGoods = OrderGoods::query()
  329. ->where('activity_type', 2)
  330. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  331. ->get();
  332. foreach ($orderGoods as $key => &$goods) {
  333. $this->goodsActivityService->clearCacheRecord($goods->goods_id, $goods->number, $orderMain->user_id);
  334. }
  335. Db::commit();
  336. return true;
  337. } catch (Exception $e) {
  338. Db::rollBack();
  339. throw new ErrorCodeException(ErrorCode::ORDER_CANCEL_FAIL, $e->getMessage());
  340. }
  341. }
  342. public function detailByUser($orderMainId, $userId)
  343. {
  344. $orderMain = OrderMain::with(['market'])->find($orderMainId);
  345. $orders = Order::query()
  346. ->where(['order_main_id' => $orderMainId, 'user_id' => $userId])
  347. ->with([
  348. 'orderGoods',
  349. 'store'
  350. ])
  351. ->get()->toArray();
  352. return ['order_main' => $orderMain, 'orders' => $orders];
  353. }
  354. /**
  355. * @inheritDoc
  356. */
  357. public function doByPaid($orderMainId)
  358. {
  359. Db::beginTransaction();
  360. try {
  361. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  362. // 查询订单
  363. $orderMain = OrderMain::query()
  364. ->where(['id' => $orderMainId,'type' => OrderType::ONLINE])
  365. ->first();
  366. // 修改订单、子订单状态
  367. $currentTime = time();
  368. $orderMain->state = OrderState::PAID;
  369. $orderMain->pay_time = $currentTime;
  370. $orderMain->save();;
  371. // 更新商品库存和销量
  372. $orders = Order::query()
  373. ->where(['order_main_id' => $orderMain->id])
  374. ->get()
  375. ->toArray();
  376. // 更新商户销量
  377. $upStoreScore = Store::query()
  378. ->whereIn('id', array_values(array_column($orders, 'store_id')))
  379. ->update(['sales' => Db::raw('sales+1')]);
  380. $orderGoods = OrderGoods::query()
  381. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  382. ->get()
  383. ->toArray();
  384. foreach ($orderGoods as $key => &$goodsItem) {
  385. if ($goodsItem['activity_type'] == 2) { # 活动商品
  386. $goods = GoodsActivity::find($goodsItem['goods_id']);
  387. } else {
  388. $goods = Goods::find($goodsItem['goods_id']);
  389. }
  390. $goods->inventory = $goods->inventory - $goodsItem['number'];
  391. $goods->sales = $goods->sales + $goodsItem['number'];
  392. $goods->save();
  393. // 商品月销
  394. if (!$ssdb->exec('exists', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_'.$goods->id)) {
  395. $ssdb->exec('set', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  396. } else {
  397. $ssdb->exec('incr', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  398. }
  399. }
  400. // 月销流水
  401. $statistics = [];
  402. foreach ($orders as $key => &$order) {
  403. $statistics[] = [
  404. 'money' => $order['money'],
  405. 'user_id' => $order['user_id'],
  406. 'store_id' => $order['store_id'],
  407. 'market_id' => $orderMain->market_id,
  408. 'order_id' => $order['id'],
  409. 'createtime' => $orderMain->pay_time,
  410. ];
  411. // 商户月销
  412. if (!$ssdb->exec('exists', SsdbKeys::STORE_MONTH_SALES . date('Ym').'_' . $order['store_id'])) {
  413. $ssdb->exec('set', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  414. } else {
  415. $ssdb->exec('incr', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  416. }
  417. }
  418. if (is_array($statistics) && !empty($statistics)) {
  419. $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics);
  420. }
  421. Db::commit();
  422. return true;
  423. } catch (Exception $e) {
  424. $this->log->event(LogLabel::ORDER_ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
  425. Db::rollBack();
  426. return false;
  427. }
  428. }
  429. /**
  430. * @inheritDoc
  431. */
  432. public function doPay($orderMainId, $userId)
  433. {
  434. // 订单待支付
  435. $orderMain = $this->check($orderMainId, $userId, OrderState::UNPAID);
  436. return $this->paymentService->do(
  437. $orderMain->global_order_id,
  438. $orderMain->money,
  439. $orderMain->user_id,
  440. config('wechat.notify_url.online')
  441. );
  442. }
  443. /**
  444. * @inheritDoc
  445. * @throws Exception
  446. */
  447. public function doDel($orderMainId, $userId)
  448. {
  449. // 订单完成
  450. $orderMain = $this->check($orderMainId, $userId, OrderState::CAN_DEL);
  451. if (!$orderMain->delete()) {
  452. throw new ErrorCodeException(ErrorCode::ORDER_DELETE_FAIL);
  453. }
  454. return true;
  455. }
  456. /**
  457. * @inheritDoc
  458. */
  459. public function doApplyRefund($orderMainId, $userId)
  460. {
  461. // 未接单
  462. $orderMain = $this->check($orderMainId, $userId, OrderState::PAID);
  463. $orderMain->state = OrderState::REFUNDING;
  464. if (!$orderMain->save()) {
  465. throw new ErrorCodeException(ErrorCode::ORDER_APPLY_REFUND_FAIL);
  466. }
  467. return true;
  468. }
  469. /**
  470. * @inheritDoc
  471. */
  472. public function doComplete($orderMainId, $userId)
  473. {
  474. $orderMain = $this->check($orderMainId, $userId, OrderState::RECEIVING);
  475. $orderMain->state = OrderState::COMPLETED;
  476. if (!$orderMain->save()) {
  477. throw new ErrorCodeException(ErrorCode::ORDER_COMPLETE_FAIL);
  478. }
  479. return true;
  480. }
  481. }