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.

526 lines
20 KiB

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