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.

485 lines
20 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
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\TaskWorker\SSDBTask;
  30. use Hyperf\DbConnection\Db;
  31. use Hyperf\Di\Annotation\Inject;
  32. use App\Service\v3\Interfaces\OrderOnlineServiceInterface;
  33. use Hyperf\Snowflake\IdGeneratorInterface;
  34. use Hyperf\Utils\ApplicationContext;
  35. class OrderOnlineService implements OrderOnlineServiceInterface
  36. {
  37. /**
  38. * @Inject
  39. * @var Log
  40. */
  41. protected $log;
  42. /**
  43. * @Inject
  44. * @var DeliveryMoneyServiceInterface
  45. */
  46. protected $deliveryService;
  47. /**
  48. * @Inject
  49. * @var CouponRecServiceInterface
  50. */
  51. protected $couponRecService;
  52. /**
  53. * @Inject
  54. * @var CouponServiceInterface
  55. */
  56. protected $couponService;
  57. /**
  58. * @Inject
  59. * @var GoodsActivityServiceInterface
  60. */
  61. protected $goodsActivityService;
  62. /**
  63. * @Inject
  64. * @var GoodsServiceInterface
  65. */
  66. protected $goodsService;
  67. /**
  68. * @Inject
  69. * @var PaymentServiceInterface
  70. */
  71. protected $paymentService;
  72. /**
  73. * 下单
  74. * @param $marketId
  75. * @param $userId
  76. * @param $userAddrId
  77. * @param $storeList
  78. * @param $totalMoney
  79. * @param string $deliveryTimeNote
  80. * @param int $serviceMoney
  81. * @param null $receiveCouponIds
  82. * @param string $plat
  83. * @return array[]
  84. */
  85. public function do($marketId, $userId, $userAddrId, $storeList, $totalMoney, $deliveryTimeNote='尽快送达', $serviceMoney=0, $receiveCouponIds=null, $plat=''){
  86. Db::beginTransaction();
  87. try {
  88. $currentTime = time();
  89. bcscale(6);
  90. // 用户收货地址
  91. $userAddr = UserAddress::query()->find($userAddrId);
  92. // 获取配送费用
  93. $deliveryAmount = $this->deliveryService->do($userAddr->lat, $userAddr->lng);
  94. // 优惠券数据
  95. $couponRec = CouponRec::query()->lockForUpdate()->whereIn('id', $receiveCouponIds)->get()->toArray();
  96. // 处理购物车数据,计算订单金额、子订单数据处理等
  97. $totalAmount = 0; # 实付金额
  98. $orderAmount = 0; # 订单金额
  99. $dataMain = []; # 主订单
  100. $dataChildren = []; # 子订单
  101. $dataOrderGoods = []; # 订单商品
  102. $storeTypeIds = []; # 订单中的商户类型,用于校验红包
  103. foreach ($storeList as $key => &$storeItem) {
  104. $storeId = $storeItem->store_id;
  105. // 子订单金额
  106. $subAmount = 0;
  107. // 店铺分类
  108. $storeType = Store::query()->where(['id' => $storeId])->value('category_id');
  109. $storeTypeIds[] = (string)$storeType;
  110. // 店铺今天的订单数
  111. $count = Order::query()
  112. ->where(['store_id' => $storeId])
  113. ->whereBetween('created_at', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))])
  114. ->count();
  115. // 用户购物车数据
  116. $cartIds = explode(',', $storeItem->cart_ids);
  117. $carts = ShoppingCart::query()->whereIn('id', $cartIds)->where(['market_id' => $marketId, 'user_id' => $userId])->get();
  118. foreach ($carts as $k => &$cart) {
  119. // 查个商品
  120. $goods = [];
  121. if ($cart->activity_type == 1) {
  122. $goods = Goods::query()->lockForUpdate()->find($cart->goods_id);
  123. $check = $this->goodsService->check($goods->id, $cart->num);
  124. if (true !== $check) {
  125. // throw new ErrorCodeException($check, '[商品失效1]'.$cart->goods_id);
  126. }
  127. } elseif ($cart->activity_type == 2) {
  128. $goods = GoodsActivity::query()->lockForUpdate()->find($cart->goods_id);
  129. $check = $this->goodsActivityService->check($goods->id, $cart->num, $userId);
  130. if (true !== $check) {
  131. // throw new ErrorCodeException($check, '[商品失效2]'.$cart->goods_id);
  132. }
  133. // 活动商品不可用优惠券
  134. if ($goods->can_use_coupon!=1 && $receiveCouponIds) {
  135. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_CANNOT_USE_COUPON, '[商品失效]'.$cart->goods_id);
  136. }
  137. // 活动商品可用优惠券,再校验这些优惠券是不是可以在当前活动类型可用
  138. // receiveCouponIds中是不是有当前活动不可用的优惠券
  139. $couponIds = array_values(array_column($couponRec, 'coupon_id'));
  140. $couponsActivityAvailable = Coupon::query()
  141. ->select(['id'])
  142. ->whereJsonContains('activity_available', [(string)$goods->type])
  143. ->whereIn('id', $couponIds)
  144. ->get()->toArray();
  145. $couponsActivityAvailableIds = array_values(array_column($couponsActivityAvailable, 'id'));
  146. if (!empty(array_diff($couponIds, $couponsActivityAvailableIds))) {
  147. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_CANNOT_USE_COUPON, '[商品失效]'.json_encode($couponsActivityAvailableIds));
  148. }
  149. }
  150. if (empty($goods)) {
  151. throw new ErrorCodeException(ErrorCode::ORDER_GOODS_NOT_AVAILABLE);
  152. }
  153. // 库存判断
  154. if ($goods->is_infinite !=1 && $goods->inventory < $cart->num) {
  155. throw new ErrorCodeException(ErrorCode::ORDER_GOODS_INVENTORY_LIMIT);
  156. }
  157. // 算金额
  158. $goodsAmount = bcmul((string)$goods->price, (string)$cart->num); # 当前商品的金额
  159. $subAmount = bcadd((string)$subAmount, (string)$goodsAmount); # 当前店铺子订单的金额
  160. // 订单商品数据
  161. $dataOrderGoods[$storeId][] = [
  162. 'order_id' => 0,
  163. 'goods_id' => $cart->goods_id,
  164. 'activity_type' => $cart->activity_type,
  165. 'number' => $cart->num,
  166. 'price' => $goods->price,
  167. 'original_price' => $goods->original_price,
  168. 'vip_price' => $goods->vip_price,
  169. 'name' => $goods->name,
  170. 'goods_unit' => $goods->goods_unit,
  171. 'cover_img' => $goods->cover_img,
  172. 'spec' => $goods->spec,
  173. ];
  174. }
  175. // 子订单数据
  176. $dataChildren[] = [
  177. 'order_main_id' => 0,
  178. 'user_id' => $userId,
  179. 'store_id' => $storeId,
  180. 'money' => bcadd((string)$subAmount, '0', 2),
  181. 'oid' => $count + 1,
  182. 'order_num' => date('YmdHis').mt_rand(1000, 9999),
  183. 'note' => $storeItem->note
  184. ];
  185. // 订单金额
  186. $orderAmount = bcadd((string)$orderAmount, (string)$subAmount);
  187. }
  188. // 优惠券的使用
  189. $couponMoney = 0;
  190. if (!empty($couponRec)) {
  191. $couponsCanUse = $this->couponRecService->allForOrderOlAvailable($totalAmount, $userId, $marketId, 2, $storeTypeIds);
  192. $couponCanUseIds = array_column($couponsCanUse, 'id');
  193. $couponCanUseIds = array_intersect($couponCanUseIds, $receiveCouponIds);
  194. $couponCannotUseIds = array_diff($receiveCouponIds, $couponCanUseIds);
  195. if (empty($couponCanUseIds)||!empty($couponCannotUseIds)) {
  196. throw new ErrorCodeException(ErrorCode::COUPON_NOT_AVAILABLE);
  197. }
  198. // 计算红包折扣金额
  199. foreach ($couponsCanUse as $key => $coupon) {
  200. if (!in_array($coupon->id, $receiveCouponIds)) {
  201. continue;
  202. }
  203. if ($coupon->discount_type == Coupon::DISCOUNT_TYPE_CASH) {
  204. $couponMoney = bcadd($couponMoney, $coupon->discounts, 2);
  205. } elseif ($coupon->discount_type == Coupon::DISCOUNT_TYPE_RATE) {
  206. $discountRate = bcdiv($coupon->discounts,10);
  207. $discountRate = bcsub(1,$discountRate);
  208. $discountMoney = bcmul($orderAmount, $discountRate);
  209. $couponMoney = bcadd($couponMoney, $discountMoney, 2);
  210. }
  211. }
  212. }
  213. // 获取分布式全局ID
  214. $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
  215. $globalOrderId = $generator->generate();
  216. $orderAmount = bcadd((string)$orderAmount, '0', 2);
  217. $totalAmount = bcadd((string)$totalAmount, (string)$orderAmount);
  218. $totalAmount = bcadd((string)$totalAmount, (string)$deliveryAmount);
  219. $totalAmount = bcadd((string)$totalAmount, (string)$serviceMoney);
  220. $totalAmount = bcsub((string)$totalAmount, (string)$couponMoney, 2);
  221. // 校验订单总金额
  222. if ($totalAmount != $totalMoney) {
  223. throw new ErrorCodeException(ErrorCode::ORDER_TOTAL_AMOUNT_ERROR);
  224. }
  225. $dataMain = [
  226. 'market_id' => $marketId,
  227. 'order_num' => $globalOrderId,
  228. 'global_order_id' => $globalOrderId,
  229. 'user_id' => $userId,
  230. 'type' => OrderType::ONLINE,
  231. 'money' => $totalAmount,
  232. 'total_money' => $orderAmount,
  233. 'services_money' => $serviceMoney,
  234. 'coupon_money' => $couponMoney,
  235. 'delivery_money' => $deliveryAmount,
  236. 'state' => OrderState::UNPAID,
  237. 'tel' => $userAddr->tel,
  238. 'address' => $userAddr->address.$userAddr->doorplate,
  239. 'lat' => $userAddr->lat,
  240. 'lng' => $userAddr->lng,
  241. 'name' => $userAddr->user_name,
  242. 'plat' => $plat,
  243. 'delivery_time_note' => $deliveryTimeNote
  244. ];
  245. // 生成主订单
  246. $orderMain = OrderMain::query()->create($dataMain);
  247. $orderMainId = $orderMain->id;
  248. // 处理子订单
  249. foreach ($dataChildren as $key => &$child) {
  250. $child['order_main_id'] = $orderMainId;
  251. $orderChild = Order::query()->create($child);
  252. $orderChildId = $orderChild->id;
  253. foreach ($dataOrderGoods[$child['store_id']] as $k => &$orderGoods) {
  254. $orderGoods['order_id'] = $orderChildId;
  255. $orderGoods['created_at'] = $currentTime;
  256. $orderGoods['updated_at'] = $currentTime;
  257. }
  258. OrderGoods::query()->insert($dataOrderGoods[$child['store_id']]);
  259. }
  260. // 判断是否有购买多个特价商品
  261. $check = $this->goodsActivityService->checkOrderActivityCount($dataOrderGoods);
  262. if(!$check){
  263. throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_RESTRICT_LIMIT, '[同一订单同种类型活动商品]'.json_encode($dataOrderGoods));
  264. }
  265. // 订单成功,做一些处理
  266. // 活动商品购买记录
  267. foreach ($dataOrderGoods as $key => &$goods) {
  268. foreach ($goods as $k => &$goodsItem)
  269. if ($goodsItem['activity_type'] == 2) {
  270. $this->goodsActivityService->cacheRecord($goodsItem['goods_id'], $goodsItem['number'], $userId);
  271. }
  272. }
  273. // 优惠券红包使用记录
  274. if (is_array($couponRec)&&!empty($couponRec)) {
  275. # 使用记录、更新当前优惠券
  276. foreach ($couponRec as $key => &$coupon) {
  277. $couponUse = [
  278. 'user_id' => $coupon['user_id'],
  279. 'user_receive_id' => $coupon['id'],
  280. 'coupon_id' => $coupon['coupon_id'],
  281. 'order_main_id' => $orderMainId,
  282. 'use_time' => $currentTime,
  283. 'return_time' => 0,
  284. 'number' => 1,
  285. 'status' => 1,
  286. 'update_time' => 0,
  287. ];
  288. $insertRes = CouponUse::query()->insert($couponUse);
  289. if ($insertRes) {
  290. $numberRemain = $coupon['number_remain'] - 1;
  291. if ($numberRemain == 0) {
  292. $status = 2;
  293. } elseif ($numberRemain > 0 && $numberRemain < $coupon['number']) {
  294. $status = 1;
  295. } elseif ($numberRemain == $coupon['number']) {
  296. $status = 0;
  297. }
  298. $upRes = CouponRec::query()->where(['id' => $coupon['id']])->update(['number_remain' => $numberRemain, 'status' => $status]);
  299. if (!$upRes) {
  300. Db::rollBack();
  301. throw new ErrorCodeException(ErrorCode::COUPON_USE_FAILURE);
  302. }
  303. // 缓存使用记录
  304. $usedRes = $this->couponService->cacheTodayCouponUsed($coupon['user_id'], $coupon['coupon_id'], $coupon['id']);
  305. if (!$usedRes) {
  306. Db::rollBack();
  307. throw new ErrorCodeException(ErrorCode::COUPON_USE_FAILURE);
  308. }
  309. } else {
  310. Db::rollBack();
  311. throw new ErrorCodeException(ErrorCode::COUPON_USE_FAILURE);
  312. }
  313. }
  314. }
  315. Db::commit();
  316. // 支付
  317. return $this->paymentService->do($globalOrderId, $totalAmount, $userId, config('site_host') . '/v3/wechat/notify/online');
  318. } catch (\Exception $e) {
  319. Db::rollBack();
  320. $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['exception_msg' => $e->getMessage()]);
  321. throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_FAIL);
  322. }
  323. }
  324. public function check()
  325. {
  326. // TODO: Implement check() method.
  327. }
  328. public function undo()
  329. {
  330. // TODO: Implement undo() method.
  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. }