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.

425 lines
16 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
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 CoupnoServiceInterface
  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. var_dump('row', $row);
  80. $storeOrderCounts[$row['id']] = $row['count'];
  81. }
  82. // 循环处理订单总额、子订单总额、商品、商户订单等信息
  83. $orderAmountTotal = 0; # 总订单金额
  84. foreach ($storeList as $key => &$item) {
  85. // 子订单数据处理
  86. $dataChild = [
  87. 'uniacid' => $data['uniacid'],
  88. 'order_num' => 's'.date('YmdHis', time()) . rand(1111, 9999),
  89. 'user_id' => $orderMain->user_id,
  90. 'store_id' => $item['store_id'],
  91. 'order_main_id' => $orderMainId,
  92. 'state' => OrderMain::ORDER_STATE_UNPAY,
  93. 'tel' => $orderMain->tel,
  94. 'name' => $orderMain->name,
  95. 'address' => $orderMain->address,
  96. 'area' => $orderMain->area,
  97. 'time' => date("Y-m-d H:i:s"),
  98. 'note' => $item['note'] ?? '',
  99. 'delivery_time' => $orderMain->delivery_time,
  100. 'type' => $orderMain->type,
  101. 'lat' => $orderMain->lat,
  102. 'lng' => $orderMain->lng,
  103. 'pay_type' => $orderMain->pay_type,
  104. 'order_type' => $orderMain->order_type,
  105. 'money' => floatval($item['subtotal']),
  106. 'box_money' => floatval($item['box_money']),
  107. 'mj_money' => floatval($item['mj_money']),
  108. 'yhq_money' => floatval($item['yhq_money']),
  109. 'yhq_money2' => floatval($item['yhq_money2']),
  110. 'zk_money' => floatval($item['zk_money']),
  111. 'coupon_id' => $item['coupon_id'],
  112. 'coupon_id2' => $item['coupon_id2'],
  113. 'xyh_money' => floatval($item['xyh_money']),
  114. 'oid' => (isset($storeOrderCounts[$item['store_id']]) ? $item['store_id'] : 0) + 1,
  115. 'time_add' => date("Y-m-d H:i:s"),
  116. 'jj_note' => '',
  117. 'form_id' => '',
  118. 'form_id2' => '',
  119. 'code' => '',
  120. ];
  121. $orderChildId = Order::query()->insertGetId($dataChild);
  122. // 子订单内商品处理
  123. $goodsAmountTotal = 0;
  124. $orderGoods = [];
  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. $canUseConpons = $this->couponService->getOrderCanUseCoupons(
  233. $data['money'],
  234. $data['market_id'],
  235. $data['user_id'],
  236. [
  237. 'receive.id',
  238. 'receive.user_id',
  239. 'receive.number',
  240. 'receive.number_remain',
  241. 'receive.system_coupon_user_id',
  242. 'coupon.discounts',
  243. 'coupon.discount_type',
  244. ]
  245. );
  246. if (is_array($canUseConpons)&&!empty($canUseConpons)) {
  247. # 使用记录、更新当前优惠券
  248. foreach ($canUseConpons as $key => &$coupon) {
  249. $couponUse = [
  250. 'user_id' => $coupon->user_id,
  251. 'user_receive_id' => $coupon->id,
  252. 'system_coupon_id' => $coupon->system_coupon_user_id,
  253. 'order_main_id' => $orderMainId,
  254. 'use_time' => $currentTime,
  255. 'return_time' => 0,
  256. 'number' => 1,
  257. 'status' => 1,
  258. 'update_time' => 0,
  259. ];
  260. $insertRes = CouponUserUse::query()->insert($couponUse);
  261. if ($insertRes) {
  262. $numberRemain = $coupon->number_remain - 1;
  263. if ($numberRemain == 0) {
  264. $status = 2;
  265. } elseif ($numberRemain > 0 && $numberRemain < $coupon->number) {
  266. $status = 1;
  267. } elseif ($numberRemain == $coupon->number) {
  268. $status = 0;
  269. }
  270. $upRes = CouponUserRec::query()->where(['id' => $coupon->id])->update(['number_remain' => $numberRemain, 'status' => $status]);
  271. if (!$upRes) {
  272. Db::rollBack();
  273. return '优惠券使用失败';
  274. }
  275. // 缓存使用记录
  276. $usedRes = $this->couponService->cacheTodayCouponUsed($coupon->user_id, $coupon->system_coupon_user_id, $coupon->id);
  277. if (!$usedRes) {
  278. Db::rollBack();
  279. return '优惠券使用失败';
  280. }
  281. } else {
  282. Db::rollBack();
  283. return '优惠券使用失败';
  284. }
  285. }
  286. }
  287. Db::commit();
  288. return $orderMainId;
  289. } catch (Exception $e) {
  290. Db::rollBack();
  291. return $e->getMessage();
  292. }
  293. }
  294. /**
  295. * @inheritDoc
  296. */
  297. public function addOfflineOrder()
  298. {
  299. // TODO: Implement addOfflineOrder() method.
  300. }
  301. /**
  302. * 计算和校验当前订单可用红包及金额
  303. * @param $couponIds
  304. * @param $orderAmount
  305. * @param $userId
  306. * @param $marketId
  307. * @throws Exception
  308. */
  309. protected function getCouponAmount($couponIds, $orderAmount, $userId, $marketId)
  310. {
  311. // 用户当前订单可用优惠券
  312. $couponsCanUse = $this->couponService->getOrderCanUseCoupons(
  313. $orderAmount,
  314. $marketId,
  315. $userId,
  316. [
  317. 'receive.id',
  318. 'receive.user_id',
  319. 'receive.number',
  320. 'receive.number_remain',
  321. 'receive.system_coupon_user_id',
  322. 'coupon.discounts',
  323. 'coupon.discount_type',
  324. ]
  325. );
  326. $couponCanUseIds = array_column($couponsCanUse, 'id');
  327. $couponCanUseIds = array_intersect($couponCanUseIds, $couponIds);
  328. $couponCannotUseIds = array_diff($couponIds, $couponCanUseIds);
  329. if (empty($couponCanUseIds)||!empty($couponCannotUseIds)) {
  330. throw new Exception('您的订单中有优惠券已经失效');
  331. }
  332. // 计算红包折扣金额
  333. $couponMoney = 0;
  334. foreach ($couponsCanUse as $key => $coupon) {
  335. if (!in_array($coupon->id, $couponIds)) {
  336. continue;
  337. }
  338. if ($coupon->discount_type == Coupon::DISCOUNT_TYPE_CASH) {
  339. $couponMoney = bcadd($couponMoney, $coupon->discounts, 2);
  340. } elseif ($coupon->discount_type == Coupon::DISCOUNT_TYPE_RATE) {
  341. $discountRate = bcdiv($coupon->discounts,10);
  342. $discountRate = bcsub(1,$discountRate);
  343. $discountMoney = bcmul($orderAmount, $discountRate);
  344. $couponMoney = bcadd($couponMoney, $discountMoney, 2);
  345. }
  346. }
  347. return $couponMoney;
  348. }
  349. /**
  350. * 订单是否存在
  351. * @param $orderNum
  352. * @return \Hyperf\Utils\HigherOrderTapProxy|mixed|void|null
  353. */
  354. public function existsByOrderNum($orderNum)
  355. {
  356. return OrderMain::query()->where(['order_num' => $orderNum])->value('id');
  357. }
  358. }