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.

424 lines
16 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
  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'] = date('Y-m-d H:i:s', $currentTime);
  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('COUNT(*) AS count')
  72. ->select('id')
  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. 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 = (object)[];
  157. if ($goodsItem['combination_id'] > 0) {
  158. $goods = SpecCombination::query()
  159. ->with(['goods' => function($query){
  160. $query->select(['name', 'is_max']);
  161. }])
  162. ->select(['id', 'number AS inventory'])
  163. ->where(['id' => $goodsItem['combination_id']])
  164. ->first()
  165. ->toArray();
  166. $goods->name = $goods->goods->name;
  167. $goods->is_max = $goods->goods->is_max;
  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. var_dump('$goods', $goods);
  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. $goods['good_id'] = $value['good_id'];
  206. $goods['img'] = $value['logo'];
  207. $goods['number'] = $value['num'];
  208. $goods['order_id'] = $value['order_id'];
  209. $goods['name'] = $value['name'];
  210. $goods['money'] = $value['money'];
  211. $goods['dishes_id'] = $value['dishes_id'];
  212. $goods['spec'] = $value['spec'];
  213. $goods['is_qg'] = $value['is_qg'];
  214. $goods['good_unit'] = $value['good_unit'];
  215. $goods['uniacid'] = $value['uniacid'];
  216. $goods['combination_id'] = $value['combination_id'];
  217. $orderGoods[] = $goods;
  218. }
  219. var_dump('$orderGoods', $orderGoods);
  220. $addOrderGoods = OrderGoods::query()->insert($orderGoods);
  221. if (!$addOrderGoods) {
  222. Db::rollBack();
  223. return '订单商品异常';
  224. }
  225. // 修改总订单金额,金额是计算来的
  226. // TODO 这部分其实可以结合处理优化一下,循环前后关联处理太多
  227. $updateOrderMain = OrderMain::query()->where(['id' => $orderMainId])->update(['money' => $orderAmountTotal, 'total_money' => $dataMain['money']]);
  228. if (!$updateOrderMain) {
  229. Db::rollBack();
  230. return '订单总金额记录失败';
  231. }
  232. // 处理红包的使用
  233. $canUseConpons = $this->couponService->getOrderCanUseCoupons(
  234. $data['money'],
  235. $data['market_id'],
  236. $data['user_id'],
  237. [
  238. 'receive.id',
  239. 'receive.user_id',
  240. 'receive.number',
  241. 'receive.number_remain',
  242. 'receive.system_coupon_user_id',
  243. 'coupon.discounts',
  244. 'coupon.discount_type',
  245. ]
  246. );
  247. if (is_array($canUseConpons)&&!empty($canUseConpons)) {
  248. # 使用记录、更新当前优惠券
  249. foreach ($canUseConpons as $key => &$coupon) {
  250. $couponUse = [
  251. 'user_id' => $coupon['user_id'],
  252. 'user_receive_id' => $coupon['id'],
  253. 'system_coupon_id' => $coupon['system_coupon_user_id'],
  254. 'order_main_id' => $orderMainId,
  255. 'use_time' => $currentTime,
  256. 'return_time' => 0,
  257. 'number' => 1,
  258. 'status' => 1,
  259. 'update_time' => 0,
  260. ];
  261. $insertRes = CouponUserUse::query()->insert($couponUse);
  262. if ($insertRes) {
  263. $numberRemain = $coupon['number_remain'] - 1;
  264. if ($numberRemain == 0) {
  265. $status = 2;
  266. } elseif ($numberRemain > 0 && $numberRemain < $coupon['number']) {
  267. $status = 1;
  268. } elseif ($numberRemain == $coupon['number']) {
  269. $status = 0;
  270. }
  271. $upRes = CouponUserRec::query()->where(['id' => $coupon['id']])->update(['number_remain' => $numberRemain, 'status' => $status]);
  272. if (!$upRes) {
  273. Db::rollBack();
  274. return '优惠券使用失败';
  275. }
  276. // 缓存使用记录
  277. $usedRes = $this->couponService->cacheTodayCouponUsed($coupon['user_id'], $coupon['system_coupon_user_id'], $coupon['id']);
  278. if (!$usedRes) {
  279. Db::rollBack();
  280. return '优惠券使用失败';
  281. }
  282. } else {
  283. Db::rollBack();
  284. return '优惠券使用失败';
  285. }
  286. }
  287. }
  288. Db::commit();
  289. return $orderMainId;
  290. } catch (Exception $e) {
  291. Db::rollBack();
  292. return $e->getMessage();
  293. }
  294. }
  295. /**
  296. * @inheritDoc
  297. */
  298. public function addOfflineOrder()
  299. {
  300. // TODO: Implement addOfflineOrder() method.
  301. }
  302. /**
  303. * 计算和校验当前订单可用红包及金额
  304. * @param $couponIds
  305. * @param $orderAmount
  306. * @param $userId
  307. * @param $marketId
  308. * @throws Exception
  309. */
  310. protected function getCouponAmount($couponIds, $orderAmount, $userId, $marketId)
  311. {
  312. // 用户当前订单可用优惠券
  313. $couponsCanUse = $this->couponService->getOrderCanUseCoupons(
  314. $orderAmount,
  315. $marketId,
  316. $userId,
  317. [
  318. 'receive.id',
  319. 'receive.user_id',
  320. 'receive.number',
  321. 'receive.number_remain',
  322. 'receive.system_coupon_user_id',
  323. 'coupon.discounts',
  324. 'coupon.discount_type',
  325. ]
  326. );
  327. $couponCanUseIds = array_column($couponsCanUse, 'id');
  328. $couponCanUseIds = array_intersect($couponCanUseIds, $couponIds);
  329. $couponCannotUseIds = array_diff($couponIds, $couponCanUseIds);
  330. if (empty($couponCanUseIds)||!empty($couponCannotUseIds)) {
  331. throw new Exception('您的订单中有优惠券已经失效');
  332. }
  333. // 计算红包折扣金额
  334. $couponMoney = 0;
  335. foreach ($couponsCanUse as $key => $coupon) {
  336. if (!in_array($coupon->id, $couponIds)) {
  337. continue;
  338. }
  339. if ($coupon->discount_type == Coupon::DISCOUNT_TYPE_CASH) {
  340. $couponMoney = bcadd($couponMoney, $coupon->discounts, 2);
  341. } elseif ($coupon->discount_type == Coupon::DISCOUNT_TYPE_RATE) {
  342. $discountRate = bcdiv($coupon->discounts,10);
  343. $discountRate = bcsub(1,$discountRate);
  344. $discountMoney = bcmul($orderAmount, $discountRate);
  345. $couponMoney = bcadd($couponMoney, $discountMoney, 2);
  346. }
  347. }
  348. return $couponMoney;
  349. }
  350. /**
  351. * 订单是否存在
  352. * @param $orderNum
  353. * @return \Hyperf\Utils\HigherOrderTapProxy|mixed|void|null
  354. */
  355. public function existsByOrderNum($orderNum)
  356. {
  357. return OrderMain::query()->where(['order_num' => $orderNum])->value('id');
  358. }
  359. }