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.

527 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
  1. <?php
  2. namespace App\Service;
  3. use App\Model\Coupon;
  4. use App\Model\CouponUserRec;
  5. use App\Model\CouponUserUse;
  6. use App\Model\Goods;
  7. use App\Model\Order;
  8. use App\Model\OrderGoods;
  9. use App\Model\OrderMain;
  10. use App\Model\SpecCombination;
  11. use App\Model\Users;
  12. use Exception;
  13. use Hyperf\DbConnection\Db;
  14. use Hyperf\Snowflake\IdGeneratorInterface;
  15. use Hyperf\Utils\ApplicationContext;
  16. use Hyperf\Di\Annotation\Inject;
  17. class OrderService implements OrderServiceInterface
  18. {
  19. /**
  20. * @Inject
  21. * @var CouponServiceInterface
  22. */
  23. protected $couponService;
  24. /**
  25. * @inheritDoc
  26. */
  27. public function addOnlineOrder($data)
  28. {
  29. bcscale(6);
  30. // 订单判重
  31. $dataMain = $data;
  32. if ($orderMainId = $this->existsByOrderNum($data['order_num'])) {
  33. return $orderMainId;
  34. }
  35. Db::beginTransaction();
  36. try {
  37. // 计算当前订单可用红包优惠金额
  38. $couponMoney = 0;
  39. if (isset($data['receive_coupon_ids'])&&$data['receive_coupon_ids']) {
  40. $receiveCouponIds = explode(',', str_replace(',',',',$data['receive_coupon_ids']));
  41. $couponMoney = $this->getCouponAmount($receiveCouponIds, $data['money'], $data['user_id'], $data['market_id']);
  42. }
  43. $dataMain['yhq_money2'] = $couponMoney;
  44. // 获取分布式全局ID
  45. $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
  46. $dataMain['global_order_id'] = $generator->generate();
  47. // 店铺IDs
  48. $dataMain['store_ids'] = '';
  49. $storeList = json_decode(html_entity_decode($data['store_list']), true);
  50. if (!is_array($storeList)||empty($storeList)) {
  51. Db::rollBack();
  52. return '订单中商品不存在或已失效';
  53. }
  54. // 获取商户IDs
  55. foreach ($storeList as &$item) {
  56. $dataMain['store_ids'] .= empty($dataMain['store_ids']) ? $item['store_id'] : ','.$item['store_id'];
  57. }
  58. // 主订单插入数据
  59. $currentTime = time();
  60. $dataMain['time'] = date('Y-m-d H:i:s', $currentTime);
  61. $dataMain['time_add'] = $currentTime;
  62. $dataMain['pay_time'] = '';
  63. $dataMain['state'] = OrderMain::ORDER_STATE_UNPAY;
  64. $dataMain['code'] = $dataMain['global_order_id'];
  65. $dataMain['jj_note'] = '';
  66. // 主订单模型保存
  67. $orderMain = OrderMain::create($dataMain);
  68. $orderMainId = $orderMain->id;
  69. // 统计订单中所有店铺当日订单数,做店铺订单序号
  70. $countsArr = Order::query()
  71. ->selectRaw('id, COUNT(*) AS count')
  72. ->whereIn('store_id', explode(',', $dataMain['store_ids']))
  73. ->where(['type' => OrderMain::ORDER_TYPE_ONLINE])
  74. ->whereBetween('time', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')])
  75. ->get()
  76. ->toArray();
  77. $storeOrderCounts = [];
  78. foreach ($countsArr as $key => &$row) {
  79. $storeOrderCounts[$row['id']] = $row['count'];
  80. }
  81. // 循环处理订单总额、子订单总额、商品、商户订单等信息
  82. $orderAmountTotal = 0; # 总订单金额
  83. foreach ($storeList as $key => &$item) {
  84. // 子订单数据处理
  85. $dataChild = [
  86. 'uniacid' => $data['uniacid'],
  87. 'order_num' => 's'.date('YmdHis', time()) . rand(1111, 9999),
  88. 'user_id' => $orderMain->user_id,
  89. 'store_id' => $item['store_id'],
  90. 'order_main_id' => $orderMainId,
  91. 'state' => OrderMain::ORDER_STATE_UNPAY,
  92. 'tel' => $orderMain->tel,
  93. 'name' => $orderMain->name,
  94. 'address' => $orderMain->address,
  95. 'area' => $orderMain->area,
  96. 'time' => date("Y-m-d H:i:s"),
  97. 'note' => $item['note'] ?? '',
  98. 'delivery_time' => $orderMain->delivery_time,
  99. 'type' => $orderMain->type,
  100. 'lat' => $orderMain->lat,
  101. 'lng' => $orderMain->lng,
  102. 'pay_type' => $orderMain->pay_type,
  103. 'order_type' => $orderMain->order_type,
  104. 'money' => floatval($item['subtotal']),
  105. 'box_money' => floatval($item['box_money']),
  106. 'mj_money' => floatval($item['mj_money']),
  107. 'yhq_money' => floatval($item['yhq_money']),
  108. 'yhq_money2' => floatval($item['yhq_money2']),
  109. 'zk_money' => floatval($item['zk_money']),
  110. 'coupon_id' => $item['coupon_id'],
  111. 'coupon_id2' => $item['coupon_id2'],
  112. 'xyh_money' => floatval($item['xyh_money']),
  113. 'oid' => (isset($storeOrderCounts[$item['store_id']]) ? $item['store_id'] : 0) + 1,
  114. 'time_add' => date("Y-m-d H:i:s"),
  115. 'jj_note' => '',
  116. 'form_id' => '',
  117. 'form_id2' => '',
  118. 'code' => '',
  119. ];
  120. $orderChildId = Order::query()->insertGetId($dataChild);
  121. // 子订单内商品处理
  122. $goodsAmountTotal = 0;
  123. $orderGoods = [];
  124. if (!is_array($item['good_list'])||empty($item['good_list'])) {
  125. Db::rollBack();
  126. return '订单商品异常';
  127. }
  128. foreach ($item['good_list'] as &$goods) {
  129. $goodsAmount = bcadd(floatval($goods['money']), floatval($goods['box_money']));
  130. $goodsAmount = bcmul($goodsAmount, $goods['num']);
  131. $goodsAmountTotal = bcadd($goodsAmountTotal, $goodsAmount);
  132. $orderGoods[$goods['id']] = $goods;
  133. $orderGoods[$goods['id']]['uniacid'] = $data['uniacid'];
  134. $orderGoods[$goods['id']]['order_id'] = $orderChildId;
  135. $orderGoods[$goods['id']]['user_id'] = $dataMain['user_id'];
  136. $orderGoods[$goods['id']]['store_id'] = $item['store_id'];
  137. }
  138. // 子订单优惠总额
  139. $discountAmountTotal = bcadd($dataChild['mj_money'], $dataChild['yhq_money']);
  140. $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['yhq_money2']);
  141. $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['zk_money']);
  142. $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['xyh_money']);
  143. $goodsAmountTotal = bcsub($goodsAmountTotal, $discountAmountTotal, 2);
  144. $orderAmountTotal = bcadd($orderAmountTotal, $goodsAmountTotal, 2);
  145. // 校验子订单金额
  146. if ($goodsAmountTotal != $dataChild['money']) {
  147. Db::rollBack();
  148. return '店铺订单总金额错误';
  149. }
  150. }
  151. // 校验库存
  152. foreach ($orderGoods as $Key => &$goodsItem) {
  153. $goodsItem['combination_id'] = intval($goodsItem['combination_id']);
  154. // 存在规格,则去规格处查库存
  155. $goods = [];
  156. if ($goodsItem['combination_id'] > 0) {
  157. $combination = SpecCombination::query()
  158. ->select(['good_id AS id', 'number AS inventory'])
  159. ->where(['id' => $goodsItem['combination_id']])
  160. ->first()
  161. ->toArray();
  162. $goods = Goods::query()
  163. ->select(['id', 'name', 'is_max'])
  164. ->where(['id' => $combination['id']])
  165. ->first()
  166. ->toArray();
  167. $goods['inventory'] = $combination['inventory'];
  168. } else {
  169. $goods = Goods::query()
  170. ->select(['id', 'name', 'is_max', 'inventory'])
  171. ->where(['id' => $goodsItem['good_id']])
  172. ->first()
  173. ->toArray();
  174. }
  175. if (!$goods) {
  176. Db::rollBack();
  177. return '缺少商品';
  178. }
  179. if($goodsItem['num'] > $goods['inventory'] && $goods['is_max'] != Goods::INVENTORY_NOLIMIT){
  180. Db::rollBack();
  181. return '商品 '.$goods->name.' 库存不足!';
  182. }
  183. }
  184. // 校验总订单金额
  185. $deliveryAmount = 0; # 配送费用
  186. if($dataMain['order_type'] == OrderMain::ORDER_TYPE_ONLINE){
  187. $deliveryAmount = $dataMain['dada_fee'];
  188. }
  189. $orderAmountTotal = bcadd($orderAmountTotal, $deliveryAmount);
  190. # 总订单优惠总额
  191. $discountAmountTotal = bcadd($dataMain['mj_money'], $dataMain['yhq_money']);
  192. $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['yhq_money2']);
  193. $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['zk_money']);
  194. $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['xyh_money']);
  195. $orderAmountTotal = bcsub($orderAmountTotal, $discountAmountTotal, 2);
  196. if ($orderAmountTotal != bcsub(bcadd($dataMain['money'], $deliveryAmount), $discountAmountTotal, 2)) {
  197. Db::rollBack();
  198. return '订单总金额错误';
  199. }
  200. // 添加订单商品
  201. $tempGoods = $orderGoods;
  202. $orderGoods = [];
  203. foreach ($tempGoods as $key => &$value) {
  204. $goodsTemp['good_id'] = $value['good_id'];
  205. $goodsTemp['img'] = $value['logo'];
  206. $goodsTemp['number'] = $value['num'];
  207. $goodsTemp['order_id'] = $value['order_id'];
  208. $goodsTemp['name'] = $value['name'];
  209. $goodsTemp['money'] = $value['money'];
  210. $goodsTemp['dishes_id'] = $value['dishes_id'];
  211. $goodsTemp['spec'] = $value['spec'];
  212. $goodsTemp['is_qg'] = $value['is_qg'];
  213. $goodsTemp['good_unit'] = $value['good_unit'];
  214. $goodsTemp['uniacid'] = $value['uniacid'];
  215. $goodsTemp['combination_id'] = $value['combination_id'];
  216. $orderGoods[] = $goodsTemp;
  217. }
  218. $addOrderGoods = OrderGoods::query()->insert($orderGoods);
  219. if (!$addOrderGoods) {
  220. Db::rollBack();
  221. return '订单商品异常';
  222. }
  223. // 修改总订单金额,金额是计算来的
  224. // TODO 这部分其实可以结合处理优化一下,循环前后关联处理太多
  225. $updateOrderMain = OrderMain::query()->where(['id' => $orderMainId])->update(['money' => $orderAmountTotal, 'total_money' => $dataMain['money']]);
  226. if (!$updateOrderMain) {
  227. Db::rollBack();
  228. return '订单总金额记录失败';
  229. }
  230. // 处理红包的使用
  231. $canUseConpons = $this->couponService->getOrderCanUseCoupons(
  232. $data['money'],
  233. $data['market_id'],
  234. $data['user_id'],
  235. [
  236. 'receive.id',
  237. 'receive.user_id',
  238. 'receive.number',
  239. 'receive.number_remain',
  240. 'receive.system_coupon_user_id',
  241. 'coupon.discounts',
  242. 'coupon.discount_type',
  243. ]
  244. );
  245. if (is_array($canUseConpons)&&!empty($canUseConpons)) {
  246. # 使用记录、更新当前优惠券
  247. foreach ($canUseConpons as $key => &$coupon) {
  248. $couponUse = [
  249. 'user_id' => $coupon->user_id,
  250. 'user_receive_id' => $coupon->id,
  251. 'system_coupon_id' => $coupon->system_coupon_user_id,
  252. 'order_main_id' => $orderMainId,
  253. 'use_time' => $currentTime,
  254. 'return_time' => 0,
  255. 'number' => 1,
  256. 'status' => 1,
  257. 'update_time' => 0,
  258. ];
  259. $insertRes = CouponUserUse::query()->insert($couponUse);
  260. if ($insertRes) {
  261. $numberRemain = $coupon->number_remain - 1;
  262. if ($numberRemain == 0) {
  263. $status = 2;
  264. } elseif ($numberRemain > 0 && $numberRemain < $coupon->number) {
  265. $status = 1;
  266. } elseif ($numberRemain == $coupon->number) {
  267. $status = 0;
  268. }
  269. $upRes = CouponUserRec::query()->where(['id' => $coupon->id])->update(['number_remain' => $numberRemain, 'status' => $status]);
  270. if (!$upRes) {
  271. Db::rollBack();
  272. return '优惠券使用失败';
  273. }
  274. // 缓存使用记录
  275. $usedRes = $this->couponService->cacheTodayCouponUsed($coupon->user_id, $coupon->system_coupon_user_id, $coupon->id);
  276. if (!$usedRes) {
  277. Db::rollBack();
  278. return '优惠券使用失败';
  279. }
  280. } else {
  281. Db::rollBack();
  282. return '优惠券使用失败';
  283. }
  284. }
  285. }
  286. Db::commit();
  287. return $orderMainId;
  288. } catch (Exception $e) {
  289. Db::rollBack();
  290. return $e->getMessage();
  291. }
  292. }
  293. /**
  294. * @inheritDoc
  295. */
  296. public function addOfflineOrder($data)
  297. {
  298. Db::beginTransaction();
  299. try {
  300. // 主订单数据
  301. $dataMain = [];
  302. // 获取分布式全局ID
  303. $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
  304. $globalRrderId = $generator->generate();
  305. // 主订单插入数据
  306. $currentTime = time();
  307. $dataMain = [
  308. 'delivery_no' => '',
  309. 'dada_fee' => 0,
  310. 'market_id' => 0,
  311. 'box_money' => 0,
  312. 'ps_money' => 0,
  313. 'mj_money' => 0,
  314. 'xyh_money' => 0,
  315. 'yhq_money' => 0,
  316. 'yhq_money2' => 0,
  317. 'zk_money' => 0,
  318. 'tel' => '',
  319. 'name' => '',
  320. 'address' => '',
  321. 'area' => '',
  322. 'lat' => '',
  323. 'lng' => '',
  324. 'note' => '',
  325. 'form_id' => '',
  326. 'form_id2' => '',
  327. 'delivery_time' => '',
  328. 'order_type' => 0,
  329. 'coupon_id' => 0,
  330. 'coupon_id2' => 0,
  331. 'store_list' => '',
  332. 'receive_coupon_ids' => '',
  333. 'type' => OrderMain::ORDER_TYPE_OFFLINE,
  334. 'time' => date('Y-m-d H:i:s', $currentTime),
  335. 'time_add' => $currentTime,
  336. 'pay_time' => '',
  337. 'pay_type' => OrderMain::ORDER_PAY_WX,
  338. 'state' => OrderMain::ORDER_STATE_UNPAY,
  339. 'dm_state' => OrderMain::ORDER_STATE_UNPAY,
  340. 'code' => $globalRrderId,
  341. 'jj_note' => '',
  342. 'uniacid' => 2,
  343. 'order_num' => 'dm'.date('YmdHis', time()) . rand(1111, 9999),
  344. 'money' => $data['money'],
  345. 'user_id' => $data['user_id'],
  346. 'store_ids' => $data['store_id'],
  347. 'global_order_id' => $globalRrderId,
  348. ];
  349. // 主订单模型保存
  350. $orderMain = OrderMain::create($dataMain);
  351. $orderMainId = $orderMain->id;
  352. // 子订单模型保存
  353. $dataChild = [
  354. 'uniacid' => 1,
  355. 'order_num' => 's'.date('YmdHis', time()) . rand(1111, 9999),
  356. 'user_id' => $orderMain->user_id,
  357. 'store_id' => $data['store_id'],
  358. 'order_main_id' => $orderMainId,
  359. 'state' => OrderMain::ORDER_STATE_UNPAY,
  360. 'dm_state' => OrderMain::ORDER_STATE_UNPAY,
  361. 'tel' => $orderMain->tel,
  362. 'name' => $orderMain->name,
  363. 'address' => $orderMain->address,
  364. 'area' => $orderMain->area,
  365. 'time' => date("Y-m-d H:i:s"),
  366. 'note' => '',
  367. 'delivery_time' => $orderMain->delivery_time,
  368. 'type' => $orderMain->type,
  369. 'lat' => $orderMain->lat,
  370. 'lng' => $orderMain->lng,
  371. 'pay_type' => $orderMain->pay_type,
  372. 'order_type' => $orderMain->order_type,
  373. 'money' => $data['money'],
  374. 'box_money' => 0,
  375. 'mj_money' => 0,
  376. 'yhq_money' => 0,
  377. 'yhq_money2' => 0,
  378. 'zk_money' => 0,
  379. 'coupon_id' => 0,
  380. 'coupon_id2' => 0,
  381. 'xyh_money' => 0,
  382. 'time_add' => date("Y-m-d H:i:s"),
  383. 'jj_note' => '',
  384. 'form_id' => '',
  385. 'form_id2' => '',
  386. 'code' => '',
  387. ];
  388. $orderChildId = Order::query()->insertGetId($dataChild);
  389. Db::commit();
  390. return $orderMainId;
  391. } catch (Exception $e) {
  392. Db::rollBack();
  393. return '购买失败';
  394. }
  395. }
  396. /**
  397. * 计算和校验当前订单可用红包及金额
  398. * @param $couponIds
  399. * @param $orderAmount
  400. * @param $userId
  401. * @param $marketId
  402. * @throws Exception
  403. */
  404. protected function getCouponAmount($couponIds, $orderAmount, $userId, $marketId)
  405. {
  406. // 用户当前订单可用优惠券
  407. $couponsCanUse = $this->couponService->getOrderCanUseCoupons(
  408. $orderAmount,
  409. $marketId,
  410. $userId,
  411. [
  412. 'receive.id',
  413. 'receive.user_id',
  414. 'receive.number',
  415. 'receive.number_remain',
  416. 'receive.system_coupon_user_id',
  417. 'coupon.discounts',
  418. 'coupon.discount_type',
  419. ]
  420. );
  421. $couponCanUseIds = array_column($couponsCanUse, 'id');
  422. $couponCanUseIds = array_intersect($couponCanUseIds, $couponIds);
  423. $couponCannotUseIds = array_diff($couponIds, $couponCanUseIds);
  424. if (empty($couponCanUseIds)||!empty($couponCannotUseIds)) {
  425. throw new Exception('您的订单中有优惠券已经失效');
  426. }
  427. // 计算红包折扣金额
  428. $couponMoney = 0;
  429. foreach ($couponsCanUse as $key => $coupon) {
  430. if (!in_array($coupon->id, $couponIds)) {
  431. continue;
  432. }
  433. if ($coupon->discount_type == Coupon::DISCOUNT_TYPE_CASH) {
  434. $couponMoney = bcadd($couponMoney, $coupon->discounts, 2);
  435. } elseif ($coupon->discount_type == Coupon::DISCOUNT_TYPE_RATE) {
  436. $discountRate = bcdiv($coupon->discounts,10);
  437. $discountRate = bcsub(1,$discountRate);
  438. $discountMoney = bcmul($orderAmount, $discountRate);
  439. $couponMoney = bcadd($couponMoney, $discountMoney, 2);
  440. }
  441. }
  442. return $couponMoney;
  443. }
  444. /**
  445. * 订单是否存在
  446. * @param $orderNum
  447. * @return \Hyperf\Utils\HigherOrderTapProxy|mixed|void|null
  448. */
  449. public function existsByOrderNum($orderNum)
  450. {
  451. return OrderMain::query()->where(['order_num' => $orderNum])->value('id');
  452. }
  453. }