OrderService.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  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\MessageModel;
  17. use App\Models\OrderModel;
  18. use App\Models\OrderGoodsModel;
  19. use App\Models\PayOrdersModel;
  20. use App\Models\StoreModel;
  21. use App\Services\Api\SettleService;
  22. use App\Services\BaseService;
  23. use App\Services\Kd100Service;
  24. use App\Services\RedisService;
  25. use Illuminate\Support\Facades\DB;
  26. /**
  27. * 订单管理-服务类
  28. * @author laravel开发员
  29. * @since 2020/11/11
  30. * Class OrderService
  31. * @package App\Services\Common
  32. */
  33. class OrderService extends BaseService
  34. {
  35. // 静态对象
  36. protected static $instance = null;
  37. /**
  38. * 构造函数
  39. * @author laravel开发员
  40. * @since 2020/11/11
  41. * OrderService constructor.
  42. */
  43. public function __construct()
  44. {
  45. $this->model = new OrderModel();
  46. }
  47. /**
  48. * 静态入口
  49. * @return static|null
  50. */
  51. public static function make()
  52. {
  53. if (!self::$instance) {
  54. self::$instance = (new static());
  55. }
  56. return self::$instance;
  57. }
  58. /**
  59. * @param $params
  60. * @param int $pageSize
  61. * @return array
  62. */
  63. public function getDataList($params, $pageSize = 15)
  64. {
  65. $query = $this->model->where('mark', 1);
  66. // 店铺筛选
  67. if (isset($params['store_id']) && $params['store_id'] > 0) {
  68. $query->where('store_id', $params['store_id']);
  69. }
  70. // 用户筛选
  71. if (isset($params['user_id']) && $params['user_id'] > 0) {
  72. $query->where('user_id', $params['user_id']);
  73. }
  74. // 状态筛选
  75. if (isset($params['status']) && $params['status'] > 0) {
  76. $query->where('status', $params['status']);
  77. }
  78. // 售后类型筛选(1-售后,2-退款)
  79. if (isset($params['after_type']) && $params['after_type'] > 0) {
  80. $query->where('after_type', $params['after_type']);
  81. }
  82. // 退款状态筛选
  83. if (isset($params['refund_status']) && $params['refund_status'] > 0) {
  84. $query->where('refund_status', $params['refund_status']);
  85. }
  86. // 关键词搜索(订单号、商品名称、收货人手机)
  87. if (isset($params['keyword']) && $params['keyword']) {
  88. $keyword = $params['keyword'];
  89. $query->where(function ($q) use ($keyword) {
  90. $q->where('order_no', 'like', '%' . $keyword . '%')
  91. ->orWhere('receiver_name', 'like', '%' . $keyword . '%')
  92. ->orWhere('receiver_mobile', 'like', '%' . $keyword . '%')
  93. ->orWhereHas('orderGoods', function ($q2) use ($keyword) {
  94. $q2->where('goods_name', 'like', '%' . $keyword . '%');
  95. });
  96. });
  97. }
  98. $list = $query->with(['user', 'orderGoods', 'store'])
  99. ->orderBy('create_time', 'desc')
  100. ->orderBy('id', 'desc')
  101. ->paginate($pageSize);
  102. $list = $list ? $list->toArray() : [];
  103. if ($list && isset($list['data'])) {
  104. foreach ($list['data'] as &$item) {
  105. $item['create_time'] = $item['create_time'] ? datetime($item['create_time']) : '';$item['user'] = $item['user'] ?? [];
  106. $item['store'] = $item['store'] ?? [];
  107. // 获取第一个商品信息(thumb已通过Model访问器处理)
  108. $item['goods'] = isset($item['order_goods'][0]) ? $item['order_goods'][0] : null;
  109. }
  110. }
  111. return [
  112. 'msg' => '操作成功',
  113. 'code' => 0,
  114. 'data' => $list['data'] ?? [],
  115. 'count' => $list['total'] ?? 0,
  116. ];
  117. }
  118. /**
  119. * 获取订单详情
  120. */
  121. public function getInfo($id)
  122. {
  123. $info = $this->model->where('id', $id)->where('mark', 1)
  124. ->with(['user', 'orderGoods', 'store','recUser'])
  125. ->first();
  126. if (!$info) {
  127. return ['code' => 1, 'msg' => '订单不存在'];
  128. }
  129. $info = $info->toArray();
  130. $info['create_time'] = $info['create_time'] ? date('Y-m-d H:i:s', strtotime($info['create_time'])) : '';
  131. $info['update_time'] = $info['update_time'] ? date('Y-m-d H:i:s', strtotime($info['update_time'])) : '';
  132. $info['deliveryData'] = $this->getDelivery($info);
  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 $id
  201. * @return array|false|mixed
  202. */
  203. public function getDelivery($info)
  204. {
  205. $id = isset($info['id']) ? $info['id'] : 0;
  206. $deliveryNo = isset($info['delivery_no']) ? $info['delivery_no'] : '';
  207. $deliveryCode = isset($info['delivery_code']) ? $info['delivery_code'] : '';
  208. $mobile = isset($info['receiver_mobile']) ? $info['receiver_mobile'] : '';
  209. $receiverArea = isset($info['receiver_area']) && $info['receiver_area']? $info['receiver_area'] : '';
  210. if (empty($info)) {
  211. $this->error = '请选择订单';
  212. return false;
  213. }
  214. $cacheKey = "caches:kd100:order_{$id}";
  215. $data = RedisService::get($cacheKey);
  216. if ($data) {
  217. return $data;
  218. }
  219. $result = Kd100Service::make()->query($deliveryNo, $mobile, $deliveryCode,$receiverArea);
  220. RedisService::set($cacheKey.'_result', $result, 300);
  221. $status = isset($result['status'])?$result['status']:0;
  222. $data = isset($result['data'])?$result['data']:[];
  223. $courierInfo = isset($result['courierInfo'])?$result['courierInfo']:[];
  224. $arrivalTime = isset($result['arrivalTime'])?$result['arrivalTime']:'';
  225. $predictedRoute = isset($result['predictedRoute'])?$result['predictedRoute']:[];
  226. $predictedData = $predictedRoute?end($predictedRoute):[];
  227. $arrivalData = [];
  228. if($arrivalTime){
  229. $arrivalData['arrivalTime'] = dayFormat(strtotime($arrivalTime.':00:00'));
  230. $arrivalData['predictedData'] = $predictedData;
  231. }
  232. if($courierInfo && $courierInfo['deliveryManPhone']){
  233. $courierInfo['deliveryManPhone'] = explode(',', $courierInfo['deliveryManPhone']);
  234. $courierInfo['deliveryPhone'] = $courierInfo['deliveryManPhone'][1]?$courierInfo['deliveryManPhone'][1]:$courierInfo['deliveryManPhone'][0];
  235. }
  236. if ($data && $status==200) {
  237. RedisService::set($cacheKey, ['info'=>$courierInfo,'arrivalData'=>$arrivalData,'list'=>$data], 1200);
  238. }
  239. return $data?['info'=>$courierInfo,'arrivalData'=>$arrivalData,'list'=>$data]:[];
  240. }
  241. /**
  242. * 按日期统计订单数
  243. * @param string $beginAt 开始时间
  244. * @param string $endAt 结束时间
  245. * @param int[] $status 状态:数组或数值
  246. * @return mixed
  247. */
  248. public function getCountByTime($beginAt = '', $endAt = '', $status = 3)
  249. {
  250. $cacheKey = "caches:orders:count_{$status}_{$beginAt}_{$endAt}";
  251. $data = RedisService::get($cacheKey);
  252. if ($data) {
  253. return $data;
  254. }
  255. $where = ['mark' => 1];
  256. $data = $this->model->where($where)->where(function ($query) use ($beginAt, $endAt, $status) {
  257. if ($beginAt && $endAt) {
  258. $query->whereBetween('create_time', [strtotime($beginAt), strtotime($endAt)]);
  259. } else if ($beginAt) {
  260. $query->where('create_time', '>=', strtotime($beginAt));
  261. }
  262. if ($status && is_array($status)) {
  263. $query->whereIn('status', $status);
  264. } else if ($status) {
  265. $query->where('status', $status);
  266. }
  267. })->count('id');
  268. if ($data) {
  269. RedisService::set($cacheKey, $data, rand(300, 600));
  270. }
  271. return $data;
  272. }
  273. /**
  274. * 按日期统计订单金额
  275. * @param string $beginAt 开始时间
  276. * @param string $endAt 结束时间
  277. * @param int[] $status 状态:数组或数值
  278. * @return mixed
  279. */
  280. public function getTotalByTime($beginAt = '', $endAt = '', $status = 3)
  281. {
  282. $cacheKey = "caches:orders:total_{$status}_{$beginAt}_{$endAt}";
  283. $data = RedisService::get($cacheKey);
  284. if ($data) {
  285. return $data;
  286. }
  287. $where = ['mark' => 1];
  288. $data = $this->model->where($where)->where(function ($query) use ($beginAt, $endAt, $status) {
  289. if ($beginAt && $endAt) {
  290. $query->whereBetween('create_time', [strtotime($beginAt), strtotime($endAt)]);
  291. } else if ($beginAt) {
  292. $query->where('create_time', '>=', strtotime($beginAt));
  293. }
  294. if ($status && is_array($status)) {
  295. $query->whereIn('status', $status);
  296. } else if ($status) {
  297. $query->where('status', $status);
  298. }
  299. })->sum('total');
  300. if ($data) {
  301. RedisService::set($cacheKey, $data, rand(300, 600));
  302. }
  303. return $data;
  304. }
  305. /**
  306. * 添加或编辑
  307. * @return array
  308. * @since 2020/11/11
  309. * @author laravel开发员
  310. */
  311. public function edit()
  312. {
  313. $params = request()->post();
  314. return parent::edit($params); // TODO: Change the autogenerated stub
  315. }
  316. /**
  317. * 完成支付
  318. */
  319. public function completePay()
  320. {
  321. $id = request()->post('id');
  322. $transactionId = request()->post('transaction_id', '');
  323. if (!$id) {
  324. return ['code' => 1, 'msg' => '参数错误'];
  325. }
  326. $order = $this->model->find($id);
  327. if (!$order) {
  328. return ['code' => 1, 'msg' => '订单不存在'];
  329. }
  330. if ($order->status != 1) {
  331. return ['code' => 1, 'msg' => '订单状态不正确'];
  332. }
  333. $updateData = [
  334. 'status' => 2, // 已付款
  335. 'transaction_id' => $transactionId ?: 'PAY' . time() . rand(1000, 9999),
  336. 'pay_at'=> date('Y-m-d H:i:s'),
  337. 'remark'=> '人工审核支付',
  338. 'update_time' => time()
  339. ];
  340. $result = $this->model->where('id', $id)->update($updateData);
  341. if ($result) {
  342. ActionLogModel::setTitle("订单完成支付");
  343. ActionLogModel::record();
  344. RedisService::keyDel("caches:orders:*");
  345. return ['code' => 0, 'msg' => '支付完成'];
  346. }
  347. return ['code' => 1, 'msg' => '操作失败'];
  348. }
  349. /**
  350. * 订单发货
  351. */
  352. public function deliverOrder()
  353. {
  354. $id = request()->post('id');
  355. $deliveryCompany = request()->post('delivery_company', '');
  356. $deliveryNo = request()->post('delivery_no', '');
  357. $deliveryCode = request()->post('delivery_code', '');
  358. if (!$id) {
  359. return ['code' => 1, 'msg' => '参数错误'];
  360. }
  361. $order = $this->model->find($id);
  362. if (!$order) {
  363. return ['code' => 1, 'msg' => '订单不存在'];
  364. }
  365. if ($order->status != 2) {
  366. return ['code' => 1, 'msg' => '订单状态不正确,只有已付款订单可以发货'];
  367. }
  368. if (!$deliveryNo) {
  369. return ['code' => 1, 'msg' => '请填写快递单号'];
  370. }
  371. $updateData = [
  372. 'status' => 3, // 已发货
  373. 'delivery_company' => $deliveryCompany,
  374. 'delivery_no' => $deliveryNo,
  375. 'delivery_code' => $deliveryCode,
  376. 'update_time' => time()
  377. ];
  378. $result = $this->model->where('id', $id)->update($updateData);
  379. if ($result) {
  380. ActionLogModel::setTitle("订单发货");
  381. ActionLogModel::record();
  382. RedisService::keyDel("caches:orders:*");
  383. return ['code' => 0, 'msg' => '发货成功'];
  384. }
  385. return ['code' => 1, 'msg' => '操作失败'];
  386. }
  387. /**
  388. * 订单完成(管理后台)
  389. */
  390. public function completeOrder()
  391. {
  392. $id = request()->post('id');
  393. if (!$id) {
  394. return ['code' => 1, 'msg' => '参数错误'];
  395. }
  396. $order = $this->model->find($id);
  397. if (!$order) {
  398. return ['code' => 1, 'msg' => '订单不存在'];
  399. }
  400. if ($order->status != 3) {
  401. return ['code' => 1, 'msg' => '订单状态不正确,只有已发货订单可以完成'];
  402. }
  403. // 调用用户端的订单完成方法,触发收益结算等业务逻辑
  404. $apiOrderService = \App\Services\Api\OrderService::make();
  405. $result = $apiOrderService->complete($order->user_id, $id);
  406. if ($result) {
  407. ActionLogModel::setTitle("订单完成");
  408. ActionLogModel::record();
  409. RedisService::keyDel("caches:orders:*");
  410. return ['code' => 0, 'msg' => '确认收货成功'];
  411. }
  412. // 获取错误信息
  413. $error = $apiOrderService->getError();
  414. return ['code' => 1, 'msg' => $error ?: '操作失败', 'error' => $error];
  415. }
  416. /**
  417. * 取消订单
  418. */
  419. public function settleOrder()
  420. {
  421. $id = request()->post('id');
  422. if (!$id) {
  423. return ['code' => 1, 'msg' => '参数错误'];
  424. }
  425. $cacheLockKey = "caches:orders:settle_".$id.'_lock';
  426. if(RedisService::get($cacheLockKey)){
  427. return ['code' => 1, 'msg' => '结算中'];
  428. }
  429. $order = $this->model->find($id);
  430. $orderNo = isset($order['order_no'])?$order['order_no']:'';
  431. $storeId = isset($order['store_id'])?$order['store_id']:0;
  432. $userId = isset($order['user_id'])?$order['user_id']:0;
  433. if (!$order) {
  434. return ['code' => 1, 'msg' => '订单不存在'];
  435. }
  436. if ($order->bonus_settle == 1) {
  437. return ['code' => 1, 'msg' => '佣金收益已结算'];
  438. }
  439. if ($order->status != 4) {
  440. return ['code' => 1, 'msg' => '订单未完成'];
  441. }
  442. RedisService::set($cacheLockKey, $order, rand(10,20));
  443. DB::beginTransaction();
  444. // 结算商家收益
  445. $result = SettleService::make()->storeBonus($storeId, $order['bonus'], $order);
  446. if ($result < 0) {
  447. DB::rollBack();
  448. $this->error = SettleService::make()->getError();
  449. RedisService::clear($cacheLockKey);
  450. \App\Services\Api\OrderService::make()->saveLog("caches:settle:{$orderNo}:store_{$storeId}_error",SettleService::make()->getError());
  451. return false;
  452. }
  453. \App\Services\Api\OrderService::make()->saveLog("caches:settle:{$orderNo}:store_{$storeId}",['msg'=>SettleService::make()->getError(),'result'=>$result]);
  454. // 代理佣金结算
  455. $result1 = SettleService::make()->agentBonus($userId, $order['rec_bonus'], $order, $order['rec_bonus_id']);
  456. if ($result1 < 0) {
  457. DB::rollBack();
  458. $this->error = SettleService::make()->getError();
  459. RedisService::clear($cacheLockKey);
  460. \App\Services\Api\OrderService::make()->saveLog("caches:settle:{$orderNo}:agent_{$userId}_error",SettleService::make()->getError());
  461. return false;
  462. }
  463. \App\Services\Api\OrderService::make()->saveLog("caches:settle:{$orderNo}:agent_{$userId}",['msg'=>SettleService::make()->getError(),'result'=>$result1]);
  464. // 更新订单结算状态
  465. if(!$this->model->where(['id'=>$id])->update(['bonus_settle'=>1,'update_time'=>time()])){
  466. DB::rollBack();
  467. $this->error = '收益结算状态更新失败';
  468. RedisService::clear($cacheLockKey);
  469. return false;
  470. }
  471. DB::commit();
  472. ActionLogModel::setTitle("订单结算");
  473. ActionLogModel::record();
  474. RedisService::keyDel("caches:orders:*");
  475. return ['code' => 0, 'msg' => '订单结算'];
  476. }
  477. /**
  478. * 取消订单
  479. */
  480. public function cancelOrder()
  481. {
  482. $id = request()->post('id');
  483. $cancelReason = request()->post('cancel_reason', '');
  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 != 1) {
  492. return ['code' => 1, 'msg' => '只有待付款订单可以取消'];
  493. }
  494. $updateData = [
  495. 'mark' => 0, // 标记为删除
  496. 'update_time' => time()
  497. ];
  498. $result = $this->model->where('id', $id)->update($updateData);
  499. if ($result) {
  500. ActionLogModel::setTitle("取消订单");
  501. ActionLogModel::record();
  502. RedisService::keyDel("caches:orders:*");
  503. return ['code' => 0, 'msg' => '订单已取消'];
  504. }
  505. return ['code' => 1, 'msg' => '操作失败'];
  506. }
  507. /**
  508. * 申请退款
  509. */
  510. public function applyRefund()
  511. {
  512. $id = request()->post('id');
  513. $afterType = request()->post('after_type', 2); // 默认退款
  514. $afterRealname = request()->post('after_realname', '');
  515. $afterPhone = request()->post('after_phone', '');
  516. $afterRemark = request()->post('after_remark', '');
  517. if (!$id) {
  518. return ['code' => 1, 'msg' => '参数错误'];
  519. }
  520. if (!$afterRealname) {
  521. return ['code' => 1, 'msg' => '请填写联系人姓名'];
  522. }
  523. if (!$afterPhone) {
  524. return ['code' => 1, 'msg' => '请填写联系电话'];
  525. }
  526. if (!$afterRemark) {
  527. return ['code' => 1, 'msg' => '请填写退款原因'];
  528. }
  529. $order = $this->model->find($id);
  530. if (!$order) {
  531. return ['code' => 1, 'msg' => '订单不存在'];
  532. }
  533. // 只有已付款、已发货、已完成的订单可以申请退款
  534. if (!in_array($order->status, [2, 3, 4])) {
  535. return ['code' => 1, 'msg' => '该订单状态不允许申请退款'];
  536. }
  537. if ($order->refund_status != 0) {
  538. return ['code' => 1, 'msg' => '该订单已申请过退款'];
  539. }
  540. $updateData = [
  541. 'refund_status' => 3, // 待审核
  542. 'after_type' => $afterType, // 1-售后,2-退款
  543. 'after_realname' => $afterRealname,
  544. 'after_phone' => $afterPhone,
  545. 'after_remark' => $afterRemark,
  546. 'update_time' => time()
  547. ];
  548. $result = $this->model->where('id', $id)->update($updateData);
  549. if ($result) {
  550. $typeText = $afterType == 1 ? '售后' : '退款';
  551. ActionLogModel::setTitle("申请{$typeText}");
  552. ActionLogModel::record();
  553. RedisService::keyDel("caches:orders:*");
  554. return ['code' => 0, 'msg' => "{$typeText}申请已提交"];
  555. }
  556. return ['code' => 1, 'msg' => '操作失败'];
  557. }
  558. /**
  559. * 同意退款(审核通过,状态变为已审核)
  560. */
  561. public function agreeRefund()
  562. {
  563. $id = request()->post('id');
  564. $refundRemark = request()->post('refund_remark', '');
  565. if (!$id) {
  566. return ['code' => 1, 'msg' => '参数错误'];
  567. }
  568. $order = $this->model->find($id);
  569. if (!$order) {
  570. return ['code' => 1, 'msg' => '订单不存在'];
  571. }
  572. if ($order->refund_status != 3) {
  573. return ['code' => 1, 'msg' => '该订单未申请退款或已处理'];
  574. }
  575. $updateData = [
  576. 'refund_status' => 2, // 已审核(待确认退款)
  577. 'refund_remark' => $refundRemark ?: '退款申请已通过,待确认退款',
  578. 'update_time' => time()
  579. ];
  580. $result = $this->model->where('id', $id)->update($updateData);
  581. if ($result) {
  582. ActionLogModel::setTitle("同意退款");
  583. ActionLogModel::record();
  584. RedisService::keyDel("caches:orders:*");
  585. return ['code' => 0, 'msg' => '已同意退款,请确认退款'];
  586. }
  587. return ['code' => 1, 'msg' => '操作失败'];
  588. }
  589. /**
  590. * 确认退款(最终完成退款)
  591. */
  592. public function confirmRefund()
  593. {
  594. $id = request()->post('id');
  595. $refundAmount = request()->post('refund_amount', 0);
  596. if (!$id) {
  597. return ['code' => 1, 'msg' => '参数错误'];
  598. }
  599. if ($refundAmount <= 0) {
  600. return ['code' => 1, 'msg' => '请输入退款金额'];
  601. }
  602. $order = $this->model->find($id);
  603. if (!$order) {
  604. return ['code' => 1, 'msg' => '订单不存在'];
  605. }
  606. // 允许待审核(3)和已审核(2)状态的订单进行退款
  607. if (!in_array($order->refund_status, [2, 3])) {
  608. return ['code' => 1, 'msg' => '该订单状态不允许退款'];
  609. }
  610. if ($refundAmount > $order->pay_total) {
  611. return ['code' => 1, 'msg' => '退款金额不能大于订单金额'];
  612. }
  613. // 使用事务
  614. DB::beginTransaction();
  615. try {
  616. // 调用支付服务退款
  617. $paymentService = \App\Services\PaymentService::make();
  618. $refundData = [
  619. 'money' => $refundAmount,
  620. 'pay_type' => $order->pay_type,
  621. 'order_no' => $order->order_no,
  622. 'out_trade_no' => $order->out_trade_no,
  623. 'transaction_id' => $order->transaction_id,
  624. 'remark' => '订单退款'
  625. ];
  626. $refundResult = $paymentService->refund($refundData, 'store');
  627. if (!$refundResult) {
  628. DB::rollBack();
  629. return ['code' => 1, 'msg' => '退款失败:' . $paymentService->getError() ?: '退款失败'];
  630. }
  631. // 更新订单状态
  632. $updateData = [
  633. 'refund_status' => 1, // 已退款
  634. 'refund_amount' => $refundAmount,
  635. 'update_time' => time()
  636. ];
  637. $result = $this->model->where('id', $id)->update($updateData);
  638. if ($result) {
  639. DB::commit();
  640. ActionLogModel::setTitle("确认退款");
  641. ActionLogModel::record();
  642. RedisService::keyDel("caches:orders:*");
  643. return ['code' => 0, 'msg' => '退款成功'];
  644. }
  645. DB::rollBack();
  646. return ['code' => 1, 'msg' => '更新订单状态失败'];
  647. } catch (\Exception $e) {
  648. DB::rollBack();
  649. return ['code' => 1, 'msg' => '退款失败:' . $e->getMessage()];
  650. }
  651. }
  652. /**
  653. * 拒绝退款
  654. */
  655. public function rejectRefund()
  656. {
  657. $id = request()->post('id');
  658. $refundRemark = request()->post('refund_remark', '');
  659. if (!$id) {
  660. return ['code' => 1, 'msg' => '参数错误'];
  661. }
  662. if (!$refundRemark) {
  663. return ['code' => 1, 'msg' => '请填写拒绝原因'];
  664. }
  665. $order = $this->model->find($id);
  666. if (!$order) {
  667. return ['code' => 1, 'msg' => '订单不存在'];
  668. }
  669. if ($order->refund_status != 3) {
  670. return ['code' => 1, 'msg' => '该订单未申请退款或已处理'];
  671. }
  672. $updateData = [
  673. 'refund_status' => 4, // 审核驳回
  674. 'refund_remark' => $refundRemark,
  675. 'update_time' => time()
  676. ];
  677. $result = $this->model->where('id', $id)->update($updateData);
  678. if ($result) {
  679. ActionLogModel::setTitle("拒绝退款");
  680. ActionLogModel::record();
  681. RedisService::keyDel("caches:orders:*");
  682. return ['code' => 0, 'msg' => '已拒绝退款'];
  683. }
  684. return ['code' => 1, 'msg' => '操作失败'];
  685. }
  686. /**
  687. * 订单统计
  688. * @param int $storeId 商户ID,0表示平台管理员查看全部数据
  689. */
  690. public function getStatistics($storeId = 0)
  691. {
  692. // 总订单数
  693. $params = request()->all();
  694. $userId = isset($params['user_id'])?$params['user_id']:0;
  695. $where = ['user_id'=>$userId,'mark'=>1];
  696. if($userId<=0){
  697. unset($where['user_id']);
  698. }
  699. $total = $this->model->where($where)
  700. ->when($storeId > 0, function ($query) use ($storeId) {
  701. return $query->where('store_id', $storeId);
  702. })
  703. ->count();
  704. // 总交易额(已完成订单)
  705. $totalAmount = $this->model->where($where)
  706. ->where('status', 4)
  707. ->when($storeId > 0, function ($query) use ($storeId) {
  708. return $query->where('store_id', $storeId);
  709. })
  710. ->sum('pay_total');
  711. // 待处理订单(待付款 + 已付款)
  712. $pending = $this->model->where($where)
  713. ->whereIn('status', [1, 2])
  714. ->when($storeId > 0, function ($query) use ($storeId) {
  715. return $query->where('store_id', $storeId);
  716. })
  717. ->count();
  718. // 待退款订单
  719. $refunding = $this->model->where($where)
  720. ->where('refund_status', 3)
  721. ->when($storeId > 0, function ($query) use ($storeId) {
  722. return $query->where('store_id', $storeId);
  723. })
  724. ->count();
  725. return [
  726. 'code' => 0,
  727. 'msg' => '操作成功',
  728. 'data' => [
  729. 'total' => $total,
  730. 'totalAmount' => number_format($totalAmount, 2, '.', ''),
  731. 'pending' => $pending,
  732. 'refunding' => $refunding
  733. ]
  734. ];
  735. }
  736. /**
  737. * 导出订单数据
  738. */
  739. public function exportData($params)
  740. {
  741. $query = $this->model->where('mark', 1);
  742. // 店铺筛选
  743. if (isset($params['store_id']) && $params['store_id'] > 0) {
  744. $query->where('store_id', $params['store_id']);
  745. }
  746. // 用户筛选
  747. if (isset($params['user_id']) && $params['user_id'] > 0) {
  748. $query->where('user_id', $params['user_id']);
  749. }
  750. // 状态筛选
  751. if (isset($params['status']) && $params['status'] > 0) {
  752. $query->where('status', $params['status']);
  753. }
  754. // 售后类型筛选
  755. if (isset($params['after_type']) && $params['after_type'] > 0) {
  756. $query->where('after_type', $params['after_type']);
  757. }
  758. // 退款状态筛选
  759. if (isset($params['refund_status']) && $params['refund_status'] > 0) {
  760. $query->where('refund_status', $params['refund_status']);
  761. }
  762. // 关键词搜索
  763. if (isset($params['keyword']) && $params['keyword']) {
  764. $keyword = $params['keyword'];
  765. $query->where(function ($q) use ($keyword) {
  766. $q->where('order_no', 'like', '%' . $keyword . '%')
  767. ->orWhere('receiver_name', 'like', '%' . $keyword . '%')
  768. ->orWhere('receiver_mobile', 'like', '%' . $keyword . '%');
  769. });
  770. }
  771. $list = $query->with(['user', 'orderGoods', 'store'])
  772. ->orderBy('create_time', 'desc')
  773. ->limit(5000)
  774. ->get();
  775. if (!$list || $list->isEmpty()) {
  776. return response()->json(['code' => 1, 'msg' => '没有可导出的数据']);
  777. }
  778. // 状态映射
  779. $statusMap = [1 => '待付款', 2 => '已付款', 3 => '已发货', 4 => '已完成', 9 => '已取消'];
  780. $refundStatusMap = [0 => '无', 1 => '已退款', 2 => '已审核', 3 => '待审核'];
  781. // 构建导出数据
  782. $data = [];
  783. foreach ($list as $item) {
  784. $goodsNames = [];
  785. if ($item->orderGoods) {
  786. foreach ($item->orderGoods as $goods) {
  787. $goodsNames[] = $goods->goods_name . ' x' . $goods->num;
  788. }
  789. }
  790. $data[] = [
  791. $item->order_no,
  792. $item->user->nickname ?? '',
  793. $item->user->mobile ?? '',
  794. implode(';', $goodsNames),
  795. $item->total ?? 0,
  796. $item->pay_total ?? 0,
  797. $statusMap[$item->status] ?? '未知',
  798. $refundStatusMap[$item->refund_status] ?? '无',
  799. $item->receiver_name ?? '',
  800. $item->receiver_mobile ?? '',
  801. $item->receiver_address ?? '',
  802. $item->create_time ? date('Y-m-d H:i:s', strtotime($item->create_time)) : '',
  803. ];
  804. }
  805. $headings = ['订单号', '用户昵称', '用户手机', '商品信息', '订单金额', '实付金额', '订单状态', '退款状态', '收货人', '收货电话', '收货地址', '下单时间'];
  806. $export = new \App\Exports\Export($data, $headings, '订单列表');
  807. $filename = '订单列表_' . date('YmdHis') . '.xlsx';
  808. return \Maatwebsite\Excel\Facades\Excel::download($export, $filename);
  809. }
  810. }