OrderService.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  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\Address;
  7. use app\common\model\UserCoupon;
  8. use app\common\model\Goods;
  9. use app\common\model\Sku;
  10. use app\common\model\Freight;
  11. use think\Db;
  12. use think\Exception;
  13. use app\common\model\OrderAddress;
  14. use app\common\Enum\OrderEnum;
  15. use app\common\exception\BusinessException;
  16. use app\common\Service\Order\OrderActionService;
  17. use app\common\Enum\OrderActionEnum;
  18. use app\common\Service\SkuSpec;
  19. use app\common\Service\ParentOrderService;
  20. use app\common\Service\DiscountService;
  21. /**
  22. * 订单服务类
  23. * 封装订单创建相关逻辑
  24. *
  25. * 新增功能:
  26. * - createSingleGoodsOrders(): 创建单商品订单,一个商品一个订单
  27. *
  28. * 使用示例:
  29. *
  30. * // 创建单商品订单(一个商品一个订单)
  31. * $goodsList = [
  32. * ['goods_id' => 1, 'goods_sku_id' => 10, 'nums' => 2],
  33. * ['goods_id' => 2, 'goods_sku_id' => 20, 'nums' => 1],
  34. * ['goods_id' => 3, 'goods_sku_id' => 30, 'nums' => 3]
  35. * ];
  36. * $orders = OrderService::createSingleGoodsOrders($addressId, $userId, $goodsList, $userCouponId, $remark);
  37. * // 返回3个订单对象的数组,每个商品对应一个订单
  38. *
  39. * // 创建传统订单(多商品合并为一个订单)
  40. * $order = OrderService::createOrder($addressId, $userId, $goodsList, $userCouponId, $remark);
  41. * // 返回1个包含所有商品的订单对象
  42. */
  43. class OrderService
  44. {
  45. /**
  46. * 订单金额
  47. * @var array
  48. */
  49. protected static $orderPrice = [
  50. 'amount' => 0, //订单应付金额
  51. 'goods_price' => 0, //商品总费用
  52. 'goods_num' => 0, //商品数量
  53. 'discount_fee' => 0, //优惠金额
  54. 'coupon_discount_fee' => 0, //优惠券金额
  55. 'promo_discount_fee' => 0, //营销金额
  56. 'total_discount_amount' => 0, //总优惠
  57. 'order_amount' => 0, //订单金额
  58. 'pay_amount' => 0, //实际付款金额
  59. 'pay_original_amount' => 0, //原始支付金额
  60. 'pay_remain_amount' => 0, //剩余支付金额
  61. 'express_fee' => 0, //配送费用
  62. 'activity_discount_amount' => 0, //活动折扣金额(新增)
  63. 'goods_original_price' => 0, //商品原价总额(新增)
  64. 'order_snapshot' => null, //订单快照,记录折扣等详细信息
  65. ];
  66. /**
  67. * 初始化订单价格
  68. * @return array
  69. */
  70. protected static function initOrderPrice()
  71. {
  72. return [
  73. 'amount' => 0, //订单应付金额
  74. 'goods_price' => 0, //商品总费用
  75. 'goods_num' => 0, //商品数量
  76. 'discount_fee' => 0, //优惠金额
  77. 'coupon_discount_fee' => 0, //优惠券金额
  78. 'promo_discount_fee' => 0, //营销金额
  79. 'total_discount_amount' => 0, //总优惠
  80. 'order_amount' => 0, //订单金额
  81. 'pay_amount' => 0, //实际付款金额
  82. 'pay_original_amount' => 0, //原始支付金额
  83. 'pay_remain_amount' => 0, //剩余支付金额
  84. 'express_fee' => 0, //配送费用
  85. 'activity_discount_amount' => 0, //活动折扣金额(新增)
  86. 'goods_original_price' => 0, //商品原价总额(新增)
  87. 'order_snapshot' => null, //订单快照,记录折扣等详细信息
  88. ];
  89. }
  90. /**
  91. * 根据商品列表计算订单明细
  92. * @param array $orderInfo 订单基础信息
  93. * @param array $goods_list 商品列表
  94. * @param int $user_id 用户ID
  95. * @param int $area_id 地区ID
  96. * @param int $user_coupon_id 优惠券ID
  97. * @return array
  98. * @throws
  99. */
  100. protected static function computeGoods(&$orderInfo, $goodsList, $userId, $areaId, $userCouponId = 0)
  101. {
  102. // 初始化订单价格
  103. $orderPrice = self::initOrderPrice();
  104. foreach ($orderPrice as $key => $value) {
  105. $orderInfo[$key] = $value;
  106. }
  107. $orderItem = [];
  108. $shippingTemp = [];
  109. $userCoupon = null;
  110. $processedGoodsList = []; // 处理后的商品列表,避免与参数$goodsList冲突
  111. // 校验优惠券
  112. if ($userCouponId) {
  113. $userCouponModel = new UserCoupon();
  114. $userCoupon = $userCouponModel->checkUserOrUse($userCouponId, $userId);
  115. $orderInfo['user_coupon_id'] = $userCouponId;
  116. }
  117. // 提取所有商品ID和SKU ID,进行批量查询
  118. $goodsIds = array_column($goodsList, 'goods_id');
  119. $skuIds = [];
  120. foreach ($goodsList as $index => $item) {
  121. if (isset($item['goods_sku_id']) && $item['goods_sku_id'] > 0) {
  122. $skuIds[] = $item['goods_sku_id'];
  123. }
  124. }
  125. // 批量查询商品信息
  126. $goodsData = [];
  127. if (!empty($goodsIds)) {
  128. $goodsModel = new Goods();
  129. $goodsCollection = $goodsModel->with(['brand'])
  130. ->where('id', 'in', $goodsIds)
  131. ->where('status', GoodsEnum::STATUS_ON_SALE)
  132. ->select();
  133. foreach ($goodsCollection as $goods) {
  134. $goodsData[$goods->id] = $goods;
  135. }
  136. }
  137. // 批量查询SKU信息
  138. $skuData = [];
  139. $multiSpecSkuIds = []; // 用于存储多规格商品的SKU ID
  140. if (!empty($skuIds)) {
  141. $skuModel = new Sku();
  142. $skuCollection = $skuModel->where('id', 'in', $skuIds)->select();
  143. foreach ($skuCollection as $sku) {
  144. $skuData[$sku->id] = $sku;
  145. // 过滤出有规格值的SKU ID(spec_value_ids不为空)
  146. if (!empty($sku->spec_value_ids)) {
  147. $multiSpecSkuIds[] = $sku->id;
  148. }
  149. }
  150. }
  151. // 批量查询规格属性字符串(只查询多规格商品的SKU)
  152. $skuAttrData = [];
  153. if (!empty($multiSpecSkuIds)) {
  154. $skuAttrData = SkuSpec::getSkuAttrs($multiSpecSkuIds);
  155. }
  156. // 批量查询商品的折扣信息
  157. $goodsDiscountData = [];
  158. $orderSnapshotData = []; // 用于收集订单快照信息
  159. if (!empty($goodsIds)) {
  160. $goodsDiscountData = DiscountService::getBatchGoodsDiscountInfo($goodsIds);
  161. }
  162. // echo "<pre>";
  163. // print_r($goodsDiscountData);
  164. // echo "</pre>";
  165. // exit;
  166. // 验证并构建商品数据
  167. foreach ($goodsList as $item) {
  168. $goods_id = $item['goods_id'];
  169. $goods_sku_id = $item['goods_sku_id']; // 现在所有商品都应该有SKU ID
  170. $nums = $item['nums'];
  171. if ($nums <= 0) {
  172. throw new BusinessException("商品数量必须大于0");
  173. }
  174. // 检查商品是否存在
  175. if (!isset($goodsData[$goods_id])) {
  176. throw new BusinessException("商品已下架");
  177. }
  178. $goods = $goodsData[$goods_id];
  179. // 所有商品都必须有SKU(包括单规格商品的默认SKU)
  180. if (empty($skuData) || !isset($skuData[$goods_sku_id])) {
  181. throw new BusinessException("商品规格不存在");
  182. }
  183. $sku = $skuData[$goods_sku_id];
  184. // 验证SKU是否属于该商品
  185. if ($sku->goods_id != $goods_id) {
  186. throw new BusinessException("商品规格不匹配");
  187. }
  188. // 获取规格属性字符串(单规格商品的sku_attr为空)
  189. $sku_attr = $skuAttrData[$goods_sku_id] ?? '';
  190. // 构建商品对象,模拟购物车数据结构
  191. $goodsItem = (object)[
  192. 'goods_id' => $goods_id,
  193. 'goods_sku_id' => $goods_sku_id,
  194. 'nums' => $nums,
  195. 'goods' => $goods,
  196. 'sku' => $sku,
  197. 'sku_attr' => $sku_attr
  198. ];
  199. $processedGoodsList[] = $goodsItem;
  200. }
  201. // 计算商品价格和运费(统一使用SKU进行计算)
  202. foreach ($processedGoodsList as $item) {
  203. $goodsItemData = [];
  204. if (empty($item->goods) || empty($item->sku)) {
  205. throw new BusinessException("商品已下架");
  206. }
  207. // 库存验证(统一使用SKU库存)
  208. if ($item->sku->stocks < $item->nums) {
  209. throw new BusinessException("商品库存不足,请重新修改数量");
  210. }
  211. // 获取商品折扣信息
  212. $discountInfo = null;
  213. $actualPrice = $item->sku->price; // 默认使用原价
  214. $originalPrice = $item->sku->price;
  215. if (isset($goodsDiscountData[$item->goods_id])) {
  216. // 查找对应SKU的折扣信息
  217. foreach ($goodsDiscountData[$item->goods_id] as $discount) {
  218. if ($discount['sku_id'] == $item->sku->id) {
  219. $discountInfo = $discount;
  220. $actualPrice = $discount['discount_price']; // 使用折扣价格
  221. break;
  222. }
  223. }
  224. }
  225. // 计算金额
  226. $amount = bcmul($actualPrice, $item->nums, 2); // 使用实际价格计算
  227. $originalAmount = bcmul($originalPrice, $item->nums, 2); // 原价总额
  228. // 统一使用SKU数据进行计算
  229. $goodsItemData['image'] = !empty($item->sku->image) ? $item->sku->image : $item->goods->image;
  230. $goodsItemData['price'] = $actualPrice; // 使用实际价格(折扣价或原价)
  231. $goodsItemData['original_price'] = $originalPrice; // 原价
  232. $goodsItemData['sku_sn'] = $item->sku->sku_sn;
  233. $goodsItemData['discount_info'] = $discountInfo; // 折扣信息
  234. $goodsItemData['amount'] = $amount;
  235. $goodsItemData['original_amount'] = $originalAmount;
  236. // 订单应付金额
  237. $orderInfo['amount'] = bcadd($orderInfo['amount'], $amount, 2);
  238. // 商品总价
  239. $orderInfo['goods_price'] = bcadd($orderInfo['goods_original_price'], $originalAmount, 2);;
  240. // 商品原价总额
  241. $orderInfo['goods_original_price'] = bcadd($orderInfo['goods_original_price'], $originalAmount, 2);
  242. // 商品数量累计
  243. $orderInfo['goods_num'] += $item->nums;
  244. // 活动折扣金额累计
  245. if ($discountInfo) {
  246. $discountAmount = bcsub($originalAmount, $amount, 2);
  247. $orderInfo['activity_discount_amount'] = bcadd($orderInfo['activity_discount_amount'], $discountAmount, 2);
  248. // 收集折扣信息到订单快照
  249. $orderSnapshotData['discount_activities'][] = [
  250. 'goods_id' => $item->goods_id,
  251. 'goods_title' => $item->goods->title,
  252. 'sku_id' => $item->sku->id,
  253. 'sku_attr' => $item->sku_attr,
  254. 'activity_id' => $discountInfo['activity_id'],
  255. 'activity_name' => $discountInfo['activity_name'],
  256. 'original_price' => $originalPrice,
  257. 'discount_price' => $actualPrice,
  258. 'discount' => $discountInfo['discount'],
  259. 'discount_amount' => $discountAmount,
  260. 'quantity' => $item->nums,
  261. 'total_discount_amount' => $discountAmount,
  262. ];
  263. }
  264. $freight_id = $item->goods->express_template_id;
  265. // 计算邮费【合并运费模板】
  266. if (!isset($shippingTemp[$freight_id])) {
  267. $shippingTemp[$freight_id] = [
  268. 'nums' => $item->nums,
  269. 'weight' => $item->sku->weight,
  270. 'amount' => $amount
  271. ];
  272. } else {
  273. $shippingTemp[$freight_id] = [
  274. 'nums' => bcadd($shippingTemp[$freight_id]['nums'], $item->nums, 2),
  275. 'weight' => bcadd($shippingTemp[$freight_id]['weight'], $item->sku->weight, 2),
  276. 'amount' => bcadd($shippingTemp[$freight_id]['amount'], $amount, 2)
  277. ];
  278. }
  279. // 创建订单商品数据 (基于正确的表结构)
  280. $orderItemData = [
  281. 'user_id' => $userId,
  282. 'order_sn' => '', // 将在订单创建后补充
  283. 'goods_sn' => $item->goods->goods_sn ?: '', // 商品货号
  284. 'sku_sn' => $item->sku->sku_sn ?: '', // SKU编号
  285. 'goods_type' => $item->goods->type ?: 0, // 商品类型
  286. 'goods_id' => $item->goods->id,
  287. 'goods_sku_attr' => $item->sku_attr,
  288. 'goods_spec_value_ids' => $item->sku->spec_value_ids,
  289. 'goods_sku_id' => $item->sku->id,
  290. 'goods_title' => $item->goods->title,
  291. 'goods_market_price' => $item->sku->market_price ?: 0, // 市场价
  292. 'goods_original_price' => $originalPrice, // 商品原价
  293. 'goods_price' => $amount, // 实付金额(折扣价)
  294. 'goods_image' => $goodsItemData['image'],
  295. 'goods_weight' => $item->sku->weight ?: 0,
  296. 'nums' => $item->nums,
  297. 'sale_status' => 0, // 销售状态:0=待申请
  298. 'comment_status' => 0, // 评论状态:0=未评论
  299. 'status' => 1, // 状态
  300. 'supplier_id' => $item->goods->supplier_id ?: 0,
  301. 'inspection_type_id' => $item->goods->inspection_type_id ?: 0,
  302. ];
  303. // 如果有折扣信息,记录活动相关信息
  304. // if ($discountInfo) {
  305. // $orderItemData['activity_id'] = $discountInfo['activity_id'] ?? 0;
  306. // $orderItemData['activity_name'] = $discountInfo['activity_name'] ?? '';
  307. // $orderItemData['discount_amount'] = bcsub($originalAmount, $amount, 2);
  308. // }
  309. $orderItem[] = $orderItemData;
  310. }
  311. // 按运费模板计算
  312. foreach ($shippingTemp as $key => $item) {
  313. $shippingfee = Freight::calculate($key, $areaId, $item['nums'], $item['weight'], $item['amount']);
  314. $orderInfo['express_fee'] = bcadd($orderInfo['express_fee'], $shippingfee, 2);
  315. }
  316. // 订单金额(商品价格+运费)
  317. $orderInfo['order_amount'] = bcadd($orderInfo['goods_price'], $orderInfo['express_fee'], 2);
  318. // 订单应付金额(暂时等于订单金额,后续会减去优惠)
  319. $orderInfo['amount'] = $orderInfo['order_amount'];
  320. // if (!empty($userCoupon)) {
  321. // // 校验优惠券
  322. // $goods_ids = array_column($orderItem, 'goods_id');
  323. // $category_ids = array_column($orderItem, 'category_id');
  324. // $brand_ids = array_column($orderItem, 'brand_id');
  325. // $couponModel = new Coupon();
  326. // $coupon = $couponModel->getCoupon($userCoupon['coupon_id'])
  327. // ->checkCoupon()
  328. // ->checkOpen()
  329. // ->checkUseTime($userCoupon['createtime'])
  330. // ->checkConditionGoods($goods_ids, $userId, $category_ids, $brand_ids);
  331. // // 计算折扣金额,判断是使用不含运费,还是含运费的金额
  332. // $amount = !isset($config['shippingfeecoupon']) || $config['shippingfeecoupon'] == 0 ? $orderInfo['goods_price'] : $orderInfo['order_amount'];
  333. // list($new_money, $coupon_money) = $coupon->doBuy($amount);
  334. // // 判断优惠金额是否超出总价,超出则直接设定优惠金额为总价
  335. // $orderInfo['coupon_discount_fee'] = $coupon_money > $amount ? $amount : $coupon_money;
  336. // $orderInfo['discount_fee'] = $orderInfo['coupon_discount_fee'];
  337. // }
  338. // 汇总所有折扣金额
  339. $orderInfo['discount_fee'] = bcadd($orderInfo['activity_discount_amount'], $orderInfo['coupon_discount_fee'], 2);
  340. $orderInfo['promo_discount_fee'] = $orderInfo['activity_discount_amount']; // 营销金额 = 活动折扣金额
  341. $orderInfo['total_discount_amount'] = $orderInfo['discount_fee']; // 总优惠金额
  342. // 计算最终应付金额【订单金额减去折扣】
  343. $orderInfo['amount'] = max(0, bcsub($orderInfo['order_amount'], $orderInfo['discount_fee'], 2));
  344. $orderInfo['pay_amount'] = $orderInfo['amount']; // 实际付款金额等于应付金额
  345. // 保存订单快照信息
  346. if (!empty($orderSnapshotData)) {
  347. $orderSnapshotData['order_summary'] = [
  348. 'total_goods_original_price' => $orderInfo['goods_original_price'],
  349. 'total_goods_price' => $orderInfo['goods_price'],
  350. 'total_activity_discount' => $orderInfo['activity_discount_amount'],
  351. 'total_coupon_discount' => $orderInfo['coupon_discount_fee'],
  352. 'total_discount' => $orderInfo['discount_fee'],
  353. 'express_fee' => $orderInfo['express_fee'],
  354. 'final_amount' => $orderInfo['amount'],
  355. 'snapshot_time' => time(),
  356. ];
  357. $orderInfo['order_snapshot'] = json_encode($orderSnapshotData, JSON_UNESCAPED_UNICODE);
  358. }
  359. return [
  360. $orderItem,
  361. $processedGoodsList,
  362. $userCoupon
  363. ];
  364. }
  365. /**
  366. * 统一的创建订单方法
  367. * @param int $address_id 地址ID
  368. * @param int $user_id 用户ID
  369. * @param array $goods_list 标准化的商品列表
  370. * @param int $user_coupon_id 优惠券ID
  371. * @param string $memo 备注
  372. * @param array $cart_ids 购物车ID数组(如果是购物车模式需要清空)
  373. * @return Order
  374. * @throws BusinessException
  375. */
  376. public static function createOrder($addressId, $userId, $goodsList, $userCouponId = 0, $remark = '',$supplierId = 0)
  377. {
  378. $address = Address::get($addressId);
  379. if (!$address || $address['user_id'] != $userId) {
  380. throw new BusinessException("地址未找到");
  381. }
  382. if (empty($goodsList)) {
  383. throw new BusinessException("商品列表不能为空");
  384. }
  385. $orderTimeout = ShopConfigService::getConfigs('shop.order.order_timeout',false) ?? 3600;
  386. $orderSn = date("Ymdhis") . sprintf("%08d", $userId) . mt_rand(1000, 9999);
  387. // 订单主表信息 (基于新表结构)
  388. $orderInfo = array_merge(self::initOrderPrice(), [
  389. 'type' => 1, // 1:普通订单
  390. 'order_sn' => $orderSn,
  391. 'user_id' => $userId,
  392. 'expire_time' => time() + $orderTimeout, // 过期时间
  393. 'order_status' => OrderEnum::STATUS_CREATE, // 待付款
  394. 'invoice_status' => 0, // 发票开具状态
  395. 'remark' => $remark, // 用户备注
  396. 'user_coupon_id' => $userCouponId ?: null,
  397. 'ip' => request()->ip(), // IP地址
  398. 'status' => 'normal',
  399. ]);
  400. $orderInfo['platform'] = request()->header('platform', 'H5');
  401. // 通过商品列表计算订单明细
  402. list($orderItem, $calculatedGoodsList, $userCoupon) = self::computeGoods($orderInfo, $goodsList, $userId, $address->area_id, $userCouponId);
  403. // 如果有活动折扣,记录活动信息
  404. if ($orderInfo['activity_discount_amount'] > 0) {
  405. $currentActivity = DiscountService::getCurrentActivity();
  406. if ($currentActivity) {
  407. $orderInfo['activity_type'] = 'discount';
  408. $orderInfo['activity_id'] = $currentActivity['id'];
  409. }
  410. }
  411. $orderInfo['pay_amount'] = bcsub($orderInfo['order_amount'], $orderInfo['discount_fee'], 2);
  412. $orderInfo['pay_original_amount'] = $orderInfo['pay_amount'];
  413. $orderInfo['pay_remain_amount'] = $orderInfo['pay_amount'];
  414. // echo "<pre>";
  415. // print_r($orderInfo);
  416. // echo "</pre>";
  417. // exit;
  418. // 创建订单
  419. $order = self::createOrderWithTransaction($orderInfo, $orderItem, $calculatedGoodsList, $userCoupon, $address);
  420. return $order;
  421. }
  422. /**
  423. * 创建单商品订单 - 一个商品一个订单
  424. * @param int $addressId 地址ID
  425. * @param int $userId 用户ID
  426. * @param array $goodsList 商品列表(支持多商品但会拆分为多个订单)
  427. * @param int $userCouponId 优惠券ID(仅用于第一个订单)
  428. * @param string $remark 备注
  429. * @return array 返回创建的订单数组
  430. * @throws BusinessException
  431. */
  432. public static function createSingleGoodsOrders($addressId, $userId, $goodsList, $userCouponId = 0, $remark = '')
  433. {
  434. // 验证地址
  435. $address = Address::get($addressId);
  436. if (!$address || $address['user_id'] != $userId) {
  437. throw new BusinessException("地址未找到");
  438. }
  439. if (empty($goodsList)) {
  440. throw new BusinessException("商品列表不能为空");
  441. }
  442. // 验证商品列表格式
  443. self::validateGoodsList($goodsList);
  444. $orderTimeout = ShopConfigService::getConfigs('shop.order.order_timeout', false) ?? 3600;
  445. $platform = request()->header('platform', 'H5');
  446. $ip = request()->ip();
  447. $orders = [];
  448. $firstOrder = true;
  449. // 为每个商品创建单独的订单
  450. foreach ($goodsList as $goodsItem) {
  451. // 构建单商品列表
  452. $singleGoodsList = [$goodsItem];
  453. // 生成订单号
  454. $orderSn = date("Ymdhis") . sprintf("%08d", $userId) . mt_rand(1000, 9999);
  455. // 订单主表信息
  456. $orderInfo = array_merge(self::initOrderPrice(), [
  457. 'type' => 1, // 1:普通订单
  458. 'order_sn' => $orderSn,
  459. 'user_id' => $userId,
  460. 'expire_time' => time() + $orderTimeout, // 过期时间
  461. 'order_status' => OrderEnum::STATUS_CREATE, // 待付款
  462. 'invoice_status' => 0, // 发票开具状态
  463. 'remark' => $remark, // 用户备注
  464. 'user_coupon_id' => $firstOrder && $userCouponId > 0 ? $userCouponId : null, // 优惠券仅用于第一个订单
  465. 'ip' => $ip,
  466. 'status' => 'normal',
  467. 'platform' => $platform,
  468. ]);
  469. try {
  470. // 通过单商品列表计算订单明细
  471. list($orderItem, $calculatedGoodsList, $userCoupon) = self::computeGoods(
  472. $orderInfo,
  473. $singleGoodsList,
  474. $userId,
  475. $address->area_id,
  476. $firstOrder && $userCouponId > 0 ? $userCouponId : 0
  477. );
  478. // 如果有活动折扣,记录活动信息
  479. if ($orderInfo['activity_discount_amount'] > 0) {
  480. $currentActivity = DiscountService::getCurrentActivity();
  481. if ($currentActivity) {
  482. $orderInfo['activity_type'] = 'discount';
  483. $orderInfo['activity_id'] = $currentActivity['id'];
  484. }
  485. }
  486. $orderInfo['pay_amount'] = bcsub($orderInfo['order_amount'], $orderInfo['discount_fee'], 2);
  487. $orderInfo['pay_original_amount'] = $orderInfo['pay_amount'];
  488. $orderInfo['pay_remain_amount'] = $orderInfo['pay_amount'];
  489. // 创建订单
  490. $order = self::createOrderWithTransaction($orderInfo, $orderItem, $calculatedGoodsList, $userCoupon, $address);
  491. $orders[] = $order;
  492. // 第一个订单创建完成后,后续订单不再使用优惠券
  493. $firstOrder = false;
  494. } catch (Exception $e) {
  495. // 如果某个订单创建失败,记录错误并继续创建其他订单
  496. \think\Log::error("创建单商品订单失败: " . $e->getMessage() . ", 商品ID: " . $goodsItem['goods_id']);
  497. throw new BusinessException("创建订单失败: " . $e->getMessage());
  498. }
  499. }
  500. if (empty($orders)) {
  501. throw new BusinessException("所有订单创建失败");
  502. }
  503. return $orders;
  504. }
  505. /**
  506. * 在事务中创建订单
  507. * @param array $orderInfo 订单信息
  508. * @param array $orderItem 订单商品列表
  509. * @param array $goodsList 商品列表
  510. * @param object $userCoupon 优惠券
  511. * @param object $address 地址信息
  512. * @return Order
  513. * @throws BusinessException
  514. */
  515. protected static function createOrderWithTransaction($orderInfo, $orderItem, $goodsList, $userCoupon, $address)
  516. {
  517. $order = null;
  518. Db::startTrans();
  519. try {
  520. // 创建订单
  521. $order = Order::create($orderInfo, true);
  522. // 为每个订单商品添加订单ID和订单号
  523. foreach ($orderItem as &$item) {
  524. $item['order_id'] = $order->id;
  525. $item['order_sn'] = $order->order_sn;
  526. // 移除临时字段
  527. unset($item['category_id'], $item['brand_id']);
  528. }
  529. unset($item);
  530. // 创建订单地址信息
  531. $orderAddressData = [
  532. 'order_id' => $order->id,
  533. 'user_id' => $orderInfo['user_id'],
  534. 'consignee' => $address->receiver,
  535. 'mobile' => $address->mobile,
  536. 'province_name' => $address->province->name ?? '',
  537. 'city_name' => $address->city->name ?? '',
  538. 'district_name' => $address->area->name ?? '',
  539. 'address' => $address->address,
  540. 'province_id' => $address->province_id,
  541. 'city_id' => $address->city_id,
  542. 'district_id' => $address->area_id,
  543. ];
  544. OrderAddress::create($orderAddressData);
  545. // 减库存
  546. foreach ($goodsList as $index => $item) {
  547. if ($item->sku) {
  548. $item->sku->setDec('stocks', $item->nums);
  549. }
  550. $item->goods->setDec("stocks", $item->nums);
  551. }
  552. // 计算单个商品折扣后的价格 (基于新字段名)
  553. $saleamount = bcsub($order['amount'], $order['express_fee'], 2);
  554. $saleratio = $order['goods_price'] > 0 ? bcdiv($saleamount, $order['goods_price'], 10) : 1;
  555. $saleremains = $saleamount;
  556. foreach ($orderItem as $index => &$item) {
  557. if (!isset($orderItem[$index + 1])) {
  558. $saleprice = $saleremains;
  559. } else {
  560. $saleprice = $order['discount_fee'] == 0 ? bcmul($item['goods_original_price'], $item['nums'], 2) : bcmul(bcmul($item['goods_original_price'], $item['nums'], 2), $saleratio, 2);
  561. }
  562. $saleremains = bcsub($saleremains, $saleprice, 2);
  563. $item['goods_price'] = $saleprice;
  564. }
  565. unset($item);
  566. // 批量创建订单商品数据
  567. if (!empty($orderItem)) {
  568. (new OrderGoods())->saveAll($orderItem);
  569. }
  570. // 修改地址使用次数
  571. if ($address) {
  572. $address->setInc('used_nums');
  573. }
  574. // 优惠券已使用
  575. if (!empty($userCoupon)) {
  576. $userCoupon->save(['is_used' => 2]);
  577. }
  578. // 提交事务
  579. Db::commit();
  580. } catch (Exception $e) {
  581. Db::rollback();
  582. throw new BusinessException($e->getMessage());
  583. }
  584. // 记录操作
  585. OrderActionService::recordUserAction(
  586. $orderInfo['order_sn'],
  587. OrderActionEnum::ACTION_CREATE,
  588. $orderInfo['user_id'],
  589. '创建订单',
  590. $orderInfo['user_id']
  591. );
  592. // 订单应付金额为0时直接结算
  593. if ($order['amount'] == 0) {
  594. // Order::settle($order->order_sn, 0);
  595. // $order = Order::get($order->id);
  596. return $order;
  597. }
  598. return $order;
  599. }
  600. /**
  601. * 验证商品规格参数
  602. * @param array $goods_list 商品列表
  603. * @throws BusinessException
  604. */
  605. public static function validateGoodsList($goods_list)
  606. {
  607. if (empty($goods_list) || !is_array($goods_list)) {
  608. throw new BusinessException("商品列表不能为空");
  609. }
  610. foreach ($goods_list as $item) {
  611. if (!isset($item['goods_id']) || !is_numeric($item['goods_id']) || $item['goods_id'] <= 0) {
  612. throw new BusinessException("商品ID无效");
  613. }
  614. if (!isset($item['nums']) || !is_numeric($item['nums']) || $item['nums'] <= 0) {
  615. throw new BusinessException("商品数量必须大于0");
  616. }
  617. if (isset($item['goods_sku_id']) && !is_numeric($item['goods_sku_id'])) {
  618. throw new BusinessException("商品规格ID无效");
  619. }
  620. }
  621. }
  622. /**
  623. * 创建父子订单 - 每个商品一个子订单,统一支付父订单
  624. * @param int $addressId 地址ID
  625. * @param int $userId 用户ID
  626. * @param array $goodsList 商品列表
  627. * @param int $userCouponId 优惠券ID
  628. * @param string $remark 备注
  629. * @return array 返回父订单和子订单信息
  630. * @throws BusinessException
  631. */
  632. public static function createParentChildOrders($addressId, $userId, $goodsList, $userCouponId = 0, $remark = '')
  633. {
  634. return ParentOrderService::createParentChildOrders($addressId, $userId, $goodsList, $userCouponId, $remark);
  635. }
  636. /**
  637. * 统一的订单计算方法(用于预览订单)
  638. * @param array $goods_list 标准化的商品列表
  639. * @param int $user_id 用户ID
  640. * @param int $area_id 地区ID
  641. * @param int $user_coupon_id 优惠券ID
  642. * @return array
  643. * @throws BusinessException
  644. */
  645. public static function calculateOrder($goodsList, $userId, $areaId = 0, $userCouponId = 0)
  646. {
  647. if (empty($goodsList)) {
  648. throw new BusinessException("商品列表不能为空");
  649. }
  650. // 验证商品列表格式
  651. self::validateGoodsList($goodsList);
  652. // 订单基础信息(用于计算,不包含订单号)
  653. $orderInfo = self::initOrderPrice();
  654. // 计算商品明细
  655. list($orderItem, $calculatedGoodsList, $userCoupon) = self::computeGoods($orderInfo, $goodsList, $userId, $areaId, $userCouponId);
  656. return [
  657. 'orderItem' => $orderItem,
  658. 'goodsList' => $calculatedGoodsList,
  659. 'orderInfo' => $orderInfo,
  660. 'userCoupon' => $userCoupon
  661. ];
  662. }
  663. /**
  664. * 订单列表
  665. *
  666. * @param $param
  667. * @return \think\Paginator
  668. */
  669. public static function getOrderList($userId = 0, $param =[],$status = [],$supplierId = 0)
  670. {
  671. $pageSize = 10;
  672. if (!empty($param['pageSize'])) {
  673. $pageSize = $param['pageSize'];
  674. }
  675. $orderModel = new Order();
  676. return $orderModel->with(['orderGoods'])
  677. ->where(function ($query) use ($param,$userId,$status) {
  678. if (!empty($userId)) {
  679. $query->where('user_id', $userId);
  680. }
  681. if (!empty($status)) {
  682. $query->whereIn('order_status', $status );
  683. }
  684. if (isset($param['keywords']) && $param['keywords'] != '') {
  685. $query->where('order_sn', 'in', function ($query) use ($param) {
  686. return $query->name('shop_order_goods')->where('order_sn|goods_title', 'like', '%' . $param['q'] . '%')->field('order_sn');
  687. });
  688. }
  689. if (!empty($supplierId)) {
  690. $query->where('order_sn', 'in', function ($query) use ($supplierId) {
  691. return $query->name('shop_order_goods')->where('supplier_id', $supplierId)->field('order_sn');
  692. });
  693. }
  694. })
  695. ->order('createtime desc')
  696. ->paginate($pageSize, false, ['query' => request()->get()]);
  697. }
  698. /**
  699. *
  700. * @ 订单信息
  701. * @param $orderId
  702. * @param $userId
  703. * @return array|false|\PDOStatement|string|Model
  704. */
  705. public static function getDetail($orderId = 0, $userId = 0)
  706. {
  707. $orderModel = new Order();
  708. return $orderModel->with(['orderGoods'])
  709. ->where('id', $orderId)
  710. ->where(function($query) use ($userId){
  711. if($userId > 0){
  712. $query->where('user_id', $userId);
  713. }
  714. })
  715. ->find();
  716. }
  717. public static function getDetailByOrderSn($orderSn)
  718. {
  719. $orderModel = new Order();
  720. return $orderModel->with(['orderGoods'])
  721. ->where('order_sn', $orderSn)
  722. ->find();
  723. }
  724. // 查询地址信息
  725. public static function getAddressInfo($orderId)
  726. {
  727. return OrderAddress::where('order_id', $orderId)->find();
  728. }
  729. /**
  730. * 判断订单是否失效
  731. * @param $order_sn
  732. * @return bool
  733. */
  734. public static function isExpired($orderSn)
  735. {
  736. $orderInfo = self::getByOrderSn($orderSn);
  737. //订单过期
  738. if (!$orderInfo['orderstate'] && !$orderInfo['paystate'] && time() > $orderInfo['expiretime']) {
  739. // 启动事务
  740. Db::startTrans();
  741. try {
  742. $orderInfo->save(['orderstate' => 2]);
  743. //库存恢复
  744. OrderGoods::setGoodsStocksInc($orderInfo->order_sn);
  745. // //恢复优惠券
  746. // UserCoupon::resetUserCoupon($orderInfo->user_coupon_id, $orderInfo->order_sn);
  747. // 提交事务
  748. Db::commit();
  749. } catch (\Exception $e) {
  750. // 回滚事务
  751. Db::rollback();
  752. }
  753. return true;
  754. }
  755. return false;
  756. }
  757. public static function getByOrderSn($orderSn)
  758. {
  759. return Order::where('order_sn', $orderSn)->find();
  760. }
  761. public static function getByOrderId($orderId)
  762. {
  763. return Order::where('id', $orderId)->find();
  764. }
  765. // 获取状态订单统计
  766. public static function getOrderStatusCount($userId = 0)
  767. {
  768. $info = [];
  769. $info['unpay'] = Order::where('user_id', $userId)->where('order_status',OrderEnum::STATUS_CREATE)->count();
  770. $info['unsend'] = Order::where('user_id', $userId)->where('order_status',OrderEnum::STATUS_INSPECTION_PASS)->count();
  771. $info['unrec'] = Order::where('user_id', $userId)->where('order_status',OrderEnum::STATUS_SHIP)->count();
  772. $info['uneva'] = Order::where('user_id', $userId)->where('order_status',OrderEnum::STATUS_CONFIRM)->count();
  773. $info['inspect'] = Order::where('user_id', $userId)
  774. ->whereIn('order_status',[
  775. OrderEnum::STATUS_PAY,
  776. OrderEnum::STATUS_INSPECTION,
  777. OrderEnum::STATUS_INSPECTION_FAIL])
  778. ->count();
  779. return $info;
  780. }
  781. // 更新订单状态
  782. public static function updateOrderStatus($orderId = 0, $userId = 0, $status = 0)
  783. {
  784. $order = self::getDetail($orderId, $userId);
  785. if (!$order) {
  786. throw new BusinessException('订单不存在!');
  787. }
  788. // 验证状态
  789. // if (!OrderEnum::isValidOrderStatus($status)) {
  790. // throw new BusinessException('状态不合法!');
  791. // }
  792. // 要处理每个状态对应的时间字段在枚举类中
  793. $timeField = OrderEnum::STATUS_TIME_MAP[$status];
  794. $updateData = [
  795. 'order_status' => $status,
  796. $timeField => time()
  797. ];
  798. Order::where('id', $orderId)->update($updateData);
  799. return $order;
  800. }
  801. /**
  802. * 获取供应商订单列表 - 关联查询方式
  803. * @param int $supplierId 供应商ID
  804. * @param int $userId 用户ID(可选)
  805. * @param array $param 查询参数
  806. * @param array $status 订单状态筛选
  807. * @return \think\Paginator
  808. */
  809. public static function getSupplierOrderList($supplierId, $userId = 0, $param = [], $status = [])
  810. {
  811. $pageSize = $param['page_size'] ?? 10;
  812. return Order::alias('o')
  813. ->join('shop_order_goods og', 'o.order_sn = og.order_sn', 'inner')
  814. ->with(['orderGoods' => function($query) use ($supplierId) {
  815. $query->where('supplier_id', $supplierId);
  816. }])
  817. ->where('og.supplier_id', $supplierId)
  818. ->where(function ($query) use ($param, $userId, $status) {
  819. if (!empty($userId)) {
  820. $query->where('o.user_id', $userId);
  821. }
  822. if (!empty($status)) {
  823. $query->whereIn('o.order_status', $status);
  824. }
  825. if (isset($param['keywords']) && $param['keywords'] != '') {
  826. $query->where(function($subQuery) use ($param) {
  827. $subQuery->where('o.order_sn', 'like', '%' . $param['keywords'] . '%')
  828. ->whereOr('og.goods_title', 'like', '%' . $param['keywords'] . '%');
  829. });
  830. }
  831. })
  832. ->field('o.*')
  833. ->group('o.id')
  834. ->order('o.createtime desc')
  835. ->paginate($pageSize, false, ['query' => request()->get()]);
  836. }
  837. /**
  838. * 获取供应商订单详情 - 支持订单ID和订单号两种方式
  839. * @param mixed $orderParam 订单ID或订单号
  840. * @param int $supplierId 供应商ID
  841. * @param int $userId 用户ID(可选,用于权限验证)
  842. * @return array|null
  843. */
  844. public static function getSupplierOrderDetail($orderParam, $supplierId, $userId = 0)
  845. {
  846. // 根据参数类型判断是订单ID还是订单号
  847. if (is_numeric($orderParam)) {
  848. // 数字类型,当作订单ID处理
  849. $query = Order::where('id', $orderParam);
  850. } else {
  851. // 字符串类型,当作订单号处理
  852. $query = Order::where('order_sn', $orderParam);
  853. }
  854. // 如果指定了用户ID,添加用户权限验证
  855. if (!empty($userId)) {
  856. $query->where('user_id', $userId);
  857. }
  858. $order = $query->find();
  859. if (!$order) {
  860. return null;
  861. }
  862. // 获取该供应商在此订单中的商品
  863. $orderGoods = OrderGoods::where('order_sn', $order->order_sn)
  864. ->where('supplier_id', $supplierId)
  865. ->select();
  866. // 如果该供应商在此订单中没有商品,返回null
  867. if (empty($orderGoods)) {
  868. return null;
  869. }
  870. $order->order_goods = $orderGoods;
  871. return $order;
  872. }
  873. /**
  874. * 获取供应商订单统计
  875. * @param int $supplierId 供应商ID
  876. * @param int $userId 用户ID(可选)
  877. * @return array
  878. */
  879. public static function getSupplierOrderStatusCount($supplierId, $userId = 0)
  880. {
  881. $baseQuery = function($status) use ($supplierId, $userId) {
  882. $query = Order::alias('o')
  883. ->join('shop_order_goods og', 'o.order_sn = og.order_sn', 'inner')
  884. ->where('og.supplier_id', $supplierId)
  885. ->where('o.order_status', $status);
  886. if (!empty($userId)) {
  887. $query->where('o.user_id', $userId);
  888. }
  889. return $query->count('DISTINCT o.id');
  890. };
  891. return [
  892. 'unpay' => $baseQuery(OrderEnum::STATUS_CREATE), // 待付款
  893. 'unsend' => $baseQuery(OrderEnum::STATUS_PAY), // 待发货
  894. 'unrec' => $baseQuery(OrderEnum::STATUS_SHIP), // 待收货
  895. 'uneva' => $baseQuery(OrderEnum::STATUS_CONFIRM), // 待评价
  896. ];
  897. }
  898. /**
  899. * 验证订单和订单商品是否存在
  900. * @param int $orderId 订单ID
  901. * @param int $orderGoodsId 订单商品ID
  902. * @return array|false 返回订单和订单商品信息,不存在返回false
  903. */
  904. public static function validateOrderAndOrderGoods($orderId, $orderGoodsId)
  905. {
  906. // 查询订单
  907. $order = Order::where('id', $orderId)->find();
  908. if (!$order) {
  909. return false;
  910. }
  911. // 查询订单商品
  912. $orderGoods = OrderGoods::where('id', $orderGoodsId)
  913. ->where('order_id', $orderId)
  914. ->find();
  915. if (!$orderGoods) {
  916. return false;
  917. }
  918. return [
  919. 'order' => $order,
  920. 'order_goods' => $orderGoods
  921. ];
  922. }
  923. /**
  924. * 更新订单商品的验收状态
  925. * @param int $orderGoodsId 订单商品ID
  926. * @param int $inspectStatus 验收状态 0:待验收 1:验收通过 2:验收不通过
  927. * @return bool
  928. */
  929. public static function updateOrderGoodsInspectStatus($orderGoodsId, $inspectStatus,$inspectUid = 0)
  930. {
  931. return OrderGoods::where('id', $orderGoodsId)->update([
  932. 'inspect_status' => $inspectStatus,
  933. 'inspect_time' => time(),
  934. 'inspect_id' => $inspectUid
  935. ]);
  936. }
  937. /**
  938. * 检查订单中所有商品的验收状态
  939. * @param int $orderId 订单ID
  940. * @return array 返回验收状态统计
  941. */
  942. public static function checkOrderInspectStatus($orderId)
  943. {
  944. $orderGoods = OrderGoods::where('order_id', $orderId)->select();
  945. $statusCount = [
  946. 'total' => count($orderGoods), // 总商品数
  947. 'pending' => 0, // 待验收
  948. 'passed' => 0, // 验收通过
  949. 'failed' => 0 // 验收不通过
  950. ];
  951. foreach ($orderGoods as $goods) {
  952. switch ($goods['inspect_status']) {
  953. case 0:
  954. $statusCount['pending']++;
  955. break;
  956. case 1:
  957. $statusCount['passed']++;
  958. break;
  959. case 2:
  960. $statusCount['failed']++;
  961. break;
  962. }
  963. }
  964. return $statusCount;
  965. }
  966. /**
  967. * 根据验收状态决定是否更新订单状态
  968. * @param int $orderId 订单ID
  969. * @param int $userId 用户ID
  970. * @return bool
  971. */
  972. public static function updateOrderStatusByInspectResult($orderId, $userId = 0)
  973. {
  974. $inspectStatus = self::checkOrderInspectStatus($orderId);
  975. // 如果所有商品都验收完成(没有待验收的商品)
  976. if ($inspectStatus['pending'] == 0) {
  977. // 如果所有商品都验收通过
  978. if ($inspectStatus['failed'] == 0 && $inspectStatus['passed'] > 0) {
  979. // 更新订单状态为验收通过
  980. return self::updateOrderStatus($orderId, $userId, OrderEnum::STATUS_INSPECTION_PASS);
  981. }
  982. // 如果所有商品都验收不通过
  983. elseif ($inspectStatus['failed'] > 0 && $inspectStatus['passed'] == 0) {
  984. // 更新订单状态为验收失败
  985. return self::updateOrderStatus($orderId, $userId, OrderEnum::STATUS_INSPECTION_FAIL);
  986. }
  987. // 如果部分商品验收通过,部分不通过
  988. elseif ($inspectStatus['failed'] > 0 && $inspectStatus['passed'] > 0) {
  989. // 混合状态,由业务人员手动处理,不自动更新订单状态
  990. return true;
  991. }
  992. }
  993. return true;
  994. }
  995. /**
  996. * 更新订单商品的发货状态
  997. * @param int $orderGoodsId 订单商品ID
  998. * @param string $expressName 快递公司
  999. * @param string $expressNo 快递单号
  1000. * @param array $expressImage 快递图片
  1001. * @return bool
  1002. */
  1003. public static function updateOrderGoodsDeliveryStatus($orderGoodsId, $expressName, $expressNo, $expressImage = [],$orderExpressId = 0)
  1004. {
  1005. $updateData = [
  1006. 'express_name' => $expressName,
  1007. 'express_no' => $expressNo,
  1008. 'express_image' => is_array($expressImage) ? json_encode($expressImage) : $expressImage,
  1009. 'delivery_status' => 1, // 已发货
  1010. 'updatetime' => time(),
  1011. 'order_express_id' =>$orderExpressId
  1012. ];
  1013. return OrderGoods::where('id', $orderGoodsId)->update($updateData);
  1014. }
  1015. /**
  1016. * 检查订单中所有商品的发货状态
  1017. * @param int $orderId 订单ID
  1018. * @return array 返回发货状态统计
  1019. */
  1020. public static function checkOrderDeliveryStatus($orderId)
  1021. {
  1022. $orderGoods = OrderGoods::where('order_id', $orderId)->select();
  1023. $statusCount = [
  1024. 'total' => count($orderGoods), // 总商品数
  1025. 'pending' => 0, // 待发货
  1026. 'delivered' => 0, // 已发货
  1027. ];
  1028. foreach ($orderGoods as $goods) {
  1029. if ($goods['delivery_status'] == 1) {
  1030. $statusCount['delivered']++;
  1031. } else {
  1032. $statusCount['pending']++;
  1033. }
  1034. }
  1035. return $statusCount;
  1036. }
  1037. /**
  1038. * 根据发货状态决定是否更新订单状态
  1039. * @param int $orderId 订单ID
  1040. * @param int $userId 用户ID
  1041. * @return bool
  1042. */
  1043. public static function updateOrderStatusByDeliveryResult($orderId, $userId = 0)
  1044. {
  1045. $deliveryStatus = self::checkOrderDeliveryStatus($orderId);
  1046. // 如果所有商品都已发货(没有待发货的商品)
  1047. if ($deliveryStatus['pending'] == 0 && $deliveryStatus['delivered'] > 0) {
  1048. // 更新订单状态为已发货
  1049. return self::updateOrderStatus($orderId, $userId, OrderEnum::STATUS_SHIP);
  1050. }
  1051. return true;
  1052. }
  1053. /**
  1054. * 验证订单商品是否可以发货
  1055. * @param int $orderId 订单ID
  1056. * @param int $orderGoodsId 订单商品ID
  1057. * @return array|false 返回订单和订单商品信息,验证失败返回false
  1058. */
  1059. public static function validateOrderGoodsForDelivery($orderId, $orderGoodsId)
  1060. {
  1061. // 验证订单和订单商品是否存在
  1062. $orderData = self::validateOrderAndOrderGoods($orderId, $orderGoodsId);
  1063. if (!$orderData) {
  1064. return false;
  1065. }
  1066. $orderGoods = $orderData['order_goods'];
  1067. // 检查订单商品的状态是都验货通过才可以发货
  1068. // if ($orderGoods['inspect_status'] !== 1) {
  1069. // return false;
  1070. // }
  1071. if (empty($orderGoods['inspect_time'])) {
  1072. return false;
  1073. }
  1074. // 检查该订单商品是否已经发货
  1075. if ($orderGoods['delivery_status'] == 1) {
  1076. return false;
  1077. }
  1078. return $orderData;
  1079. }
  1080. }