OrderService.php 29 KB

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