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.

455 lines
18 KiB

5 years ago
5 years ago
5 years ago
5 years ago
  1. <?php
  2. namespace App\Service\v3\Implementations;
  3. use App\Constants\LogLabel;
  4. use App\Constants\v3\OrderType;
  5. use App\Model\CouponRec;
  6. use App\Model\CouponUserUse;
  7. use App\Model\Goods;
  8. use App\Model\OrderGoods;
  9. use App\Model\SpecCombination;
  10. use App\Model\v3\Order;
  11. use App\Model\v3\OrderMain;
  12. use App\Model\v3\ShoppingCart;
  13. use App\Model\v3\UserAddress;
  14. use App\Service\v3\Interfaces\DeliveryMoneyServiceInterface;
  15. use Hyperf\DbConnection\Db;
  16. use Hyperf\Di\Annotation\Inject;
  17. use App\Service\v3\Interfaces\OrderOnlineServiceInterface;
  18. use Hyperf\Snowflake\IdGeneratorInterface;
  19. use Hyperf\Utils\ApplicationContext;
  20. class OrderOnlineService implements OrderOnlineServiceInterface
  21. {
  22. /**
  23. * @Inject
  24. * @var DeliveryMoneyServiceInterface
  25. */
  26. protected $deliveryService;
  27. /**
  28. * 下单
  29. * @param $marketId
  30. * @param $userId
  31. * @param $userAddrId
  32. * @param $cartIds
  33. * @param $totalMoney
  34. * @param string $deliveryTimeNote
  35. * @param null $receiveCouponIds
  36. * @return string
  37. */
  38. public function do($marketId, $userId, $userAddrId, $cartIds, $totalMoney, $deliveryTimeNote='尽快送达', $receiveCouponIds=null){
  39. bcscale(6);
  40. // 用户收货地址
  41. $userAddr = UserAddress::query()->find($userAddrId);
  42. // 用户购物车数据
  43. $carts = ShoppingCart::query()->whereIn('id', $cartIds)->where(['market_id' => $marketId])->get();
  44. // 优惠券数据
  45. $couponRec = CouponRec::query()->whereIn('id', $receiveCouponIds);
  46. // 获取配送费用
  47. $deliveryAmount = $this->deliveryService->do($userAddr->lat, $userAddr->lng);
  48. // 处理购物车数据,计算订单金额、子订单数据处理等
  49. $totalAmount = bcadd((string)$deliveryAmount, 0);
  50. $orderAmount = 0;
  51. $orderChildren = [];
  52. foreach ($carts as $key => $cart) {
  53. // 查个商品
  54. $goods = Goods::query()->select('price')->find($cart->goods_id);
  55. $goodsAmount = bcmul((string)$goods->price, (string)$cart->num);
  56. // 子订单
  57. $orderChildren[$cart->store_id]['user_id'] = $cart->user_id;
  58. if (!isset($orderChildren[$cart->store_id]['money'])) {
  59. $orderChildren[$cart->store_id]['money'] = 0;
  60. }
  61. $orderChildren[$cart->store_id]['money'] = bcadd((string)$orderChildren[$cart->store_id]['money'], (string)$goodsAmount);
  62. $totalAmount = bcadd((string)$totalAmount, (string)$goodsAmount);
  63. }
  64. // 获取分布式全局ID
  65. $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
  66. $global_order_id = $generator->generate();
  67. $dataMain = [
  68. 'market_id' => $marketId,
  69. 'order_num' => $global_order_id,
  70. 'global_order_id' => $global_order_id,
  71. 'user_id' => $userId,
  72. 'type' => OrderType::ONLINE,
  73. 'money' => $totalAmount,
  74. 'total_money' => '',
  75. 'services_money' => '',
  76. 'coupon_money' => '',
  77. 'delivery_money' => '',
  78. 'state' => '',
  79. 'pay_time' => '',
  80. 'receive_time' => '',
  81. 'delivery_time' => '',
  82. 'complete_time' => '',
  83. 'cancel_time' => '',
  84. 'refund_time' => '',
  85. 'tel' => '',
  86. 'address' => '',
  87. 'area' => '',
  88. 'lat' => '',
  89. 'lng' => '',
  90. 'name' => '',
  91. 'print_num' => '',
  92. 'plat' => '',
  93. 'refuse_refund_note' => '',
  94. 'delivery_time_note' => '',
  95. 'total_refund_note' => '',
  96. 'note' => '',
  97. 'created_at' => '',
  98. 'updated_at' => '',
  99. 'deleted_at' => '',
  100. ];
  101. return ['data_main' => $dataMain];
  102. $dataMain = $data;
  103. Db::beginTransaction();
  104. try {
  105. // TODO 这个字段后续可能不用了,之前由达达订单号从前端传上来
  106. $dataMain['order_num'] = 'o'.date('YmdHis').mt_rand(1000,9999);
  107. // 计算当前订单可用红包优惠金额
  108. $couponMoney = 0;
  109. $receiveCouponIds = [];
  110. if (isset($data['receive_coupon_ids'])&&$data['receive_coupon_ids']) {
  111. $receiveCouponIds = explode(',', str_replace(',',',',$data['receive_coupon_ids']));
  112. $couponMoney = $this->getCouponAmount($receiveCouponIds, $data['money'], $data['user_id'], $data['market_id']);
  113. }
  114. $dataMain['yhq_money2'] = $couponMoney;
  115. // 获取分布式全局ID
  116. $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
  117. $dataMain['global_order_id'] = $generator->generate();
  118. // 店铺IDs
  119. $dataMain['store_ids'] = '';
  120. $storeList = json_decode(html_entity_decode($data['store_list']), true);
  121. if (!is_array($storeList)||empty($storeList)) {
  122. Db::rollBack();
  123. return '订单中商品不存在或已失效';
  124. }
  125. // 获取商户IDs
  126. foreach ($storeList as &$item) {
  127. $dataMain['store_ids'] .= empty($dataMain['store_ids']) ? $item['store_id'] : ','.$item['store_id'];
  128. }
  129. // 主订单插入数据
  130. $currentTime = time();
  131. $dataMain['time'] = date('Y-m-d H:i:s', $currentTime);
  132. $dataMain['time_add'] = $currentTime;
  133. $dataMain['pay_time'] = '';
  134. $dataMain['state'] = \App\Model\OrderMain::ORDER_STATE_UNPAY;
  135. $dataMain['code'] = $dataMain['global_order_id'];
  136. $dataMain['jj_note'] = '';
  137. // 主订单模型保存
  138. $orderMain = OrderMain::create($dataMain);
  139. $orderMainId = $orderMain->id;
  140. // 统计订单中所有店铺当日订单数,做店铺订单序号
  141. $countsArr = \App\Model\Order::query()
  142. ->selectRaw('store_id, COUNT(*) AS count')
  143. ->whereIn('store_id', explode(',', $dataMain['store_ids']))
  144. ->where(['type' => OrderMain::ORDER_TYPE_ONLINE])
  145. ->whereBetween('time', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')])
  146. ->groupBy('store_id')
  147. ->get()
  148. ->toArray();
  149. $storeOrderCounts = [];
  150. foreach ($countsArr as $key => &$row) {
  151. $storeOrderCounts[$row['store_id']] = $row['count'];
  152. }
  153. // 循环处理订单总额、子订单总额、商品、商户订单等信息
  154. $orderAmountTotal = 0; # 总订单金额
  155. $orderGoods = [];
  156. foreach ($storeList as $key => &$item) {
  157. // 子订单数据处理
  158. $dataChild = [
  159. 'uniacid' => $data['uniacid'],
  160. 'order_num' => 's'.date('YmdHis', time()) . rand(1111, 9999),
  161. 'user_id' => $orderMain->user_id,
  162. 'store_id' => $item['store_id'],
  163. 'order_main_id' => $orderMainId,
  164. 'state' => OrderMain::ORDER_STATE_UNPAY,
  165. 'tel' => $orderMain->tel,
  166. 'name' => $orderMain->name,
  167. 'address' => $orderMain->address,
  168. 'area' => $orderMain->area,
  169. 'time' => date("Y-m-d H:i:s"),
  170. 'note' => $item['note'] ?? '',
  171. 'delivery_time' => $orderMain->delivery_time,
  172. 'type' => $orderMain->type,
  173. 'lat' => $orderMain->lat,
  174. 'lng' => $orderMain->lng,
  175. 'pay_type' => $orderMain->pay_type,
  176. 'order_type' => $orderMain->order_type,
  177. 'money' => floatval($item['subtotal']),
  178. 'box_money' => floatval($item['box_money']),
  179. 'mj_money' => floatval($item['mj_money']),
  180. 'yhq_money' => floatval($item['yhq_money']),
  181. 'yhq_money2' => floatval($item['yhq_money2']),
  182. 'zk_money' => floatval($item['zk_money']),
  183. 'coupon_id' => $item['coupon_id'],
  184. 'coupon_id2' => $item['coupon_id2'],
  185. 'xyh_money' => floatval($item['xyh_money']),
  186. 'oid' => (isset($storeOrderCounts[$item['store_id']]) ? $item['store_id'] : 0) + 1,
  187. 'time_add' => date("Y-m-d H:i:s"),
  188. 'jj_note' => '',
  189. 'form_id' => '',
  190. 'form_id2' => '',
  191. 'code' => '',
  192. ];
  193. $orderChildId = Order::query()->insertGetId($dataChild);
  194. // 子订单内商品处理
  195. $goodsAmountTotal = 0;
  196. if (!is_array($item['good_list'])||empty($item['good_list'])) {
  197. Db::rollBack();
  198. return '订单商品异常';
  199. }
  200. foreach ($item['good_list'] as &$goods) {
  201. $goodsAmount = bcadd(floatval($goods['money']), floatval($goods['box_money']));
  202. $goodsAmount = bcmul($goodsAmount, $goods['num']);
  203. $goodsAmountTotal = bcadd($goodsAmountTotal, $goodsAmount);
  204. $orderGoods[$goods['id']] = $goods;
  205. $orderGoods[$goods['id']]['uniacid'] = $data['uniacid'];
  206. $orderGoods[$goods['id']]['order_id'] = $orderChildId;
  207. $orderGoods[$goods['id']]['user_id'] = $dataMain['user_id'];
  208. $orderGoods[$goods['id']]['store_id'] = $item['store_id'];
  209. }
  210. // 子订单优惠总额
  211. $discountAmountTotal = bcadd($dataChild['mj_money'], $dataChild['yhq_money']);
  212. $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['yhq_money2']);
  213. $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['zk_money']);
  214. $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['xyh_money']);
  215. $goodsAmountTotal = bcsub($goodsAmountTotal, $discountAmountTotal, 2);
  216. $orderAmountTotal = bcadd($orderAmountTotal, $goodsAmountTotal, 2);
  217. // 校验子订单金额
  218. if ($goodsAmountTotal != $dataChild['money']) {
  219. Db::rollBack();
  220. return '店铺订单总金额错误';
  221. }
  222. }
  223. // 校验库存
  224. foreach ($orderGoods as $Key => &$goodsItem) {
  225. $goodsItem['combination_id'] = intval($goodsItem['combination_id']);
  226. // 存在规格,则去规格处查库存
  227. $goods = [];
  228. if ($goodsItem['combination_id'] > 0) {
  229. $combination = SpecCombination::query()
  230. ->select(['good_id AS id', 'number AS inventory'])
  231. ->where(['id' => $goodsItem['combination_id']])
  232. ->first()
  233. ->toArray();
  234. $goods = Goods::query()
  235. ->select(['id', 'name', 'is_max'])
  236. ->where(['id' => $combination['id']])
  237. ->first()
  238. ->toArray();
  239. $goods['inventory'] = $combination['inventory'];
  240. } else {
  241. $goods = Goods::query()
  242. ->select(['id', 'name', 'is_max', 'inventory'])
  243. ->where(['id' => $goodsItem['good_id']])
  244. ->first()
  245. ->toArray();
  246. }
  247. if (!$goods) {
  248. Db::rollBack();
  249. return '缺少商品';
  250. }
  251. if($goodsItem['num'] > $goods['inventory'] && $goods['is_max'] != Goods::INVENTORY_NOLIMIT){
  252. Db::rollBack();
  253. return '商品 '.$goods->name.' 库存不足!';
  254. }
  255. }
  256. // 校验总订单金额
  257. $deliveryAmount = 0; # 配送费用
  258. if($dataMain['order_type'] == OrderMain::ORDER_TYPE_ONLINE){
  259. $deliveryAmount = $dataMain['dada_fee'];
  260. }
  261. $orderAmountTotal = bcadd($orderAmountTotal, $deliveryAmount);
  262. # 总订单优惠总额
  263. $discountAmountTotal = bcadd($dataMain['mj_money'], $dataMain['yhq_money']);
  264. $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['yhq_money2']);
  265. $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['zk_money']);
  266. $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['xyh_money']);
  267. $orderAmountTotal = bcsub($orderAmountTotal, $discountAmountTotal, 2);
  268. if ($orderAmountTotal != bcsub(bcadd($dataMain['money'], $deliveryAmount), $discountAmountTotal, 2)) {
  269. Db::rollBack();
  270. return '订单总金额错误';
  271. }
  272. // 添加订单商品
  273. $tempGoods = $orderGoods;
  274. $orderGoods = [];
  275. foreach ($tempGoods as $key => &$value) {
  276. $goodsTemp['good_id'] = $value['good_id'];
  277. $goodsTemp['img'] = $value['logo'];
  278. $goodsTemp['number'] = $value['num'];
  279. $goodsTemp['order_id'] = $value['order_id'];
  280. $goodsTemp['name'] = $value['name'];
  281. $goodsTemp['money'] = $value['money'];
  282. $goodsTemp['dishes_id'] = $value['dishes_id'];
  283. $goodsTemp['spec'] = $value['spec'];
  284. $goodsTemp['is_qg'] = $value['is_qg'];
  285. $goodsTemp['good_unit'] = $value['good_unit'];
  286. $goodsTemp['uniacid'] = $value['uniacid'];
  287. $goodsTemp['combination_id'] = $value['combination_id'];
  288. $orderGoods[] = $goodsTemp;
  289. }
  290. $addOrderGoods = OrderGoods::query()->insert($orderGoods);
  291. if (!$addOrderGoods) {
  292. Db::rollBack();
  293. return '订单商品异常';
  294. }
  295. //判断是否有购买多个特价商品
  296. $result = $this->purchaseLimitService->PurchaseLimit($orderGoods);
  297. if(!$result){
  298. Db::rollBack();
  299. return '同一个订单不能购买多个特价商品';
  300. }
  301. //判断是否有购买特价商品
  302. $this->purchaseLimitService->ssdbPurchaseRecord($orderGoods,$data['user_id'],$dataMain['global_order_id']);
  303. // 修改总订单金额,金额是计算来的
  304. // TODO 这部分其实可以结合处理优化一下,循环前后关联处理太多
  305. $updateOrderMain = OrderMain::query()->where(['id' => $orderMainId])->update(['money' => $orderAmountTotal, 'total_money' => $dataMain['money']]);
  306. if (!$updateOrderMain) {
  307. Db::rollBack();
  308. return '订单总金额记录失败';
  309. }
  310. // 处理红包的使用
  311. $canUseCoupons = CouponRec::select(['id', 'user_id', 'number', 'number_remain', 'system_coupon_user_id'])
  312. ->whereIn('id', $receiveCouponIds)
  313. ->get()->toArray();
  314. if (is_array($canUseCoupons)&&!empty($canUseCoupons)) {
  315. # 使用记录、更新当前优惠券
  316. foreach ($canUseCoupons as $key => &$coupon) {
  317. $couponUse = [
  318. 'user_id' => $coupon['user_id'],
  319. 'user_receive_id' => $coupon['id'],
  320. 'system_coupon_id' => $coupon['system_coupon_user_id'],
  321. 'order_main_id' => $orderMainId,
  322. 'use_time' => $currentTime,
  323. 'return_time' => 0,
  324. 'number' => 1,
  325. 'status' => 1,
  326. 'update_time' => 0,
  327. ];
  328. $insertRes = CouponUserUse::query()->insert($couponUse);
  329. if ($insertRes) {
  330. $numberRemain = $coupon['number_remain'] - 1;
  331. if ($numberRemain == 0) {
  332. $status = 2;
  333. } elseif ($numberRemain > 0 && $numberRemain < $coupon['number']) {
  334. $status = 1;
  335. } elseif ($numberRemain == $coupon['number']) {
  336. $status = 0;
  337. }
  338. $upRes = CouponRec::query()->where(['id' => $coupon['id']])->update(['number_remain' => $numberRemain, 'status' => $status]);
  339. if (!$upRes) {
  340. Db::rollBack();
  341. return '优惠券使用失败';
  342. }
  343. // 缓存使用记录
  344. $usedRes = $this->couponService->cacheTodayCouponUsed($coupon['user_id'], $coupon['system_coupon_user_id'], $coupon['id']);
  345. if (!$usedRes) {
  346. Db::rollBack();
  347. return '优惠券使用失败';
  348. }
  349. } else {
  350. Db::rollBack();
  351. return '优惠券使用失败';
  352. }
  353. }
  354. }
  355. Db::commit();
  356. return $orderMainId;
  357. } catch (Exception $e) {
  358. $this->log->event(
  359. LogLabel::ORDER_LOG,
  360. ['message' => $e->getMessage()]
  361. );
  362. Db::rollBack();
  363. return $e->getMessage();
  364. }
  365. }
  366. public function check()
  367. {
  368. // TODO: Implement check() method.
  369. }
  370. public function undo()
  371. {
  372. // TODO: Implement undo() method.
  373. }
  374. public function detailByUser($orderMainId, $userId)
  375. {
  376. $orderMain = OrderMain::with(['market'])->find($orderMainId);
  377. $orders = Order::query()
  378. ->where(['order_main_id' => $orderMainId, 'user_id' => $userId])
  379. ->with([
  380. 'orderGoods',
  381. 'store'
  382. ])
  383. ->get()->toArray();
  384. return ['order_main' => $orderMain, 'orders' => $orders];
  385. }
  386. }