OrderService.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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. $deliveryList = [];
  394. $result = MpService::make()->requestApi('getDelivery');
  395. $list = isset($result['delivery_list'])?$result['delivery_list'] : [];
  396. if($list){
  397. foreach ($list as $item){
  398. $deliveryList[$item['delivery_id']] = $item;
  399. }
  400. }else{
  401. $deliveryList = config('platform.mpDeliveryList');
  402. }
  403. RedisService::set($cacheKey, $deliveryList, rand(3600, 7200));
  404. }else{
  405. $deliveryList = config('platform.deliveryList');
  406. }
  407. return ['code' => 0, 'msg' =>'获取成功', 'data'=>$deliveryList];
  408. }
  409. /**
  410. * 订单发货
  411. */
  412. public function deliverOrder()
  413. {
  414. $id = request()->post('id');
  415. $deliveryCompany = request()->post('delivery_company', '');
  416. $deliveryNo = request()->post('delivery_no', '');
  417. $deliveryCode = request()->post('delivery_code', '');
  418. if (!$id) {
  419. return ['code' => 1, 'msg' => '参数错误'];
  420. }
  421. // 发货方式
  422. $deliveryType = \App\Services\ConfigService::make()->getConfigByCode('delivery_type',1);
  423. $order = $this->model->with(['user','orderGoods'])->find($id);
  424. $orderGoods = isset($order['orderGoods'])?$order['orderGoods'] : [];
  425. $goodsName = isset($orderGoods[0]['goods_name'])?$orderGoods[0]['goods_name']:'订单商品';
  426. $userInfo = isset($order['user'])?$order['user'] : [];
  427. $openid = isset($userInfo['openid'])?$userInfo['openid'] : '';
  428. $mobile = isset($userInfo['mobile'])?$userInfo['mobile'] : '';
  429. if (!$order) {
  430. return ['code' => 1, 'msg' => '订单不存在'];
  431. }
  432. if ($order->status != 2) {
  433. return ['code' => 1, 'msg' => '订单状态不正确,只有已付款订单可以发货'];
  434. }
  435. if (!$deliveryNo) {
  436. return ['code' => 1, 'msg' => '请填写快递单号'];
  437. }
  438. DB::beginTransaction();
  439. $updateData = [
  440. 'status' => 3, // 已发货
  441. 'delivery_company' => $deliveryCompany,
  442. 'delivery_no' => $deliveryNo,
  443. 'delivery_code' => $deliveryCode,
  444. 'update_time' => time()
  445. ];
  446. if (!$result = $this->model->where('id', $id)->update($updateData)) {
  447. DB::rollBack();
  448. return ['code' => 1, 'msg' => '操作失败'];
  449. }
  450. // 调用小程序发货信息同步接口
  451. $msg = '发货成功';
  452. if($deliveryType == 1 && $openid){
  453. $sendData = [
  454. 'order_key' => [
  455. "order_number_type" => 2,
  456. "transaction_id" => isset($order['transaction_id']) ? $order['transaction_id'] : '',
  457. "out_trade_no" => isset($order['out_trade_no']) ? $order['out_trade_no'] : ''
  458. ],
  459. "delivery_mode" => 1,
  460. "logistics_type" => 1,
  461. "shipping_list" => [
  462. [
  463. "tracking_no" => $deliveryNo,
  464. "express_company" => $deliveryCompany,
  465. "item_desc" => $goodsName,
  466. "contact" => [
  467. "consignor_contact" => isset($order['receiver_mobile']) ? $order['receiver_mobile'] : $mobile
  468. ]
  469. ]
  470. ],
  471. "upload_time" => date('Y-m-d H:i:s'),
  472. "payer" => [
  473. "openid" => $openid
  474. ]
  475. ];
  476. $result = MpService::make()->requestApi('deliverySend',$sendData);
  477. $errcode = isset($result['errcode'])?$result['errcode'] : -1;
  478. $errmsg = isset($result['errmsg']) && $result['errmsg']?$result['errmsg'] : '请求失败';
  479. if($errcode == -1){
  480. $msg = '发货成功,但上传发货信息到小程序失败:'.$errmsg;
  481. }
  482. var_dump($result);
  483. }
  484. if ($result) {
  485. ActionLogModel::setTitle("订单发货");
  486. ActionLogModel::record();
  487. RedisService::keyDel("caches:orders:*");
  488. return ['code' => 0, 'msg' => $msg];
  489. }
  490. return ['code' => 1, 'msg' => '操作失败'];
  491. }
  492. /**
  493. * 订单完成(管理后台)
  494. */
  495. public function completeOrder()
  496. {
  497. $id = request()->post('id');
  498. if (!$id) {
  499. return ['code' => 1, 'msg' => '参数错误'];
  500. }
  501. $order = $this->model->find($id);
  502. if (!$order) {
  503. return ['code' => 1, 'msg' => '订单不存在'];
  504. }
  505. if ($order->status != 3) {
  506. return ['code' => 1, 'msg' => '订单状态不正确,只有已发货订单可以完成'];
  507. }
  508. // 调用用户端的订单完成方法,触发收益结算等业务逻辑
  509. $apiOrderService = \App\Services\Api\OrderService::make();
  510. $result = $apiOrderService->complete($order->user_id, $id);
  511. if ($result) {
  512. ActionLogModel::setTitle("订单完成");
  513. ActionLogModel::record();
  514. RedisService::keyDel("caches:orders:*");
  515. return ['code' => 0, 'msg' => '确认收货成功'];
  516. }
  517. // 获取错误信息
  518. $error = $apiOrderService->getError();
  519. return ['code' => 1, 'msg' => $error ?: '操作失败', 'error' => $error];
  520. }
  521. /**
  522. * 取消订单
  523. */
  524. public function cancelOrder()
  525. {
  526. $id = request()->post('id');
  527. $cancelReason = request()->post('cancel_reason', '');
  528. if (!$id) {
  529. return ['code' => 1, 'msg' => '参数错误'];
  530. }
  531. $order = $this->model->find($id);
  532. if (!$order) {
  533. return ['code' => 1, 'msg' => '订单不存在'];
  534. }
  535. if ($order->status != 1) {
  536. return ['code' => 1, 'msg' => '只有待付款订单可以取消'];
  537. }
  538. $updateData = [
  539. 'mark' => 0, // 标记为删除
  540. 'update_time' => time()
  541. ];
  542. $result = $this->model->where('id', $id)->update($updateData);
  543. if ($result) {
  544. ActionLogModel::setTitle("取消订单");
  545. ActionLogModel::record();
  546. RedisService::keyDel("caches:orders:*");
  547. return ['code' => 0, 'msg' => '订单已取消'];
  548. }
  549. return ['code' => 1, 'msg' => '操作失败'];
  550. }
  551. /**
  552. * 申请退款
  553. */
  554. public function applyRefund()
  555. {
  556. $id = request()->post('id');
  557. $afterType = request()->post('after_type', 2); // 默认退款
  558. $afterRealname = request()->post('after_realname', '');
  559. $afterPhone = request()->post('after_phone', '');
  560. $afterRemark = request()->post('after_remark', '');
  561. if (!$id) {
  562. return ['code' => 1, 'msg' => '参数错误'];
  563. }
  564. if (!$afterRealname) {
  565. return ['code' => 1, 'msg' => '请填写联系人姓名'];
  566. }
  567. if (!$afterPhone) {
  568. return ['code' => 1, 'msg' => '请填写联系电话'];
  569. }
  570. if (!$afterRemark) {
  571. return ['code' => 1, 'msg' => '请填写退款原因'];
  572. }
  573. $order = $this->model->find($id);
  574. if (!$order) {
  575. return ['code' => 1, 'msg' => '订单不存在'];
  576. }
  577. // 只有已付款、已发货、已完成的订单可以申请退款
  578. if (!in_array($order->status, [2, 3, 4])) {
  579. return ['code' => 1, 'msg' => '该订单状态不允许申请退款'];
  580. }
  581. if ($order->refund_status != 0) {
  582. return ['code' => 1, 'msg' => '该订单已申请过退款'];
  583. }
  584. $updateData = [
  585. 'refund_status' => 3, // 待审核
  586. 'after_type' => $afterType, // 1-售后,2-退款
  587. 'after_realname' => $afterRealname,
  588. 'after_phone' => $afterPhone,
  589. 'after_remark' => $afterRemark,
  590. 'update_time' => time()
  591. ];
  592. $result = $this->model->where('id', $id)->update($updateData);
  593. if ($result) {
  594. $typeText = $afterType == 1 ? '售后' : '退款';
  595. ActionLogModel::setTitle("申请{$typeText}");
  596. ActionLogModel::record();
  597. RedisService::keyDel("caches:orders:*");
  598. return ['code' => 0, 'msg' => "{$typeText}申请已提交"];
  599. }
  600. return ['code' => 1, 'msg' => '操作失败'];
  601. }
  602. /**
  603. * 同意退款(审核通过,状态变为已审核)
  604. */
  605. public function agreeRefund()
  606. {
  607. $id = request()->post('id');
  608. $refundRemark = request()->post('refund_remark', '');
  609. if (!$id) {
  610. return ['code' => 1, 'msg' => '参数错误'];
  611. }
  612. $order = $this->model->find($id);
  613. if (!$order) {
  614. return ['code' => 1, 'msg' => '订单不存在'];
  615. }
  616. if ($order->refund_status != 3) {
  617. return ['code' => 1, 'msg' => '该订单未申请退款或已处理'];
  618. }
  619. $updateData = [
  620. 'refund_status' => 2, // 已审核(待确认退款)
  621. 'refund_remark' => $refundRemark ?: '退款申请已通过,待确认退款',
  622. 'update_time' => time()
  623. ];
  624. $result = $this->model->where('id', $id)->update($updateData);
  625. if ($result) {
  626. ActionLogModel::setTitle("同意退款");
  627. ActionLogModel::record();
  628. RedisService::keyDel("caches:orders:*");
  629. return ['code' => 0, 'msg' => '已同意退款,请确认退款'];
  630. }
  631. return ['code' => 1, 'msg' => '操作失败'];
  632. }
  633. /**
  634. * 确认退款(最终完成退款)
  635. */
  636. public function confirmRefund()
  637. {
  638. $id = request()->post('id');
  639. $refundAmount = request()->post('refund_amount', 0);
  640. if (!$id) {
  641. return ['code' => 1, 'msg' => '参数错误'];
  642. }
  643. if ($refundAmount <= 0) {
  644. return ['code' => 1, 'msg' => '请输入退款金额'];
  645. }
  646. $order = $this->model->find($id);
  647. if (!$order) {
  648. return ['code' => 1, 'msg' => '订单不存在'];
  649. }
  650. // 允许待审核(3)和已审核(2)状态的订单进行退款
  651. if (!in_array($order->refund_status, [2, 3])) {
  652. return ['code' => 1, 'msg' => '该订单状态不允许退款'];
  653. }
  654. if ($refundAmount > floatval($order->pay_total + $order->delivery_fee)) {
  655. return ['code' => 1, 'msg' => '退款金额不能大于订单支付金额'];
  656. }
  657. // 使用事务
  658. DB::beginTransaction();
  659. try {
  660. // 调用支付服务退款
  661. $paymentService = \App\Services\PaymentService::make();
  662. $refundData = [
  663. 'money' => $refundAmount,
  664. 'pay_type' => $order->pay_type,
  665. 'order_no' => $order->order_no,
  666. 'out_trade_no' => $order->out_trade_no,
  667. 'transaction_id' => $order->transaction_id,
  668. 'remark' => '订单退款'
  669. ];
  670. $refundResult = $paymentService->refund($refundData, 'store');
  671. if (!$refundResult) {
  672. DB::rollBack();
  673. return ['code' => 1, 'msg' => '退款失败:' . $paymentService->getError() ?: '退款失败'];
  674. }
  675. // 更新订单状态
  676. $updateData = [
  677. 'refund_status' => 1, // 已退款
  678. 'refund_amount' => $refundAmount,
  679. 'update_time' => time()
  680. ];
  681. $result = $this->model->where('id', $id)->update($updateData);
  682. if ($result) {
  683. DB::commit();
  684. ActionLogModel::setTitle("确认退款");
  685. ActionLogModel::record();
  686. RedisService::keyDel("caches:orders:*");
  687. return ['code' => 0, 'msg' => '退款成功'];
  688. }
  689. DB::rollBack();
  690. return ['code' => 1, 'msg' => '更新订单状态失败'];
  691. } catch (\Exception $e) {
  692. DB::rollBack();
  693. return ['code' => 1, 'msg' => '退款失败:' . $e->getMessage()];
  694. }
  695. }
  696. /**
  697. * 拒绝退款
  698. */
  699. public function rejectRefund()
  700. {
  701. $id = request()->post('id');
  702. $refundRemark = request()->post('refund_remark', '');
  703. if (!$id) {
  704. return ['code' => 1, 'msg' => '参数错误'];
  705. }
  706. if (!$refundRemark) {
  707. return ['code' => 1, 'msg' => '请填写拒绝原因'];
  708. }
  709. $order = $this->model->find($id);
  710. if (!$order) {
  711. return ['code' => 1, 'msg' => '订单不存在'];
  712. }
  713. if ($order->refund_status != 3) {
  714. return ['code' => 1, 'msg' => '该订单未申请退款或已处理'];
  715. }
  716. $updateData = [
  717. 'refund_status' => 4, // 审核驳回
  718. 'refund_remark' => $refundRemark,
  719. 'update_time' => time()
  720. ];
  721. $result = $this->model->where('id', $id)->update($updateData);
  722. if ($result) {
  723. ActionLogModel::setTitle("拒绝退款");
  724. ActionLogModel::record();
  725. RedisService::keyDel("caches:orders:*");
  726. return ['code' => 0, 'msg' => '已拒绝退款'];
  727. }
  728. return ['code' => 1, 'msg' => '操作失败'];
  729. }
  730. /**
  731. * 订单统计
  732. * @param int $storeId 商户ID,0表示平台管理员查看全部数据
  733. */
  734. public function getStatistics($storeId = 0)
  735. {
  736. // 总订单数
  737. $total = $this->model->where('mark', 1)
  738. ->when($storeId > 0, function ($query) use ($storeId) {
  739. return $query->where('store_id', $storeId);
  740. })
  741. ->count();
  742. // 总交易额(已完成订单)
  743. $totalAmount = $this->model->where('mark', 1)
  744. ->where('status', 4)
  745. ->when($storeId > 0, function ($query) use ($storeId) {
  746. return $query->where('store_id', $storeId);
  747. })
  748. ->sum('pay_total');
  749. // 待处理订单(待付款 + 已付款)
  750. $pending = $this->model->where('mark', 1)
  751. ->whereIn('status', [1, 2])
  752. ->when($storeId > 0, function ($query) use ($storeId) {
  753. return $query->where('store_id', $storeId);
  754. })
  755. ->count();
  756. // 待退款订单
  757. $refunding = $this->model->where('mark', 1)
  758. ->where('refund_status', 3)
  759. ->when($storeId > 0, function ($query) use ($storeId) {
  760. return $query->where('store_id', $storeId);
  761. })
  762. ->count();
  763. return [
  764. 'code' => 0,
  765. 'msg' => '操作成功',
  766. 'data' => [
  767. 'total' => $total,
  768. 'totalAmount' => number_format($totalAmount, 2, '.', ''),
  769. 'pending' => $pending,
  770. 'refunding' => $refunding
  771. ]
  772. ];
  773. }
  774. }