OrderService.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. <?php
  2. namespace app\common\Service;
  3. use app\common\Enum\GoodsEnum;
  4. use app\common\model\Order;
  5. use app\common\model\OrderGoods;
  6. use app\common\model\OrderAction;
  7. use app\common\model\Address;
  8. use app\common\model\UserCoupon;
  9. use app\common\model\Goods;
  10. use app\common\model\Sku;
  11. use app\common\model\Freight;
  12. use app\common\model\Coupon;
  13. use app\common\model\Carts;
  14. use think\Db;
  15. use think\Exception;
  16. use app\common\model\OrderAddress;
  17. /**
  18. * 订单服务类
  19. * 封装订单创建相关逻辑
  20. */
  21. class OrderService
  22. {
  23. /**
  24. * 根据商品列表计算订单明细
  25. * @param array $orderInfo 订单基础信息
  26. * @param array $goods_list 商品列表
  27. * @param int $user_id 用户ID
  28. * @param int $area_id 地区ID
  29. * @param int $user_coupon_id 优惠券ID
  30. * @return array
  31. * @throws Exception
  32. */
  33. protected static function computeGoods(&$orderInfo, $goodsList, $userId, $areaId, $userCouponId = 0)
  34. {
  35. $config = get_addon_config('shop');
  36. $orderInfo['amount'] = 0;
  37. $orderInfo['goods_price'] = 0;
  38. $orderInfo['goods_num'] = 0;
  39. $orderInfo['express_fee'] = 0;
  40. $orderInfo['discount_fee'] = 0;
  41. $orderInfo['coupon_discount_fee'] = 0;
  42. $orderInfo['order_amount'] = 0;
  43. $orderItem = [];
  44. $shippingTemp = [];
  45. $userCoupon = null;
  46. $processedGoodsList = []; // 处理后的商品列表,避免与参数$goodsList冲突
  47. // 校验优惠券
  48. if ($userCouponId) {
  49. $userCouponModel = new UserCoupon();
  50. $userCoupon = $userCouponModel->checkUserOrUse($userCouponId, $userId);
  51. $orderInfo['user_coupon_id'] = $userCouponId;
  52. }
  53. // 提取所有商品ID和SKU ID,进行批量查询
  54. $goodsIds = array_column($goodsList, 'goods_id');
  55. $skuIds = [];
  56. foreach ($goodsList as $index => $item) {
  57. if (isset($item['goods_sku_id']) && $item['goods_sku_id'] > 0) {
  58. $skuIds[] = $item['goods_sku_id'];
  59. }
  60. }
  61. // 批量查询商品信息
  62. $goodsData = [];
  63. if (!empty($goodsIds)) {
  64. $goodsCollection = Goods::with(['brand'])
  65. ->where('id', 'in', $goodsIds)
  66. ->where('status', GoodsEnum::STATUS_ON_SALE)
  67. ->select();
  68. foreach ($goodsCollection as $goods) {
  69. $goodsData[$goods->id] = $goods;
  70. }
  71. }
  72. // 批量查询SKU信息
  73. $skuData = [];
  74. $multiSpecSkuIds = []; // 用于存储多规格商品的SKU ID
  75. if (!empty($skuIds)) {
  76. $skuCollection = Sku::where('id', 'in', $skuIds)->select();
  77. foreach ($skuCollection as $sku) {
  78. $skuData[$sku->id] = $sku;
  79. // 过滤出有规格值的SKU ID(spec_value_ids不为空)
  80. if (!empty($sku->spec_value_ids)) {
  81. $multiSpecSkuIds[] = $sku->id;
  82. }
  83. }
  84. }
  85. // 批量查询规格属性字符串(只查询多规格商品的SKU)
  86. $skuAttrData = [];
  87. if (!empty($multiSpecSkuIds)) {
  88. $skuAttrData = \app\common\Service\SkuSpec::getSkuAttrs($multiSpecSkuIds);
  89. }
  90. // 验证并构建商品数据
  91. foreach ($goodsList as $item) {
  92. $goods_id = $item['goods_id'];
  93. $goods_sku_id = $item['goods_sku_id']; // 现在所有商品都应该有SKU ID
  94. $nums = $item['nums'];
  95. if ($nums <= 0) {
  96. throw new Exception("商品数量必须大于0");
  97. }
  98. // 检查商品是否存在
  99. if (!isset($goodsData[$goods_id])) {
  100. throw new Exception("商品已下架");
  101. }
  102. $goods = $goodsData[$goods_id];
  103. // 所有商品都必须有SKU(包括单规格商品的默认SKU)
  104. if (empty($skuData) || !isset($skuData[$goods_sku_id])) {
  105. throw new Exception("商品规格不存在");
  106. }
  107. $sku = $skuData[$goods_sku_id];
  108. // 验证SKU是否属于该商品
  109. if ($sku->goods_id != $goods_id) {
  110. throw new Exception("商品规格不匹配");
  111. }
  112. // 获取规格属性字符串(单规格商品的sku_attr为空)
  113. $sku_attr = $skuAttrData[$goods_sku_id] ?? '';
  114. // 构建商品对象,模拟购物车数据结构
  115. $goodsItem = (object)[
  116. 'goods_id' => $goods_id,
  117. 'goods_sku_id' => $goods_sku_id,
  118. 'nums' => $nums,
  119. 'goods' => $goods,
  120. 'sku' => $sku,
  121. 'sku_attr' => $sku_attr
  122. ];
  123. $processedGoodsList[] = $goodsItem;
  124. }
  125. // 计算商品价格和运费(统一使用SKU进行计算)
  126. foreach ($processedGoodsList as $item) {
  127. $goodsItemData = [];
  128. if (empty($item->goods) || empty($item->sku)) {
  129. throw new Exception("商品已下架");
  130. }
  131. // 库存验证(统一使用SKU库存)
  132. if ($item->sku->stocks < $item->nums) {
  133. throw new Exception("商品库存不足,请重新修改数量");
  134. }
  135. // 统一使用SKU数据进行计算
  136. $goodsItemData['image'] = !empty($item->sku->image) ? $item->sku->image : $item->goods->image;
  137. $goodsItemData['price'] = $item->sku->price;
  138. // $goodsItemData['lineation_price'] = $item->sku->lineation_price;
  139. $goodsItemData['sku_sn'] = $item->sku->sku_sn;
  140. $amount = bcmul($item->sku->price, $item->nums, 2);
  141. $goodsItemData['amount'] = $amount;
  142. // 订单应付金额
  143. $orderInfo['amount'] = bcadd($orderInfo['amount'], $amount, 2);
  144. // 商品总价
  145. $orderInfo['goods_price'] = bcadd($orderInfo['goods_price'], $amount, 2);
  146. // 商品数量累计
  147. $orderInfo['goods_num'] += $item->nums;
  148. $freight_id = $item->goods->express_template_id;
  149. // 计算邮费【合并运费模板】
  150. if (!isset($shippingTemp[$freight_id])) {
  151. $shippingTemp[$freight_id] = [
  152. 'nums' => $item->nums,
  153. 'weight' => $item->sku->weight,
  154. 'amount' => $amount
  155. ];
  156. } else {
  157. $shippingTemp[$freight_id] = [
  158. 'nums' => bcadd($shippingTemp[$freight_id]['nums'], $item->nums, 2),
  159. 'weight' => bcadd($shippingTemp[$freight_id]['weight'], $item->sku->weight, 2),
  160. 'amount' => bcadd($shippingTemp[$freight_id]['amount'], $amount, 2)
  161. ];
  162. }
  163. // 创建订单商品数据 (基于正确的表结构)
  164. $orderItemData = [
  165. 'user_id' => $userId,
  166. 'order_sn' => '', // 将在订单创建后补充
  167. 'goods_sn' => $item->goods->goods_sn ?: '', // 商品货号
  168. 'sku_sn' => $item->sku->sku_sn ?: '', // SKU编号
  169. 'goods_type' => $item->goods->type ?: 0, // 商品类型
  170. 'goods_id' => $item->goods->id,
  171. 'goods_sku_attr' => $item->sku->sku_attr,
  172. 'goods_spec_value_ids' => $item->sku->spec_value_ids,
  173. 'goods_sku_id' => $item->sku->id,
  174. 'goods_title' => $item->goods->title,
  175. 'goods_market_price' => $item->sku->market_price ?: 0, // 市场价
  176. 'goods_original_price' => $item->sku->price, // 商城售价
  177. 'goods_price' => $amount, // 实付金额
  178. 'goods_image' => $goodsItemData['image'],
  179. 'goods_weight' => $item->sku->weight ?: 0,
  180. 'nums' => $item->nums,
  181. 'sale_status' => 0, // 销售状态:0=待申请
  182. 'comment_status' => 0, // 评论状态:0=未评论
  183. 'status' => 1, // 状态
  184. // 添加分类和品牌信息用于优惠券计算 (临时字段,不会保存到数据库)
  185. // 'category_id' => $item->goods->category_ids,
  186. 'brand_id' => $item->goods->brand_id,
  187. ];
  188. $orderItem[] = $orderItemData;
  189. }
  190. // 按运费模板计算
  191. foreach ($shippingTemp as $key => $item) {
  192. $shippingfee = Freight::calculate($key, $areaId, $item['nums'], $item['weight'], $item['amount']);
  193. $orderInfo['express_fee'] = bcadd($orderInfo['express_fee'], $shippingfee, 2);
  194. }
  195. // 订单金额(商品价格+运费)
  196. $orderInfo['order_amount'] = bcadd($orderInfo['goods_price'], $orderInfo['express_fee'], 2);
  197. // 订单应付金额(暂时等于订单金额,后续会减去优惠)
  198. $orderInfo['amount'] = $orderInfo['order_amount'];
  199. // if (!empty($userCoupon)) {
  200. // // 校验优惠券
  201. // $goods_ids = array_column($orderItem, 'goods_id');
  202. // $category_ids = array_column($orderItem, 'category_id');
  203. // $brand_ids = array_column($orderItem, 'brand_id');
  204. // $couponModel = new Coupon();
  205. // $coupon = $couponModel->getCoupon($userCoupon['coupon_id'])
  206. // ->checkCoupon()
  207. // ->checkOpen()
  208. // ->checkUseTime($userCoupon['createtime'])
  209. // ->checkConditionGoods($goods_ids, $userId, $category_ids, $brand_ids);
  210. // // 计算折扣金额,判断是使用不含运费,还是含运费的金额
  211. // $amount = !isset($config['shippingfeecoupon']) || $config['shippingfeecoupon'] == 0 ? $orderInfo['goods_price'] : $orderInfo['order_amount'];
  212. // list($new_money, $coupon_money) = $coupon->doBuy($amount);
  213. // // 判断优惠金额是否超出总价,超出则直接设定优惠金额为总价
  214. // $orderInfo['coupon_discount_fee'] = $coupon_money > $amount ? $amount : $coupon_money;
  215. // $orderInfo['discount_fee'] = $orderInfo['coupon_discount_fee'];
  216. // }
  217. // 计算最终应付金额【订单金额减去折扣】
  218. $orderInfo['amount'] = max(0, bcsub($orderInfo['order_amount'], $orderInfo['discount_fee'], 2));
  219. $orderInfo['pay_amount'] = $orderInfo['amount']; // 实际付款金额等于应付金额
  220. $orderInfo['discount_fee'] = bcadd($orderInfo['discount_fee'], 0, 2);
  221. return [
  222. $orderItem,
  223. $processedGoodsList,
  224. $userCoupon
  225. ];
  226. }
  227. /**
  228. * 统一的创建订单方法
  229. * @param int $address_id 地址ID
  230. * @param int $user_id 用户ID
  231. * @param array $goods_list 标准化的商品列表
  232. * @param int $user_coupon_id 优惠券ID
  233. * @param string $memo 备注
  234. * @param array $cart_ids 购物车ID数组(如果是购物车模式需要清空)
  235. * @return Order
  236. * @throws Exception
  237. */
  238. public static function createOrder($addressId, $userId, $goodsList, $userCouponId = 0, $remark = '')
  239. {
  240. $address = Address::get($addressId);
  241. if (!$address || $address['user_id'] != $userId) {
  242. throw new Exception("地址未找到");
  243. }
  244. if (empty($goodsList)) {
  245. throw new Exception("商品列表不能为空");
  246. }
  247. $config = get_addon_config('shop');
  248. $orderSn = date("Ymdhis") . sprintf("%08d", $userId) . mt_rand(1000, 9999);
  249. // 订单主表信息 (基于新表结构)
  250. $orderInfo = [
  251. 'type' => 1, // 1:普通订单
  252. 'source' => 'H5', // 订单来源 (暂定H5,可根据实际情况调整)
  253. 'order_sn' => $orderSn,
  254. 'user_id' => $userId,
  255. 'amount' => 0, // 订单应付金额
  256. 'goods_price' => 0, // 商品总费用
  257. 'goods_num' => 0, // 商品数量
  258. 'discount_fee' => 0, // 优惠金额
  259. 'coupon_discount_fee' => 0, // 优惠券金额
  260. 'promo_discount_fee' => 0, // 营销金额
  261. 'order_amount' => 0, // 订单金额
  262. 'pay_amount' => 0, // 实际付款金额
  263. 'pay_type' => '', // 支付方式
  264. 'pay_time' => null, // 支付时间
  265. 'delivery_type' => 1, // 发货方式
  266. 'express_name' => '', // 快递名称
  267. 'express_no' => '', // 快递单号
  268. 'express_fee' => 0, // 配送费用
  269. 'expire_time' => time() + $config['order_timeout'], // 过期时间
  270. 'order_status' => \app\common\Enum\OrderEnum::STATUS_CREATE, // 待付款
  271. 'invoice_status' => 0, // 发票开具状态
  272. 'remark' => $remark, // 用户备注
  273. 'user_coupon_id' => $userCouponId ?: null,
  274. 'ip' => request()->ip(), // IP地址
  275. 'status' => 'normal'
  276. ];
  277. // 通过商品列表计算订单明细
  278. list($orderItem, $calculatedGoodsList, $userCoupon) = self::computeGoods($orderInfo, $goodsList, $userId, $address->area_id, $userCouponId);
  279. // 创建订单
  280. $order = self::createOrderWithTransaction($orderInfo, $orderItem, $calculatedGoodsList, $userCoupon, $address);
  281. return $order;
  282. }
  283. /**
  284. * 在事务中创建订单
  285. * @param array $orderInfo 订单信息
  286. * @param array $orderItem 订单商品列表
  287. * @param array $goodsList 商品列表
  288. * @param object $userCoupon 优惠券
  289. * @param object $address 地址信息
  290. * @return Order
  291. * @throws Exception
  292. */
  293. protected static function createOrderWithTransaction($orderInfo, $orderItem, $goodsList, $userCoupon, $address)
  294. {
  295. $order = null;
  296. Db::startTrans();
  297. try {
  298. // 创建订单
  299. $order = Order::create($orderInfo, true);
  300. // 为每个订单商品添加订单ID和订单号
  301. foreach ($orderItem as &$item) {
  302. $item['order_id'] = $order->id;
  303. $item['order_sn'] = $order->order_sn;
  304. // 移除临时字段
  305. unset($item['category_id'], $item['brand_id']);
  306. }
  307. unset($item);
  308. // 创建订单地址信息
  309. $orderAddressData = [
  310. 'order_id' => $order->id,
  311. 'user_id' => $orderInfo['user_id'],
  312. 'consignee' => $address->receiver,
  313. 'mobile' => $address->mobile,
  314. 'province_name' => $address->province->name ?? '',
  315. 'city_name' => $address->city->name ?? '',
  316. 'district_name' => $address->area->name ?? '',
  317. 'address' => $address->address,
  318. 'province_id' => $address->province_id,
  319. 'city_id' => $address->city_id,
  320. 'district_id' => $address->area_id,
  321. ];
  322. OrderAddress::create($orderAddressData);
  323. // 减库存
  324. foreach ($goodsList as $index => $item) {
  325. if ($item->sku) {
  326. $item->sku->setDec('stocks', $item->nums);
  327. }
  328. $item->goods->setDec("stocks", $item->nums);
  329. }
  330. // 计算单个商品折扣后的价格 (基于新字段名)
  331. $saleamount = bcsub($order['amount'], $order['express_fee'], 2);
  332. $saleratio = $order['goods_price'] > 0 ? bcdiv($saleamount, $order['goods_price'], 10) : 1;
  333. $saleremains = $saleamount;
  334. foreach ($orderItem as $index => &$item) {
  335. if (!isset($orderItem[$index + 1])) {
  336. $saleprice = $saleremains;
  337. } else {
  338. $saleprice = $order['discount_fee'] == 0 ? bcmul($item['goods_original_price'], $item['nums'], 2) : bcmul(bcmul($item['goods_original_price'], $item['nums'], 2), $saleratio, 2);
  339. }
  340. $saleremains = bcsub($saleremains, $saleprice, 2);
  341. $item['goods_price'] = $saleprice;
  342. }
  343. unset($item);
  344. // 批量创建订单商品数据
  345. if (!empty($orderItem)) {
  346. (new OrderGoods())->saveAll($orderItem);
  347. }
  348. // 修改地址使用次数
  349. if ($address) {
  350. $address->setInc('used_nums');
  351. }
  352. // 优惠券已使用
  353. if (!empty($userCoupon)) {
  354. $userCoupon->save(['is_used' => 2]);
  355. }
  356. // 提交事务
  357. Db::commit();
  358. } catch (Exception $e) {
  359. Db::rollback();
  360. throw new Exception($e->getMessage());
  361. }
  362. // 记录操作
  363. OrderAction::push($orderInfo['order_sn'], '系统', '订单创建成功');
  364. // 订单应付金额为0时直接结算
  365. if ($order['amount'] == 0) {
  366. Order::settle($order->order_sn, 0);
  367. $order = Order::get($order->id);
  368. }
  369. return $order;
  370. }
  371. /**
  372. * 验证商品规格参数
  373. * @param array $goods_list 商品列表
  374. * @throws Exception
  375. */
  376. public static function validateGoodsList($goods_list)
  377. {
  378. if (empty($goods_list) || !is_array($goods_list)) {
  379. throw new Exception("商品列表不能为空");
  380. }
  381. foreach ($goods_list as $item) {
  382. if (!isset($item['goods_id']) || !is_numeric($item['goods_id']) || $item['goods_id'] <= 0) {
  383. throw new Exception("商品ID无效");
  384. }
  385. if (!isset($item['nums']) || !is_numeric($item['nums']) || $item['nums'] <= 0) {
  386. throw new Exception("商品数量必须大于0");
  387. }
  388. if (isset($item['goods_sku_id']) && !is_numeric($item['goods_sku_id'])) {
  389. throw new Exception("商品规格ID无效");
  390. }
  391. }
  392. }
  393. /**
  394. * 统一的订单计算方法(用于预览订单)
  395. * @param array $goods_list 标准化的商品列表
  396. * @param int $user_id 用户ID
  397. * @param int $area_id 地区ID
  398. * @param int $user_coupon_id 优惠券ID
  399. * @return array
  400. * @throws Exception
  401. */
  402. public static function calculateOrder($goodsList, $userId, $areaId = 0, $userCouponId = 0)
  403. {
  404. if (empty($goodsList)) {
  405. throw new Exception("商品列表不能为空");
  406. }
  407. // 验证商品列表格式
  408. self::validateGoodsList($goodsList);
  409. // 订单基础信息(用于计算,不包含订单号)
  410. $orderInfo = [
  411. 'amount' => 0, // 应付金额
  412. 'goods_price' => 0, // 商品金额 (不含运费)
  413. 'goods_num' => 0, // 商品数量
  414. 'discount_fee' => 0, // 总优惠金额
  415. 'coupon_discount_fee' => 0, // 优惠券金额
  416. 'promo_discount_fee' => 0, // 营销金额
  417. 'order_amount' => 0, // 总金额 (含运费)
  418. 'express_fee' => 0, // 运费
  419. ];
  420. // 计算商品明细
  421. list($orderItem, $calculatedGoodsList, $userCoupon) = self::computeGoods($orderInfo, $goodsList, $userId, $areaId, $userCouponId);
  422. return [
  423. 'orderItem' => $orderItem,
  424. 'goodsList' => $calculatedGoodsList,
  425. 'orderInfo' => $orderInfo,
  426. 'userCoupon' => $userCoupon
  427. ];
  428. }
  429. /**
  430. * 订单列表
  431. *
  432. * @param $param
  433. * @return \think\Paginator
  434. */
  435. public static function getOrderList($userId = 0, $param =[],$status = [])
  436. {
  437. $pageSize = 15;
  438. if (!empty($param['pageSize'])) {
  439. $pageSize = $param['pageSize'];
  440. }
  441. return Order::with(['orderGoods'])
  442. ->where(function ($query) use ($param) {
  443. if (!empty($userId)) {
  444. $query->where('user_id', $userId);
  445. }
  446. if (!empty($status)) {
  447. $query->whereIn('order_status', $status );
  448. }
  449. if (isset($param['keywords']) && $param['keywords'] != '') {
  450. $query->where('order_sn', 'in', function ($query) use ($param) {
  451. return $query->name('shop_order_goods')->where('order_sn|goods_title', 'like', '%' . $param['q'] . '%')->field('order_sn');
  452. });
  453. }
  454. })
  455. ->order('createtime desc')
  456. ->paginate($pageSize, false, ['query' => request()->get()]);
  457. }
  458. /**
  459. *
  460. * @ 订单信息
  461. * @param $orderId
  462. * @param $userId
  463. * @return array|false|\PDOStatement|string|Model
  464. */
  465. public static function getDetail($orderId, $userId)
  466. {
  467. return Order::with(['orderGoods'])
  468. ->where('id', $orderId)
  469. ->where('user_id', $userId)
  470. ->find();
  471. }
  472. // 查询地址信息
  473. public static function getAddressInfo($orderId)
  474. {
  475. return OrderAddress::where('order_id', $orderId)->find();
  476. }
  477. /**
  478. * 判断订单是否失效
  479. * @param $order_sn
  480. * @return bool
  481. */
  482. public static function isExpired($orderSn)
  483. {
  484. $orderInfo = self::getByOrderSn($orderSn);
  485. //订单过期
  486. if (!$orderInfo['orderstate'] && !$orderInfo['paystate'] && time() > $orderInfo['expiretime']) {
  487. // 启动事务
  488. Db::startTrans();
  489. try {
  490. $orderInfo->save(['orderstate' => 2]);
  491. //库存恢复
  492. OrderGoods::setGoodsStocksInc($orderInfo->order_sn);
  493. //恢复优惠券
  494. UserCoupon::resetUserCoupon($orderInfo->user_coupon_id, $orderInfo->order_sn);
  495. // 提交事务
  496. Db::commit();
  497. } catch (\Exception $e) {
  498. // 回滚事务
  499. Db::rollback();
  500. }
  501. return true;
  502. }
  503. return false;
  504. }
  505. public static function getByOrderSn($orderSn)
  506. {
  507. return Order::where('order_sn', $orderSn)->find();
  508. }
  509. public static function getByOrderId($orderId)
  510. {
  511. return Order::where('id', $orderId)->find();
  512. }
  513. }