OrderService.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services\Common;
  12. use App\Models\AccountLogModel;
  13. use App\Models\ActionLogModel;
  14. use App\Models\GoodsModel;
  15. use App\Models\MemberModel;
  16. use App\Models\OrderModel;
  17. use App\Services\BaseService;
  18. use App\Services\RedisService;
  19. use Illuminate\Support\Facades\DB;
  20. /**
  21. * 订单管理-服务类
  22. * @author laravel开发员
  23. * @since 2020/11/11
  24. * Class OrderService
  25. * @package App\Services\Common
  26. */
  27. class OrderService extends BaseService
  28. {
  29. // 静态对象
  30. protected static $instance = null;
  31. /**
  32. * 构造函数
  33. * @author laravel开发员
  34. * @since 2020/11/11
  35. * OrderService constructor.
  36. */
  37. public function __construct()
  38. {
  39. $this->model = new OrderModel();
  40. }
  41. /**
  42. * 静态入口
  43. * @return static|null
  44. */
  45. public static function make()
  46. {
  47. if (!self::$instance) {
  48. self::$instance = (new static());
  49. }
  50. return self::$instance;
  51. }
  52. /**
  53. * @param $params
  54. * @param int $pageSize
  55. * @return array
  56. */
  57. public function getDataList($params, $pageSize = 15)
  58. {
  59. $query = $this->model->where('mark', 1);
  60. // 店铺筛选
  61. if (isset($params['store_id']) && $params['store_id'] > 0) {
  62. $query->where('store_id', $params['store_id']);
  63. }
  64. // 用户筛选
  65. if (isset($params['user_id']) && $params['user_id'] > 0) {
  66. $query->where('user_id', $params['user_id']);
  67. }
  68. // 状态筛选
  69. if (isset($params['status']) && $params['status'] > 0) {
  70. $query->where('status', $params['status']);
  71. }
  72. // 售后类型筛选(1-售后,2-退款)
  73. if (isset($params['after_type']) && $params['after_type'] > 0) {
  74. $query->where('after_type', $params['after_type']);
  75. }
  76. // 退款状态筛选
  77. if (isset($params['refund_status']) && $params['refund_status'] > 0) {
  78. $query->where('refund_status', $params['refund_status']);
  79. }
  80. // 关键词搜索(订单号、商品名称、收货人手机)
  81. if (isset($params['keyword']) && $params['keyword']) {
  82. $keyword = $params['keyword'];
  83. $query->where(function ($q) use ($keyword) {
  84. $q->where('order_no', 'like', '%' . $keyword . '%')
  85. ->orWhere('receiver_name', 'like', '%' . $keyword . '%')
  86. ->orWhere('receiver_mobile', 'like', '%' . $keyword . '%')
  87. ->orWhereHas('orderGoods', function ($q2) use ($keyword) {
  88. $q2->where('goods_name', 'like', '%' . $keyword . '%');
  89. });
  90. });
  91. }
  92. $list = $query->with(['user', 'orderGoods', 'store'])
  93. ->orderBy('create_time', 'desc')
  94. ->orderBy('id', 'desc')
  95. ->paginate($pageSize);
  96. $list = $list ? $list->toArray() : [];
  97. if ($list && isset($list['data'])) {
  98. foreach ($list['data'] as &$item) {
  99. $item['create_time'] = $item['create_time'] ? date('Y-m-d H:i:s', strtotime($item['create_time'])) : '';
  100. $item['update_time'] = $item['update_time'] ? date('Y-m-d H:i:s', strtotime($item['update_time'])) : '';
  101. $item['user'] = $item['user'] ?? [];
  102. $item['store'] = $item['store'] ?? [];
  103. // 获取第一个商品信息(thumb已通过Model访问器处理)
  104. $item['goods'] = isset($item['order_goods'][0]) ? $item['order_goods'][0] : null;
  105. $item['real_total'] = $item['pay_total'];
  106. $item['pay_total'] = moneyFormat($item['pay_total'] + $item['delivery_fee'],2);
  107. //$item['refund_amount'] = $item['refund_amount']?$item['refund_amount']:$item['pay_total'];
  108. }
  109. }
  110. return [
  111. 'msg' => '操作成功',
  112. 'code' => 0,
  113. 'data' => $list['data'] ?? [],
  114. 'count' => $list['total'] ?? 0,
  115. ];
  116. }
  117. /**
  118. * 获取订单详情
  119. */
  120. public function getInfo($id)
  121. {
  122. $info = $this->model->where('id', $id)->where('mark', 1)
  123. ->with(['user', 'orderGoods', 'store'])
  124. ->first();
  125. if (!$info) {
  126. return ['code' => 1, 'msg' => '订单不存在'];
  127. }
  128. $info = $info->toArray();
  129. $info['create_time'] = $info['create_time'] ? date('Y-m-d H:i:s', strtotime($info['create_time'])) : '';
  130. $info['update_time'] = $info['update_time'] ? date('Y-m-d H:i:s', strtotime($info['update_time'])) : '';
  131. $info['real_total'] = $info['pay_total'];
  132. $info['pay_total'] = moneyFormat($info['pay_total'] + $info['delivery_fee'],2);
  133. if (isset($info['order_goods'])) {
  134. foreach ($info['order_goods'] as &$goods) {
  135. $goods['thumb'] = $goods['thumb'] ? get_image_url($goods['thumb']) : '';
  136. $goods['create_time'] = $goods['create_time'] ? date('Y-m-d H:i:s', strtotime($goods['create_time'])) : '';
  137. $goods['update_time'] = $goods['update_time'] ? date('Y-m-d H:i:s', strtotime($goods['update_time'])) : '';
  138. }
  139. }
  140. return ['code' => 0, 'msg' => '操作成功', 'data' => $info];
  141. }
  142. /**
  143. * 查询
  144. * @param $params
  145. * @return \Illuminate\Database\Eloquent\Builder
  146. */
  147. public function getQuery($params)
  148. {
  149. $where = ['a.mark' => 1];
  150. $userId = isset($params['user_id']) ? $params['user_id'] : 0;
  151. return $this->model->with(['user', 'goods'])->from('orders as a')
  152. ->leftJoin('member as b', 'a.user_id', '=', 'b.id')
  153. ->leftJoin('goods as c', 'c.id', '=', 'a.goods_id')
  154. ->where($where)
  155. ->where(function ($query) use ($params) {
  156. $keyword = isset($params['keyword']) ? $params['keyword'] : '';
  157. if ($keyword) {
  158. $query->where('a.order_no', 'like', "%{$keyword}%");
  159. }
  160. // 接单人
  161. $account = isset($params['account']) ? $params['account'] : '';
  162. if ($account) {
  163. $query->where(function ($query) use ($account) {
  164. $query->where('b.nickname', 'like', "%{$account}%")->orWhere('b.mobile', 'like', "%{$account}%");
  165. });
  166. }
  167. // 商品
  168. $goodsId = isset($params['goods_id']) ? intval($params['goods_id']) : 0;
  169. $goods = isset($params['goods']) ? trim($params['goods']) : '';
  170. if ($goods) {
  171. $query->where(function ($query) use ($goods) {
  172. $query->where('c.goods_name', 'like', "%{$goods}%");
  173. if (preg_match("/^(1[0-9]+|[1-9]+)$/", $goods)) {
  174. $query->where('a.goods_id', intval($goods));
  175. } else {
  176. $query->where('c.goods_name', 'like', "%{$goods}%");
  177. }
  178. });
  179. }
  180. if ($goodsId > 0) {
  181. $query->where('a.goods_id', intval($goodsId));
  182. }
  183. })
  184. ->where(function ($query) use ($params) {
  185. $status = isset($params['status']) ? $params['status'] : 0;
  186. if ($status == 0) {
  187. $query->whereIn('a.status', [2, 3]);
  188. } else if ($status) {
  189. $query->where('a.status', $status);
  190. }
  191. })
  192. ->where(function ($query) use ($userId) {
  193. if ($userId) {
  194. $query->where('a.user_id', '=', $userId);
  195. }
  196. });
  197. }
  198. /**
  199. * 按日期统计订单数
  200. * @param string $beginAt 开始时间
  201. * @param string $endAt 结束时间
  202. * @param int[] $status 状态:数组或数值
  203. * @return mixed
  204. */
  205. public function getCountByTime($beginAt = '', $endAt = '', $status = 3)
  206. {
  207. $cacheKey = "caches:orders:count_{$status}_{$beginAt}_{$endAt}";
  208. $data = RedisService::get($cacheKey);
  209. if ($data) {
  210. return $data;
  211. }
  212. $where = ['mark' => 1];
  213. $data = $this->model->where($where)->where(function ($query) use ($beginAt, $endAt, $status) {
  214. if ($beginAt && $endAt) {
  215. $query->whereBetween('create_time', [strtotime($beginAt), strtotime($endAt)]);
  216. } else if ($beginAt) {
  217. $query->where('create_time', '>=', strtotime($beginAt));
  218. }
  219. if ($status && is_array($status)) {
  220. $query->whereIn('status', $status);
  221. } else if ($status) {
  222. $query->where('status', $status);
  223. }
  224. })->count('id');
  225. if ($data) {
  226. RedisService::set($cacheKey, $data, rand(300, 600));
  227. }
  228. return $data;
  229. }
  230. /**
  231. * 按日期统计订单金额
  232. * @param string $beginAt 开始时间
  233. * @param string $endAt 结束时间
  234. * @param int[] $status 状态:数组或数值
  235. * @return mixed
  236. */
  237. public function getTotalByTime($beginAt = '', $endAt = '', $status = 3)
  238. {
  239. $cacheKey = "caches:orders:total_{$status}_{$beginAt}_{$endAt}";
  240. $data = RedisService::get($cacheKey);
  241. if ($data) {
  242. return $data;
  243. }
  244. $where = ['mark' => 1];
  245. $data = $this->model->where($where)->where(function ($query) use ($beginAt, $endAt, $status) {
  246. if ($beginAt && $endAt) {
  247. $query->whereBetween('create_time', [strtotime($beginAt), strtotime($endAt)]);
  248. } else if ($beginAt) {
  249. $query->where('create_time', '>=', strtotime($beginAt));
  250. }
  251. if ($status && is_array($status)) {
  252. $query->whereIn('status', $status);
  253. } else if ($status) {
  254. $query->where('status', $status);
  255. }
  256. })->sum('total');
  257. if ($data) {
  258. RedisService::set($cacheKey, $data, rand(300, 600));
  259. }
  260. return $data;
  261. }
  262. /**
  263. * 添加或编辑
  264. * @return array
  265. * @since 2020/11/11
  266. * @author laravel开发员
  267. */
  268. public function edit()
  269. {
  270. $params = request()->post();
  271. return parent::edit($params); // TODO: Change the autogenerated stub
  272. }
  273. /**
  274. * 删除订单
  275. */
  276. public function delete()
  277. {
  278. $id = request()->post('id');
  279. if (!$id) {
  280. return ['code' => 1, 'msg' => '参数错误'];
  281. }
  282. if (is_array($id)) {
  283. $result = $this->model->whereIn('id', $id)->update(['mark' => 0]);
  284. } else {
  285. $result = $this->model->where('id', $id)->update(['mark' => 0]);
  286. }
  287. if ($result) {
  288. ActionLogModel::setTitle("删除订单");
  289. ActionLogModel::record();
  290. RedisService::keyDel("caches:orders:*");
  291. return ['code' => 0, 'msg' => '删除成功'];
  292. }
  293. return ['code' => 1, 'msg' => '删除失败'];
  294. }
  295. /**
  296. * 更新订单状态
  297. */
  298. public function status()
  299. {
  300. $id = request()->post('id');
  301. $status = request()->post('status');
  302. $refundStatus = request()->post('refund_status');
  303. $refundRemark = request()->post('refund_remark', '');
  304. if (!$id) {
  305. return ['code' => 1, 'msg' => '参数错误'];
  306. }
  307. $updateData = ['update_time' => time()];
  308. // 更新订单状态
  309. if ($status !== null) {
  310. $updateData['status'] = $status;
  311. // 如果是完成订单,计算佣金
  312. if ($status == 4) {
  313. $order = $this->model->find($id);
  314. if ($order) {
  315. $updateData['bonus'] = round($order->pay_total * 0.05, 2);
  316. }
  317. }
  318. }
  319. // 更新退款状态
  320. if ($refundStatus !== null) {
  321. $updateData['refund_status'] = $refundStatus;
  322. $updateData['refund_remark'] = $refundRemark;
  323. // 如果同意退款,保持原订单状态不变
  324. // 退款状态通过 refund_status 字段管理
  325. }
  326. $result = $this->model->where('id', $id)->update($updateData);
  327. if ($result !== false) {
  328. ActionLogModel::setTitle("更新订单状态");
  329. ActionLogModel::record();
  330. RedisService::keyDel("caches:orders:*");
  331. return ['code' => 0, 'msg' => '操作成功'];
  332. }
  333. return ['code' => 1, 'msg' => '操作失败'];
  334. }
  335. /**
  336. * 完成支付
  337. */
  338. public function completePay()
  339. {
  340. $id = request()->post('id');
  341. $transactionId = request()->post('transaction_id', '');
  342. if (!$id) {
  343. return ['code' => 1, 'msg' => '参数错误'];
  344. }
  345. $order = $this->model->find($id);
  346. if (!$order) {
  347. return ['code' => 1, 'msg' => '订单不存在'];
  348. }
  349. if ($order->status != 1) {
  350. return ['code' => 1, 'msg' => '订单状态不正确'];
  351. }
  352. $updateData = [
  353. 'status' => 2, // 已付款
  354. 'transaction_id' => $transactionId ?: 'PAY' . time() . rand(1000, 9999),
  355. 'pay_at'=> date('Y-m-d H:i:s'),
  356. 'remark'=> '人工审核支付',
  357. 'update_time' => time()
  358. ];
  359. $result = $this->model->where('id', $id)->update($updateData);
  360. if ($result) {
  361. ActionLogModel::setTitle("订单完成支付");
  362. ActionLogModel::record();
  363. RedisService::keyDel("caches:orders:*");
  364. return ['code' => 0, 'msg' => '支付完成'];
  365. }
  366. return ['code' => 1, 'msg' => '操作失败'];
  367. }
  368. /**
  369. * 订单发货
  370. */
  371. public function deliverOrder()
  372. {
  373. $id = request()->post('id');
  374. $deliveryCompany = request()->post('delivery_company', '');
  375. $deliveryNo = request()->post('delivery_no', '');
  376. $deliveryCode = request()->post('delivery_code', '');
  377. if (!$id) {
  378. return ['code' => 1, 'msg' => '参数错误'];
  379. }
  380. $order = $this->model->find($id);
  381. if (!$order) {
  382. return ['code' => 1, 'msg' => '订单不存在'];
  383. }
  384. if ($order->status != 2) {
  385. return ['code' => 1, 'msg' => '订单状态不正确,只有已付款订单可以发货'];
  386. }
  387. if (!$deliveryNo) {
  388. return ['code' => 1, 'msg' => '请填写快递单号'];
  389. }
  390. $updateData = [
  391. 'status' => 3, // 已发货
  392. 'delivery_company' => $deliveryCompany,
  393. 'delivery_no' => $deliveryNo,
  394. 'delivery_code' => $deliveryCode,
  395. 'update_time' => time()
  396. ];
  397. $result = $this->model->where('id', $id)->update($updateData);
  398. if ($result) {
  399. ActionLogModel::setTitle("订单发货");
  400. ActionLogModel::record();
  401. RedisService::keyDel("caches:orders:*");
  402. return ['code' => 0, 'msg' => '发货成功'];
  403. }
  404. return ['code' => 1, 'msg' => '操作失败'];
  405. }
  406. /**
  407. * 订单完成(管理后台)
  408. */
  409. public function completeOrder()
  410. {
  411. $id = request()->post('id');
  412. if (!$id) {
  413. return ['code' => 1, 'msg' => '参数错误'];
  414. }
  415. $order = $this->model->find($id);
  416. if (!$order) {
  417. return ['code' => 1, 'msg' => '订单不存在'];
  418. }
  419. if ($order->status != 3) {
  420. return ['code' => 1, 'msg' => '订单状态不正确,只有已发货订单可以完成'];
  421. }
  422. // 调用用户端的订单完成方法,触发收益结算等业务逻辑
  423. $apiOrderService = \App\Services\Api\OrderService::make();
  424. $result = $apiOrderService->complete($order->user_id, $id);
  425. if ($result) {
  426. ActionLogModel::setTitle("订单完成");
  427. ActionLogModel::record();
  428. RedisService::keyDel("caches:orders:*");
  429. return ['code' => 0, 'msg' => '确认收货成功'];
  430. }
  431. // 获取错误信息
  432. $error = $apiOrderService->getError();
  433. return ['code' => 1, 'msg' => $error ?: '操作失败', 'error' => $error];
  434. }
  435. /**
  436. * 取消订单
  437. */
  438. public function cancelOrder()
  439. {
  440. $id = request()->post('id');
  441. $cancelReason = request()->post('cancel_reason', '');
  442. if (!$id) {
  443. return ['code' => 1, 'msg' => '参数错误'];
  444. }
  445. $order = $this->model->find($id);
  446. if (!$order) {
  447. return ['code' => 1, 'msg' => '订单不存在'];
  448. }
  449. if ($order->status != 1) {
  450. return ['code' => 1, 'msg' => '只有待付款订单可以取消'];
  451. }
  452. $updateData = [
  453. 'mark' => 0, // 标记为删除
  454. 'update_time' => time()
  455. ];
  456. $result = $this->model->where('id', $id)->update($updateData);
  457. if ($result) {
  458. ActionLogModel::setTitle("取消订单");
  459. ActionLogModel::record();
  460. RedisService::keyDel("caches:orders:*");
  461. return ['code' => 0, 'msg' => '订单已取消'];
  462. }
  463. return ['code' => 1, 'msg' => '操作失败'];
  464. }
  465. /**
  466. * 申请退款
  467. */
  468. public function applyRefund()
  469. {
  470. $id = request()->post('id');
  471. $afterType = request()->post('after_type', 2); // 默认退款
  472. $afterRealname = request()->post('after_realname', '');
  473. $afterPhone = request()->post('after_phone', '');
  474. $afterRemark = request()->post('after_remark', '');
  475. if (!$id) {
  476. return ['code' => 1, 'msg' => '参数错误'];
  477. }
  478. if (!$afterRealname) {
  479. return ['code' => 1, 'msg' => '请填写联系人姓名'];
  480. }
  481. if (!$afterPhone) {
  482. return ['code' => 1, 'msg' => '请填写联系电话'];
  483. }
  484. if (!$afterRemark) {
  485. return ['code' => 1, 'msg' => '请填写退款原因'];
  486. }
  487. $order = $this->model->find($id);
  488. if (!$order) {
  489. return ['code' => 1, 'msg' => '订单不存在'];
  490. }
  491. // 只有已付款、已发货、已完成的订单可以申请退款
  492. if (!in_array($order->status, [2, 3, 4])) {
  493. return ['code' => 1, 'msg' => '该订单状态不允许申请退款'];
  494. }
  495. if ($order->refund_status != 0) {
  496. return ['code' => 1, 'msg' => '该订单已申请过退款'];
  497. }
  498. $updateData = [
  499. 'refund_status' => 3, // 待审核
  500. 'after_type' => $afterType, // 1-售后,2-退款
  501. 'after_realname' => $afterRealname,
  502. 'after_phone' => $afterPhone,
  503. 'after_remark' => $afterRemark,
  504. 'update_time' => time()
  505. ];
  506. $result = $this->model->where('id', $id)->update($updateData);
  507. if ($result) {
  508. $typeText = $afterType == 1 ? '售后' : '退款';
  509. ActionLogModel::setTitle("申请{$typeText}");
  510. ActionLogModel::record();
  511. RedisService::keyDel("caches:orders:*");
  512. return ['code' => 0, 'msg' => "{$typeText}申请已提交"];
  513. }
  514. return ['code' => 1, 'msg' => '操作失败'];
  515. }
  516. /**
  517. * 同意退款(审核通过,状态变为已审核)
  518. */
  519. public function agreeRefund()
  520. {
  521. $id = request()->post('id');
  522. $refundRemark = request()->post('refund_remark', '');
  523. if (!$id) {
  524. return ['code' => 1, 'msg' => '参数错误'];
  525. }
  526. $order = $this->model->find($id);
  527. if (!$order) {
  528. return ['code' => 1, 'msg' => '订单不存在'];
  529. }
  530. if ($order->refund_status != 3) {
  531. return ['code' => 1, 'msg' => '该订单未申请退款或已处理'];
  532. }
  533. $updateData = [
  534. 'refund_status' => 2, // 已审核(待确认退款)
  535. 'refund_remark' => $refundRemark ?: '退款申请已通过,待确认退款',
  536. 'update_time' => time()
  537. ];
  538. $result = $this->model->where('id', $id)->update($updateData);
  539. if ($result) {
  540. ActionLogModel::setTitle("同意退款");
  541. ActionLogModel::record();
  542. RedisService::keyDel("caches:orders:*");
  543. return ['code' => 0, 'msg' => '已同意退款,请确认退款'];
  544. }
  545. return ['code' => 1, 'msg' => '操作失败'];
  546. }
  547. /**
  548. * 确认退款(最终完成退款)
  549. */
  550. public function confirmRefund()
  551. {
  552. $id = request()->post('id');
  553. $refundAmount = request()->post('refund_amount', 0);
  554. if (!$id) {
  555. return ['code' => 1, 'msg' => '参数错误'];
  556. }
  557. if ($refundAmount <= 0) {
  558. return ['code' => 1, 'msg' => '请输入退款金额'];
  559. }
  560. $order = $this->model->find($id);
  561. if (!$order) {
  562. return ['code' => 1, 'msg' => '订单不存在'];
  563. }
  564. // 允许待审核(3)和已审核(2)状态的订单进行退款
  565. if (!in_array($order->refund_status, [2, 3])) {
  566. return ['code' => 1, 'msg' => '该订单状态不允许退款'];
  567. }
  568. if ($refundAmount > floatval($order->pay_total + $order->delivery_fee)) {
  569. return ['code' => 1, 'msg' => '退款金额不能大于订单支付金额'];
  570. }
  571. // 使用事务
  572. DB::beginTransaction();
  573. try {
  574. // 调用支付服务退款
  575. $paymentService = \App\Services\PaymentService::make();
  576. $refundData = [
  577. 'money' => $refundAmount,
  578. 'pay_type' => $order->pay_type,
  579. 'order_no' => $order->order_no,
  580. 'out_trade_no' => $order->out_trade_no,
  581. 'transaction_id' => $order->transaction_id,
  582. 'remark' => '订单退款'
  583. ];
  584. $refundResult = $paymentService->refund($refundData, 'store');
  585. if (!$refundResult) {
  586. DB::rollBack();
  587. return ['code' => 1, 'msg' => '退款失败:' . $paymentService->getError() ?: '退款失败'];
  588. }
  589. // 更新订单状态
  590. $updateData = [
  591. 'refund_status' => 1, // 已退款
  592. 'refund_amount' => $refundAmount,
  593. 'update_time' => time()
  594. ];
  595. $result = $this->model->where('id', $id)->update($updateData);
  596. if ($result) {
  597. DB::commit();
  598. ActionLogModel::setTitle("确认退款");
  599. ActionLogModel::record();
  600. RedisService::keyDel("caches:orders:*");
  601. return ['code' => 0, 'msg' => '退款成功'];
  602. }
  603. DB::rollBack();
  604. return ['code' => 1, 'msg' => '更新订单状态失败'];
  605. } catch (\Exception $e) {
  606. DB::rollBack();
  607. return ['code' => 1, 'msg' => '退款失败:' . $e->getMessage()];
  608. }
  609. }
  610. /**
  611. * 拒绝退款
  612. */
  613. public function rejectRefund()
  614. {
  615. $id = request()->post('id');
  616. $refundRemark = request()->post('refund_remark', '');
  617. if (!$id) {
  618. return ['code' => 1, 'msg' => '参数错误'];
  619. }
  620. if (!$refundRemark) {
  621. return ['code' => 1, 'msg' => '请填写拒绝原因'];
  622. }
  623. $order = $this->model->find($id);
  624. if (!$order) {
  625. return ['code' => 1, 'msg' => '订单不存在'];
  626. }
  627. if ($order->refund_status != 3) {
  628. return ['code' => 1, 'msg' => '该订单未申请退款或已处理'];
  629. }
  630. $updateData = [
  631. 'refund_status' => 4, // 审核驳回
  632. 'refund_remark' => $refundRemark,
  633. 'update_time' => time()
  634. ];
  635. $result = $this->model->where('id', $id)->update($updateData);
  636. if ($result) {
  637. ActionLogModel::setTitle("拒绝退款");
  638. ActionLogModel::record();
  639. RedisService::keyDel("caches:orders:*");
  640. return ['code' => 0, 'msg' => '已拒绝退款'];
  641. }
  642. return ['code' => 1, 'msg' => '操作失败'];
  643. }
  644. /**
  645. * 订单统计
  646. * @param int $storeId 商户ID,0表示平台管理员查看全部数据
  647. */
  648. public function getStatistics($storeId = 0)
  649. {
  650. // 总订单数
  651. $total = $this->model->where('mark', 1)
  652. ->when($storeId > 0, function ($query) use ($storeId) {
  653. return $query->where('store_id', $storeId);
  654. })
  655. ->count();
  656. // 总交易额(已完成订单)
  657. $totalAmount = $this->model->where('mark', 1)
  658. ->where('status', 4)
  659. ->when($storeId > 0, function ($query) use ($storeId) {
  660. return $query->where('store_id', $storeId);
  661. })
  662. ->sum('pay_total');
  663. // 待处理订单(待付款 + 已付款)
  664. $pending = $this->model->where('mark', 1)
  665. ->whereIn('status', [1, 2])
  666. ->when($storeId > 0, function ($query) use ($storeId) {
  667. return $query->where('store_id', $storeId);
  668. })
  669. ->count();
  670. // 待退款订单
  671. $refunding = $this->model->where('mark', 1)
  672. ->where('refund_status', 3)
  673. ->when($storeId > 0, function ($query) use ($storeId) {
  674. return $query->where('store_id', $storeId);
  675. })
  676. ->count();
  677. return [
  678. 'code' => 0,
  679. 'msg' => '操作成功',
  680. 'data' => [
  681. 'total' => $total,
  682. 'totalAmount' => number_format($totalAmount, 2, '.', ''),
  683. 'pending' => $pending,
  684. 'refunding' => $refunding
  685. ]
  686. ];
  687. }
  688. }