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.

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