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.

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