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.

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