OrderService.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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_id' => $item->sku->id,
  172. 'goods_title' => $item->goods->title,
  173. 'goods_market_price' => $item->sku->market_price ?: 0, // 市场价
  174. 'goods_original_price' => $item->sku->price, // 商城售价
  175. 'goods_price' => $amount, // 实付金额
  176. 'goods_image' => $goodsItemData['image'],
  177. 'goods_weight' => $item->sku->weight ?: 0,
  178. 'nums' => $item->nums,
  179. 'sale_status' => 0, // 销售状态:0=待申请
  180. 'comment_status' => 0, // 评论状态:0=未评论
  181. 'status' => 1, // 状态
  182. // 添加分类和品牌信息用于优惠券计算 (临时字段,不会保存到数据库)
  183. // 'category_id' => $item->goods->category_ids,
  184. 'brand_id' => $item->goods->brand_id,
  185. ];
  186. $orderItem[] = $orderItemData;
  187. }
  188. // 按运费模板计算
  189. foreach ($shippingTemp as $key => $item) {
  190. $shippingfee = Freight::calculate($key, $areaId, $item['nums'], $item['weight'], $item['amount']);
  191. $orderInfo['express_fee'] = bcadd($orderInfo['express_fee'], $shippingfee, 2);
  192. }
  193. // 订单金额(商品价格+运费)
  194. $orderInfo['order_amount'] = bcadd($orderInfo['goods_price'], $orderInfo['express_fee'], 2);
  195. // 订单应付金额(暂时等于订单金额,后续会减去优惠)
  196. $orderInfo['amount'] = $orderInfo['order_amount'];
  197. // if (!empty($userCoupon)) {
  198. // // 校验优惠券
  199. // $goods_ids = array_column($orderItem, 'goods_id');
  200. // $category_ids = array_column($orderItem, 'category_id');
  201. // $brand_ids = array_column($orderItem, 'brand_id');
  202. // $couponModel = new Coupon();
  203. // $coupon = $couponModel->getCoupon($userCoupon['coupon_id'])
  204. // ->checkCoupon()
  205. // ->checkOpen()
  206. // ->checkUseTime($userCoupon['createtime'])
  207. // ->checkConditionGoods($goods_ids, $userId, $category_ids, $brand_ids);
  208. // // 计算折扣金额,判断是使用不含运费,还是含运费的金额
  209. // $amount = !isset($config['shippingfeecoupon']) || $config['shippingfeecoupon'] == 0 ? $orderInfo['goods_price'] : $orderInfo['order_amount'];
  210. // list($new_money, $coupon_money) = $coupon->doBuy($amount);
  211. // // 判断优惠金额是否超出总价,超出则直接设定优惠金额为总价
  212. // $orderInfo['coupon_discount_fee'] = $coupon_money > $amount ? $amount : $coupon_money;
  213. // $orderInfo['discount_fee'] = $orderInfo['coupon_discount_fee'];
  214. // }
  215. // 计算最终应付金额【订单金额减去折扣】
  216. $orderInfo['amount'] = max(0, bcsub($orderInfo['order_amount'], $orderInfo['discount_fee'], 2));
  217. $orderInfo['pay_amount'] = $orderInfo['amount']; // 实际付款金额等于应付金额
  218. $orderInfo['discount_fee'] = bcadd($orderInfo['discount_fee'], 0, 2);
  219. return [
  220. $orderItem,
  221. $processedGoodsList,
  222. $userCoupon
  223. ];
  224. }
  225. /**
  226. * 统一的创建订单方法
  227. * @param int $address_id 地址ID
  228. * @param int $user_id 用户ID
  229. * @param array $goods_list 标准化的商品列表
  230. * @param int $user_coupon_id 优惠券ID
  231. * @param string $memo 备注
  232. * @param array $cart_ids 购物车ID数组(如果是购物车模式需要清空)
  233. * @return Order
  234. * @throws Exception
  235. */
  236. public static function createOrder($addressId, $userId, $goodsList, $userCouponId = 0, $remark = '')
  237. {
  238. $address = Address::get($addressId);
  239. if (!$address || $address['user_id'] != $userId) {
  240. throw new Exception("地址未找到");
  241. }
  242. if (empty($goodsList)) {
  243. throw new Exception("商品列表不能为空");
  244. }
  245. $config = get_addon_config('shop');
  246. $orderSn = date("Ymdhis") . sprintf("%08d", $userId) . mt_rand(1000, 9999);
  247. // 订单主表信息 (基于新表结构)
  248. $orderInfo = [
  249. 'type' => 1, // 1:普通订单
  250. 'source' => 'H5', // 订单来源 (暂定H5,可根据实际情况调整)
  251. 'order_sn' => $orderSn,
  252. 'user_id' => $userId,
  253. 'amount' => 0, // 订单应付金额
  254. 'goods_price' => 0, // 商品总费用
  255. 'goods_num' => 0, // 商品数量
  256. 'discount_fee' => 0, // 优惠金额
  257. 'coupon_discount_fee' => 0, // 优惠券金额
  258. 'promo_discount_fee' => 0, // 营销金额
  259. 'order_amount' => 0, // 订单金额
  260. 'pay_amount' => 0, // 实际付款金额
  261. 'pay_type' => '', // 支付方式
  262. 'pay_time' => null, // 支付时间
  263. 'delivery_type' => 1, // 发货方式
  264. 'express_name' => '', // 快递名称
  265. 'express_no' => '', // 快递单号
  266. 'express_fee' => 0, // 配送费用
  267. 'expire_time' => time() + $config['order_timeout'], // 过期时间
  268. 'order_status' => \app\common\Enum\OrderEnum::STATUS_CREATE, // 待付款
  269. 'invoice_status' => 0, // 发票开具状态
  270. 'remark' => $remark, // 用户备注
  271. 'user_coupon_id' => $userCouponId ?: null,
  272. 'ip' => request()->ip(), // IP地址
  273. 'status' => 'normal'
  274. ];
  275. // 通过商品列表计算订单明细
  276. list($orderItem, $calculatedGoodsList, $userCoupon) = self::computeGoods($orderInfo, $goodsList, $userId, $address->area_id, $userCouponId);
  277. // 创建订单
  278. $order = self::createOrderWithTransaction($orderInfo, $orderItem, $calculatedGoodsList, $userCoupon, $address);
  279. return $order;
  280. }
  281. /**
  282. * 在事务中创建订单
  283. * @param array $orderInfo 订单信息
  284. * @param array $orderItem 订单商品列表
  285. * @param array $goodsList 商品列表
  286. * @param object $userCoupon 优惠券
  287. * @param object $address 地址信息
  288. * @return Order
  289. * @throws Exception
  290. */
  291. protected static function createOrderWithTransaction($orderInfo, $orderItem, $goodsList, $userCoupon, $address)
  292. {
  293. $order = null;
  294. Db::startTrans();
  295. try {
  296. // 创建订单
  297. $order = Order::create($orderInfo, true);
  298. // 为每个订单商品添加订单ID和订单号
  299. foreach ($orderItem as &$item) {
  300. $item['order_id'] = $order->id;
  301. $item['order_sn'] = $order->order_sn;
  302. // 移除临时字段
  303. unset($item['category_id'], $item['brand_id']);
  304. }
  305. unset($item);
  306. // 创建订单地址信息
  307. $orderAddressData = [
  308. 'order_id' => $order->id,
  309. 'user_id' => $orderInfo['user_id'],
  310. 'consignee' => $address->receiver,
  311. 'mobile' => $address->mobile,
  312. 'province_name' => $address->province->name ?? '',
  313. 'city_name' => $address->city->name ?? '',
  314. 'district_name' => $address->area->name ?? '',
  315. 'address' => $address->address,
  316. 'province_id' => $address->province_id,
  317. 'city_id' => $address->city_id,
  318. 'district_id' => $address->area_id,
  319. ];
  320. OrderAddress::create($orderAddressData);
  321. // 减库存
  322. foreach ($goodsList as $index => $item) {
  323. if ($item->sku) {
  324. $item->sku->setDec('stocks', $item->nums);
  325. }
  326. $item->goods->setDec("stocks", $item->nums);
  327. }
  328. // 计算单个商品折扣后的价格 (基于新字段名)
  329. $saleamount = bcsub($order['amount'], $order['express_fee'], 2);
  330. $saleratio = $order['goods_price'] > 0 ? bcdiv($saleamount, $order['goods_price'], 10) : 1;
  331. $saleremains = $saleamount;
  332. foreach ($orderItem as $index => &$item) {
  333. if (!isset($orderItem[$index + 1])) {
  334. $saleprice = $saleremains;
  335. } else {
  336. $saleprice = $order['discount_fee'] == 0 ? bcmul($item['goods_original_price'], $item['nums'], 2) : bcmul(bcmul($item['goods_original_price'], $item['nums'], 2), $saleratio, 2);
  337. }
  338. $saleremains = bcsub($saleremains, $saleprice, 2);
  339. $item['goods_price'] = $saleprice;
  340. }
  341. unset($item);
  342. // 批量创建订单商品数据
  343. if (!empty($orderItem)) {
  344. (new OrderGoods())->saveAll($orderItem);
  345. }
  346. // 修改地址使用次数
  347. if ($address) {
  348. $address->setInc('usednums');
  349. }
  350. // 优惠券已使用
  351. if (!empty($userCoupon)) {
  352. $userCoupon->save(['is_used' => 2]);
  353. }
  354. // 提交事务
  355. Db::commit();
  356. } catch (Exception $e) {
  357. Db::rollback();
  358. throw new Exception($e->getMessage());
  359. }
  360. // 记录操作
  361. OrderAction::push($orderInfo['order_sn'], '系统', '订单创建成功');
  362. // 订单应付金额为0时直接结算
  363. if ($order['amount'] == 0) {
  364. Order::settle($order->order_sn, 0);
  365. $order = Order::get($order->id);
  366. }
  367. return $order;
  368. }
  369. /**
  370. * 验证商品规格参数
  371. * @param array $goods_list 商品列表
  372. * @throws Exception
  373. */
  374. public static function validateGoodsList($goods_list)
  375. {
  376. if (empty($goods_list) || !is_array($goods_list)) {
  377. throw new Exception("商品列表不能为空");
  378. }
  379. foreach ($goods_list as $item) {
  380. if (!isset($item['goods_id']) || !is_numeric($item['goods_id']) || $item['goods_id'] <= 0) {
  381. throw new Exception("商品ID无效");
  382. }
  383. if (!isset($item['nums']) || !is_numeric($item['nums']) || $item['nums'] <= 0) {
  384. throw new Exception("商品数量必须大于0");
  385. }
  386. if (isset($item['goods_sku_id']) && !is_numeric($item['goods_sku_id'])) {
  387. throw new Exception("商品规格ID无效");
  388. }
  389. }
  390. }
  391. /**
  392. * 统一的订单计算方法(用于预览订单)
  393. * @param array $goods_list 标准化的商品列表
  394. * @param int $user_id 用户ID
  395. * @param int $area_id 地区ID
  396. * @param int $user_coupon_id 优惠券ID
  397. * @return array
  398. * @throws Exception
  399. */
  400. public static function calculateOrder($goodsList, $userId, $areaId = 0, $userCouponId = 0)
  401. {
  402. if (empty($goodsList)) {
  403. throw new Exception("商品列表不能为空");
  404. }
  405. // 验证商品列表格式
  406. self::validateGoodsList($goodsList);
  407. // 订单基础信息(用于计算,不包含订单号)
  408. $orderInfo = [
  409. 'amount' => 0, // 应付金额
  410. 'goods_price' => 0, // 商品金额 (不含运费)
  411. 'goods_num' => 0, // 商品数量
  412. 'discount_fee' => 0, // 总优惠金额
  413. 'coupon_discount_fee' => 0, // 优惠券金额
  414. 'promo_discount_fee' => 0, // 营销金额
  415. 'order_amount' => 0, // 总金额 (含运费)
  416. 'express_fee' => 0, // 运费
  417. ];
  418. // 计算商品明细
  419. list($orderItem, $calculatedGoodsList, $userCoupon) = self::computeGoods($orderInfo, $goodsList, $userId, $areaId, $userCouponId);
  420. return [
  421. 'orderItem' => $orderItem,
  422. 'goodsList' => $calculatedGoodsList,
  423. 'orderInfo' => $orderInfo,
  424. 'userCoupon' => $userCoupon
  425. ];
  426. }
  427. /**
  428. * 订单列表
  429. *
  430. * @param $param
  431. * @return \think\Paginator
  432. */
  433. public static function getOrderList($userId = 0, $param =[],$status = [])
  434. {
  435. $pageSize = 15;
  436. if (!empty($param['pageSize'])) {
  437. $pageSize = $param['pageSize'];
  438. }
  439. return Order::with(['orderGoods'])
  440. ->where(function ($query) use ($param) {
  441. if (!empty($userId)) {
  442. $query->where('user_id', $userId);
  443. }
  444. if (!empty($status)) {
  445. $query->whereIn('order_status', $status );
  446. }
  447. if (isset($param['keywords']) && $param['keywords'] != '') {
  448. $query->where('order_sn', 'in', function ($query) use ($param) {
  449. return $query->name('shop_order_goods')->where('order_sn|goods_title', 'like', '%' . $param['q'] . '%')->field('order_sn');
  450. });
  451. }
  452. })
  453. ->order('createtime desc')
  454. ->paginate($pageSize, false, ['query' => request()->get()]);
  455. }
  456. /**
  457. *
  458. * @ 订单信息
  459. * @param $orderId
  460. * @param $userId
  461. * @return array|false|\PDOStatement|string|Model
  462. */
  463. public static function getDetail($orderId, $userId)
  464. {
  465. return Order::with(['orderGoods'])
  466. ->where('id', $orderId)
  467. ->where('user_id', $userId)->find();
  468. }
  469. /**
  470. * 判断订单是否失效
  471. * @param $order_sn
  472. * @return bool
  473. */
  474. public static function isExpired($orderSn)
  475. {
  476. $orderInfo = self::getByOrderSn($orderSn);
  477. //订单过期
  478. if (!$orderInfo['orderstate'] && !$orderInfo['paystate'] && time() > $orderInfo['expiretime']) {
  479. // 启动事务
  480. Db::startTrans();
  481. try {
  482. $orderInfo->save(['orderstate' => 2]);
  483. //库存恢复
  484. OrderGoods::setGoodsStocksInc($orderInfo->order_sn);
  485. //恢复优惠券
  486. UserCoupon::resetUserCoupon($orderInfo->user_coupon_id, $orderInfo->order_sn);
  487. // 提交事务
  488. Db::commit();
  489. } catch (\Exception $e) {
  490. // 回滚事务
  491. Db::rollback();
  492. }
  493. return true;
  494. }
  495. return false;
  496. }
  497. public static function getByOrderSn($orderSn)
  498. {
  499. return Order::where('order_sn', $orderSn)->find();
  500. }
  501. public static function getByOrderId($orderId)
  502. {
  503. return Order::where('id', $orderId)->find();
  504. }
  505. }