OrderService.php 32 KB

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