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.

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