OrderService.php 30 KB

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