OrderService.php 25 KB

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