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.

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