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.

552 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. ->where(['store_id' => $storeId, 'type' => OrderType::ONLINE])
  121. ->whereBetween('created_at', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))])
  122. ->count();
  123. // 用户购物车数据
  124. $cartIds = explode(',', $storeItem->cart_ids);
  125. $carts = ShoppingCart::query()->whereIn('id', $cartIds)->where(['market_id' => $marketId, 'user_id' => $userId])->get();
  126. foreach ($carts as $k => &$cart) {
  127. // 查个商品
  128. $goods = [];
  129. if ($cart->activity_type == 1) {
  130. $goods = Goods::query()->lockForUpdate()->find($cart->goods_id);
  131. $check = $this->goodsService->check($goods->id, $cart->num);
  132. if (true !== $check) {
  133. throw new ErrorCodeException($check, '[商品失效1]'.$cart->goods_id);
  134. }
  135. } elseif ($cart->activity_type == 2) {
  136. $goods = GoodsActivity::query()->lockForUpdate()->find($cart->goods_id);
  137. $check = $this->goodsActivityService->check($goods->id, $cart->num, $userId);
  138. if (true !== $check) {
  139. throw new ErrorCodeException($check, '[商品失效2]'.$cart->goods_id);
  140. }
  141. // 活动商品不可用优惠券
  142. if ($goods->can_use_coupon!=1 && $receiveCouponIds) {
  143. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_CANNOT_USE_COUPON, '[商品失效]'.$cart->goods_id);
  144. }
  145. // 活动商品可用优惠券,再校验这些优惠券是不是可以在当前活动类型可用
  146. // receiveCouponIds中是不是有当前活动不可用的优惠券
  147. $couponIds = array_values(array_column($couponRec, 'coupon_id'));
  148. $couponsActivityAvailable = Coupon::query()
  149. ->select(['id'])
  150. ->whereJsonContains('activity_available', [(string)$goods->type])
  151. ->whereIn('id', $couponIds)
  152. ->get()->toArray();
  153. $couponsActivityAvailableIds = array_values(array_column($couponsActivityAvailable, 'id'));
  154. if (!empty(array_diff($couponIds, $couponsActivityAvailableIds))) {
  155. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_CANNOT_USE_COUPON, '[商品失效]'.json_encode($couponsActivityAvailableIds));
  156. }
  157. }
  158. if (empty($goods)) {
  159. throw new ErrorCodeException(ErrorCode::ORDER_GOODS_NOT_AVAILABLE);
  160. }
  161. // 库存判断
  162. if ($goods->is_infinite !=1 && $goods->inventory < $cart->num) {
  163. throw new ErrorCodeException(ErrorCode::ORDER_GOODS_INVENTORY_LIMIT);
  164. }
  165. // 算金额
  166. $goodsAmount = bcmul((string)$goods->price, (string)$cart->num); # 当前商品的金额
  167. $subAmount = bcadd((string)$subAmount, (string)$goodsAmount); # 当前店铺子订单的金额
  168. // 订单商品数据
  169. $dataOrderGoods[$storeId][] = [
  170. 'order_id' => 0,
  171. 'goods_id' => $cart->goods_id,
  172. 'activity_type' => $cart->activity_type,
  173. 'number' => $cart->num,
  174. 'price' => $goods->price,
  175. 'original_price' => $goods->original_price,
  176. 'vip_price' => $goods->vip_price,
  177. 'name' => $goods->name,
  178. 'goods_unit' => $goods->goods_unit,
  179. 'cover_img' => $goods->cover_img,
  180. 'spec' => $goods->spec,
  181. ];
  182. }
  183. // 子订单数据
  184. $dataChildren[] = [
  185. 'order_main_id' => 0,
  186. 'user_id' => $userId,
  187. 'store_id' => $storeId,
  188. 'money' => bcadd((string)$subAmount, '0', 2),
  189. 'oid' => $count + 1,
  190. 'order_num' => date('YmdHis').mt_rand(1000, 9999),
  191. 'note' => $storeItem->note
  192. ];
  193. // 订单金额
  194. $orderAmount = bcadd((string)$orderAmount, (string)$subAmount);
  195. }
  196. // 优惠券的使用
  197. $couponMoney = 0;
  198. if (!empty($couponRec)) {
  199. $couponsCanUse = $this->couponRecService->allForOrderOlAvailable($totalAmount, $userId, $marketId, 2, $storeTypeIds);
  200. $couponCanUseIds = array_column($couponsCanUse, 'id');
  201. $couponCanUseIds = array_intersect($couponCanUseIds, $receiveCouponIds);
  202. $couponCannotUseIds = array_diff($receiveCouponIds, $couponCanUseIds);
  203. if (empty($couponCanUseIds)||!empty($couponCannotUseIds)) {
  204. throw new ErrorCodeException(ErrorCode::COUPON_NOT_AVAILABLE);
  205. }
  206. // 计算红包折扣金额
  207. foreach ($couponsCanUse as $key => $coupon) {
  208. if (!in_array($coupon->id, $receiveCouponIds)) {
  209. continue;
  210. }
  211. if ($coupon->discount_type == Coupon::DISCOUNT_TYPE_CASH) {
  212. $couponMoney = bcadd($couponMoney, $coupon->discounts, 2);
  213. } elseif ($coupon->discount_type == Coupon::DISCOUNT_TYPE_RATE) {
  214. $discountRate = bcdiv($coupon->discounts,10);
  215. $discountRate = bcsub(1,$discountRate);
  216. $discountMoney = bcmul($orderAmount, $discountRate);
  217. $couponMoney = bcadd($couponMoney, $discountMoney, 2);
  218. }
  219. }
  220. }
  221. // 获取分布式全局ID
  222. $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
  223. $globalOrderId = $generator->generate();
  224. $orderAmount = bcadd((string)$orderAmount, '0', 2);
  225. $totalAmount = bcadd((string)$totalAmount, (string)$orderAmount);
  226. $totalAmount = bcadd((string)$totalAmount, (string)$deliveryAmount);
  227. $totalAmount = bcadd((string)$totalAmount, (string)$serviceMoney);
  228. $totalAmount = bcsub((string)$totalAmount, (string)$couponMoney, 2);
  229. // 校验订单总金额
  230. if ($totalAmount != $totalMoney) {
  231. throw new ErrorCodeException(ErrorCode::ORDER_TOTAL_AMOUNT_ERROR);
  232. }
  233. $dataMain = [
  234. 'market_id' => $marketId,
  235. 'order_num' => $globalOrderId,
  236. 'global_order_id' => $globalOrderId,
  237. 'user_id' => $userId,
  238. 'type' => OrderType::ONLINE,
  239. 'money' => $totalAmount,
  240. 'total_money' => $orderAmount,
  241. 'services_money' => $serviceMoney,
  242. 'coupon_money' => $couponMoney,
  243. 'delivery_money' => $deliveryAmount,
  244. 'state' => OrderState::UNPAID,
  245. 'tel' => $userAddr->tel,
  246. 'address' => $userAddr->address.$userAddr->doorplate,
  247. 'lat' => $userAddr->lat,
  248. 'lng' => $userAddr->lng,
  249. 'name' => $userAddr->user_name,
  250. 'plat' => $plat,
  251. 'delivery_time_note' => $deliveryTimeNote
  252. ];
  253. // 生成主订单
  254. $orderMain = OrderMain::query()->create($dataMain);
  255. $orderMainId = $orderMain->id;
  256. // 处理子订单
  257. foreach ($dataChildren as $key => &$child) {
  258. $child['order_main_id'] = $orderMainId;
  259. $orderChild = Order::query()->create($child);
  260. $orderChildId = $orderChild->id;
  261. foreach ($dataOrderGoods[$child['store_id']] as $k => &$orderGoods) {
  262. $orderGoods['order_id'] = $orderChildId;
  263. $orderGoods['created_at'] = $currentTime;
  264. $orderGoods['updated_at'] = $currentTime;
  265. }
  266. OrderGoods::query()->insert($dataOrderGoods[$child['store_id']]);
  267. }
  268. // 判断是否有购买多个特价商品
  269. $check = $this->goodsActivityService->checkOrderActivityCount($dataOrderGoods);
  270. if(!$check){
  271. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_RESTRICT_LIMIT, '[同一订单同种类型活动商品]'.json_encode($dataOrderGoods));
  272. }
  273. // 订单成功,做一些处理
  274. // 活动商品购买记录
  275. foreach ($dataOrderGoods as $key => &$goods) {
  276. foreach ($goods as $k => &$goodsItem)
  277. if ($goodsItem['activity_type'] == 2) {
  278. $this->goodsActivityService->cacheRecord($goodsItem['goods_id'], $goodsItem['number'], $userId);
  279. }
  280. }
  281. // 优惠券红包使用记录
  282. $this->couponService->orderUseCoupons($orderMainId, $couponRec);
  283. Db::commit();
  284. // 清除购物车
  285. $this->shopCartUpdateService->doClear($userId, $marketId);
  286. // 支付
  287. return $this->paymentService->do($globalOrderId, $totalAmount, $userId, config('wechat.notify_url.online'));
  288. } catch (Exception $e) {
  289. Db::rollBack();
  290. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['exception_msg' => $e->getMessage()]);
  291. throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_FAIL, $e->getMessage());
  292. }
  293. }
  294. public function check($orderMainId, $userId, $state): Model
  295. {
  296. $builder = OrderMain::query()
  297. ->where(['id' => $orderMainId, 'user_id' => $userId]);
  298. if (is_array($state)) {
  299. $builder = $builder->whereIn('state', $state);
  300. } else {
  301. $builder = $builder->where(['state' => $state]);
  302. }
  303. $orderMain = $builder->first();
  304. if (empty($orderMain)) {
  305. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  306. }
  307. return $orderMain;
  308. }
  309. /**
  310. * @inheritDoc
  311. */
  312. public function undo($orderMainId, $userId)
  313. {
  314. Db::beginTransaction();
  315. try {
  316. // 订单待支付
  317. $orderMain = $this->check($orderMainId, $userId, OrderState::UNPAID);
  318. $orderMain->state = OrderState::CANCELED;
  319. if (!$orderMain->save()) {
  320. throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
  321. }
  322. // 退还优惠券
  323. $this->couponService->orderRefundCoupons($orderMainId);
  324. // 撤销活动商品购买记录
  325. $orders = Order::query()->where(['order_main_id' => $orderMainId])->get()->toArray();
  326. $orderGoods = OrderGoods::query()
  327. ->where('activity_type', 2)
  328. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  329. ->get();
  330. foreach ($orderGoods as $key => &$goods) {
  331. $this->goodsActivityService->clearCacheRecord($goods->goods_id, $goods->number, $orderMain->user_id);
  332. }
  333. Db::commit();
  334. return true;
  335. } catch (Exception $e) {
  336. Db::rollBack();
  337. throw new ErrorCodeException(ErrorCode::ORDER_CANCEL_FAIL, $e->getMessage());
  338. }
  339. }
  340. public function detailByUser($orderMainId, $userId)
  341. {
  342. $orderMain = OrderMain::with(['market'])->find($orderMainId);
  343. $orders = Order::query()
  344. ->where(['order_main_id' => $orderMainId, 'user_id' => $userId])
  345. ->with([
  346. 'orderGoods',
  347. 'store'
  348. ])
  349. ->get()->toArray();
  350. return ['order_main' => $orderMain, 'orders' => $orders];
  351. }
  352. /**
  353. * @inheritDoc
  354. */
  355. public function doByPaid($orderMainId)
  356. {
  357. Db::beginTransaction();
  358. try {
  359. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  360. // 查询订单
  361. $orderMain = OrderMain::query()
  362. ->where(['id' => $orderMainId,'type' => OrderType::ONLINE])
  363. ->first();
  364. // 修改订单、子订单状态
  365. $currentTime = time();
  366. $orderMain->state = OrderState::PAID;
  367. $orderMain->pay_time = $currentTime;
  368. $orderMain->save();;
  369. // 更新商品库存和销量
  370. $orders = Order::query()
  371. ->where(['order_main_id' => $orderMain->id])
  372. ->get()
  373. ->toArray();
  374. // 更新商户销量
  375. $upStoreScore = Store::query()
  376. ->whereIn('id', array_values(array_column($orders, 'store_id')))
  377. ->update(['sales' => Db::raw('sales+1')]);
  378. $orderGoods = OrderGoods::query()
  379. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  380. ->get()
  381. ->toArray();
  382. foreach ($orderGoods as $key => &$goodsItem) {
  383. if ($goodsItem['activity_type'] == 2) { # 活动商品
  384. $goods = GoodsActivity::find($goodsItem['goods_id']);
  385. } else {
  386. $goods = Goods::find($goodsItem['goods_id']);
  387. }
  388. $goods->inventory = $goods->inventory - $goodsItem['number'];
  389. $goods->sales = $goods->sales + $goodsItem['number'];
  390. $goods->save();
  391. // 商品月销
  392. if (!$ssdb->exec('exists', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_'.$goods->id)) {
  393. $ssdb->exec('set', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  394. } else {
  395. $ssdb->exec('incr', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
  396. }
  397. }
  398. // 月销流水
  399. $statistics = [];
  400. foreach ($orders as $key => &$order) {
  401. $statistics[] = [
  402. 'money' => $order['money'],
  403. 'user_id' => $order['user_id'],
  404. 'store_id' => $order['store_id'],
  405. 'market_id' => $orderMain->market_id,
  406. 'order_id' => $order['id'],
  407. 'createtime' => $orderMain->pay_time,
  408. ];
  409. // 商户月销
  410. if (!$ssdb->exec('exists', SsdbKeys::STORE_MONTH_SALES . date('Ym').'_' . $order['store_id'])) {
  411. $ssdb->exec('set', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  412. } else {
  413. $ssdb->exec('incr', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
  414. }
  415. }
  416. if (is_array($statistics) && !empty($statistics)) {
  417. $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics);
  418. }
  419. Db::commit();
  420. return true;
  421. } catch (Exception $e) {
  422. $this->log->event(LogLabel::ORDER_ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
  423. Db::rollBack();
  424. return false;
  425. }
  426. }
  427. /**
  428. * @inheritDoc
  429. */
  430. public function doPay($orderMainId, $userId)
  431. {
  432. // 订单待支付
  433. $orderMain = $this->check($orderMainId, $userId, OrderState::UNPAID);
  434. return $this->paymentService->do(
  435. $orderMain->global_order_id,
  436. $orderMain->money,
  437. $orderMain->user_id,
  438. config('wechat.notify_url.online')
  439. );
  440. }
  441. /**
  442. * @inheritDoc
  443. * @throws Exception
  444. */
  445. public function doDel($orderMainId, $userId)
  446. {
  447. // 订单完成
  448. $orderMain = $this->check($orderMainId, $userId, OrderState::CAN_DEL);
  449. if (!$orderMain->delete()) {
  450. throw new ErrorCodeException(ErrorCode::ORDER_DELETE_FAIL);
  451. }
  452. return true;
  453. }
  454. /**
  455. * @inheritDoc
  456. */
  457. public function doApplyRefund($orderMainId, $userId)
  458. {
  459. // 未接单
  460. $orderMain = $this->check($orderMainId, $userId, OrderState::PAID);
  461. $orderMain->state = OrderState::REFUNDING;
  462. if (!$orderMain->save()) {
  463. throw new ErrorCodeException(ErrorCode::ORDER_APPLY_REFUND_FAIL);
  464. }
  465. return true;
  466. }
  467. /**
  468. * @inheritDoc
  469. */
  470. public function doComplete($orderMainId, $userId)
  471. {
  472. $orderMain = $this->check($orderMainId, $userId, OrderState::RECEIVING);
  473. $orderMain->state = OrderState::COMPLETED;
  474. if (!$orderMain->save()) {
  475. throw new ErrorCodeException(ErrorCode::ORDER_COMPLETE_FAIL);
  476. }
  477. return true;
  478. }
  479. }