OrderService.php 24 KB

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