OrderService.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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\StoreModel;
  20. use App\Services\BaseService;
  21. use App\Services\RedisService;
  22. use Illuminate\Support\Facades\DB;
  23. /**
  24. * 订单管理-服务类
  25. * @author laravel开发员
  26. * @since 2020/11/11
  27. * Class OrderService
  28. * @package App\Services\Common
  29. */
  30. class OrderService extends BaseService
  31. {
  32. // 静态对象
  33. protected static $instance = null;
  34. /**
  35. * 构造函数
  36. * @author laravel开发员
  37. * @since 2020/11/11
  38. * OrderService constructor.
  39. */
  40. public function __construct()
  41. {
  42. $this->model = new OrderModel();
  43. }
  44. /**
  45. * 静态入口
  46. * @return static|null
  47. */
  48. public static function make()
  49. {
  50. if (!self::$instance) {
  51. self::$instance = (new static());
  52. }
  53. return self::$instance;
  54. }
  55. /**
  56. * @param $params
  57. * @param int $pageSize
  58. * @return array
  59. */
  60. public function getDataList($params, $pageSize = 15)
  61. {
  62. $query = $this->model->where('mark', 1);
  63. // 店铺筛选
  64. if (isset($params['store_id']) && $params['store_id'] > 0) {
  65. $query->where('store_id', $params['store_id']);
  66. }
  67. // 用户筛选
  68. if (isset($params['user_id']) && $params['user_id'] > 0) {
  69. $query->where('user_id', $params['user_id']);
  70. }
  71. // 状态筛选
  72. if (isset($params['status']) && $params['status'] > 0) {
  73. $query->where('status', $params['status']);
  74. }
  75. // 售后类型筛选(1-售后,2-退款)
  76. if (isset($params['after_type']) && $params['after_type'] > 0) {
  77. $query->where('after_type', $params['after_type']);
  78. }
  79. // 退款状态筛选
  80. if (isset($params['refund_status']) && $params['refund_status'] > 0) {
  81. $query->where('refund_status', $params['refund_status']);
  82. }
  83. // 关键词搜索(订单号、商品名称、收货人手机)
  84. if (isset($params['keyword']) && $params['keyword']) {
  85. $keyword = $params['keyword'];
  86. $query->where(function ($q) use ($keyword) {
  87. $q->where('order_no', 'like', '%' . $keyword . '%')
  88. ->orWhere('receiver_name', 'like', '%' . $keyword . '%')
  89. ->orWhere('receiver_mobile', 'like', '%' . $keyword . '%')
  90. ->orWhereHas('orderGoods', function ($q2) use ($keyword) {
  91. $q2->where('goods_name', 'like', '%' . $keyword . '%');
  92. });
  93. });
  94. }
  95. $list = $query->with(['user', 'orderGoods', 'store'])
  96. ->orderBy('create_time', 'desc')
  97. ->orderBy('id', 'desc')
  98. ->paginate($pageSize);
  99. $list = $list ? $list->toArray() : [];
  100. if ($list && isset($list['data'])) {
  101. foreach ($list['data'] as &$item) {
  102. $item['create_time'] = $item['create_time'] ? date('Y-m-d H:i:s', strtotime($item['create_time'])) : '';
  103. $item['update_time'] = $item['update_time'] ? date('Y-m-d H:i:s', strtotime($item['update_time'])) : '';
  104. $item['user'] = $item['user'] ?? [];
  105. $item['store'] = $item['store'] ?? [];
  106. // 获取第一个商品信息(thumb已通过Model访问器处理)
  107. $item['goods'] = isset($item['order_goods'][0]) ? $item['order_goods'][0] : null;
  108. }
  109. }
  110. return [
  111. 'msg' => '操作成功',
  112. 'code' => 0,
  113. 'data' => $list['data'] ?? [],
  114. 'count' => $list['total'] ?? 0,
  115. ];
  116. }
  117. /**
  118. * 获取订单详情
  119. */
  120. public function getInfo($id)
  121. {
  122. $info = $this->model->where('id', $id)->where('mark', 1)
  123. ->with(['user', 'orderGoods', 'store'])
  124. ->first();
  125. if (!$info) {
  126. return ['code' => 1, 'msg' => '订单不存在'];
  127. }
  128. $info = $info->toArray();
  129. $info['create_time'] = $info['create_time'] ? date('Y-m-d H:i:s', strtotime($info['create_time'])) : '';
  130. $info['update_time'] = $info['update_time'] ? date('Y-m-d H:i:s', strtotime($info['update_time'])) : '';
  131. if (isset($info['order_goods'])) {
  132. foreach ($info['order_goods'] as &$goods) {
  133. $goods['thumb'] = $goods['thumb'] ? get_image_url($goods['thumb']) : '';
  134. $goods['create_time'] = $goods['create_time'] ? date('Y-m-d H:i:s', strtotime($goods['create_time'])) : '';
  135. $goods['update_time'] = $goods['update_time'] ? date('Y-m-d H:i:s', strtotime($goods['update_time'])) : '';
  136. }
  137. }
  138. return ['code' => 0, 'msg' => '操作成功', 'data' => $info];
  139. }
  140. /**
  141. * 查询
  142. * @param $params
  143. * @return \Illuminate\Database\Eloquent\Builder
  144. */
  145. public function getQuery($params)
  146. {
  147. $where = ['a.mark' => 1];
  148. $userId = isset($params['user_id']) ? $params['user_id'] : 0;
  149. return $this->model->with(['user', 'goods'])->from('orders as a')
  150. ->leftJoin('member as b', 'a.user_id', '=', 'b.id')
  151. ->leftJoin('goods as c', 'c.id', '=', 'a.goods_id')
  152. ->where($where)
  153. ->where(function ($query) use ($params) {
  154. $keyword = isset($params['keyword']) ? $params['keyword'] : '';
  155. if ($keyword) {
  156. $query->where('a.order_no', 'like', "%{$keyword}%");
  157. }
  158. // 接单人
  159. $account = isset($params['account']) ? $params['account'] : '';
  160. if ($account) {
  161. $query->where(function ($query) use ($account) {
  162. $query->where('b.nickname', 'like', "%{$account}%")->orWhere('b.mobile', 'like', "%{$account}%");
  163. });
  164. }
  165. // 商品
  166. $goodsId = isset($params['goods_id']) ? intval($params['goods_id']) : 0;
  167. $goods = isset($params['goods']) ? trim($params['goods']) : '';
  168. if ($goods) {
  169. $query->where(function ($query) use ($goods) {
  170. $query->where('c.goods_name', 'like', "%{$goods}%");
  171. if (preg_match("/^(1[0-9]+|[1-9]+)$/", $goods)) {
  172. $query->where('a.goods_id', intval($goods));
  173. } else {
  174. $query->where('c.goods_name', 'like', "%{$goods}%");
  175. }
  176. });
  177. }
  178. if ($goodsId > 0) {
  179. $query->where('a.goods_id', intval($goodsId));
  180. }
  181. })
  182. ->where(function ($query) use ($params) {
  183. $status = isset($params['status']) ? $params['status'] : 0;
  184. if ($status == 0) {
  185. $query->whereIn('a.status', [2, 3]);
  186. } else if ($status) {
  187. $query->where('a.status', $status);
  188. }
  189. })
  190. ->where(function ($query) use ($userId) {
  191. if ($userId) {
  192. $query->where('a.user_id', '=', $userId);
  193. }
  194. });
  195. }
  196. /**
  197. * 按日期统计订单数
  198. * @param string $beginAt 开始时间
  199. * @param string $endAt 结束时间
  200. * @param int[] $status 状态:数组或数值
  201. * @return mixed
  202. */
  203. public function getCountByTime($beginAt = '', $endAt = '', $status = 3)
  204. {
  205. $cacheKey = "caches:orders:count_{$status}_{$beginAt}_{$endAt}";
  206. $data = RedisService::get($cacheKey);
  207. if ($data) {
  208. return $data;
  209. }
  210. $where = ['mark' => 1];
  211. $data = $this->model->where($where)->where(function ($query) use ($beginAt, $endAt, $status) {
  212. if ($beginAt && $endAt) {
  213. $query->whereBetween('create_time', [strtotime($beginAt), strtotime($endAt)]);
  214. } else if ($beginAt) {
  215. $query->where('create_time', '>=', strtotime($beginAt));
  216. }
  217. if ($status && is_array($status)) {
  218. $query->whereIn('status', $status);
  219. } else if ($status) {
  220. $query->where('status', $status);
  221. }
  222. })->count('id');
  223. if ($data) {
  224. RedisService::set($cacheKey, $data, rand(300, 600));
  225. }
  226. return $data;
  227. }
  228. /**
  229. * 按日期统计订单金额
  230. * @param string $beginAt 开始时间
  231. * @param string $endAt 结束时间
  232. * @param int[] $status 状态:数组或数值
  233. * @return mixed
  234. */
  235. public function getTotalByTime($beginAt = '', $endAt = '', $status = 3)
  236. {
  237. $cacheKey = "caches:orders:total_{$status}_{$beginAt}_{$endAt}";
  238. $data = RedisService::get($cacheKey);
  239. if ($data) {
  240. return $data;
  241. }
  242. $where = ['mark' => 1];
  243. $data = $this->model->where($where)->where(function ($query) use ($beginAt, $endAt, $status) {
  244. if ($beginAt && $endAt) {
  245. $query->whereBetween('create_time', [strtotime($beginAt), strtotime($endAt)]);
  246. } else if ($beginAt) {
  247. $query->where('create_time', '>=', strtotime($beginAt));
  248. }
  249. if ($status && is_array($status)) {
  250. $query->whereIn('status', $status);
  251. } else if ($status) {
  252. $query->where('status', $status);
  253. }
  254. })->sum('total');
  255. if ($data) {
  256. RedisService::set($cacheKey, $data, rand(300, 600));
  257. }
  258. return $data;
  259. }
  260. /**
  261. * 添加或编辑
  262. * @return array
  263. * @since 2020/11/11
  264. * @author laravel开发员
  265. */
  266. public function edit()
  267. {
  268. $params = request()->post();
  269. return parent::edit($params); // TODO: Change the autogenerated stub
  270. }
  271. /**
  272. * 订单审核
  273. * @return bool
  274. */
  275. public function confirm($adminId, $params)
  276. {
  277. $id = isset($params['id']) ? intval($params['id']) : 0;
  278. $remark = isset($params['remark']) ? trim($params['remark']) : '';
  279. $checkStatus = isset($params['status']) ? intval($params['status']) : 0;
  280. if (!in_array($checkStatus, [2, 9])) {
  281. $this->error = '请选择审核状态';
  282. return false;
  283. }
  284. $info = $this->model->with(['user', 'goods'])->where(['id' => $id, 'mark' => 1])->first();
  285. $userInfo = isset($info['user']) ? $info['user'] : [];
  286. $goods = isset($info['goods']) ? $info['goods'] : [];
  287. $status = isset($info['status']) ? $info['status'] : 0;
  288. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  289. $goodsId = isset($info['goods_id']) ? $info['goods_id'] : 0;
  290. if (empty($info) || empty($goods) || empty($userInfo) || $goodsId <= 0 || $orderUserId <= 0) {
  291. $this->error = '订单信息不存在或参数错误';
  292. return false;
  293. }
  294. if ($status != 1) {
  295. $this->error = '订单状态不可操作';
  296. return false;
  297. }
  298. // 审核通过
  299. if ($checkStatus == 2) {
  300. if ($this->model->where(['goods_id' => $goodsId, 'status' => 3, 'mark' => 1])->value('id')) {
  301. $this->error = '该货物订单已完成';
  302. return false;
  303. }
  304. if ($this->model->where(['goods_id' => $goodsId, 'status' => 2, 'mark' => 1])->value('id')) {
  305. $this->error = '该货物存在订单进行中,已审核通过其他司机';
  306. return false;
  307. }
  308. }
  309. DB::beginTransaction();
  310. if (!$this->model->where(['id' => $id])->update(['status' => $checkStatus, 'confirm_admin_id' => $adminId, 'confirm_at' => date('Y-m-d H:i:s'), 'remark' => $remark, 'update_time' => time()])) {
  311. DB::rollBack();
  312. $this->error = '订单审核失败';
  313. return false;
  314. }
  315. if ($checkStatus == 2 && !GoodsModel::where(['id' => $goodsId])->update(['picker_status' => 2, 'update_time' => time()])) {
  316. DB::rollBack();
  317. $this->error = '订单审核失败';
  318. return false;
  319. }
  320. // // 用户数据更新
  321. $updateData = ['update_time' => time()];
  322. if ($checkStatus == 2) {
  323. // 接单数量
  324. $updateData['picker_order_num'] = DB::raw("picker_order_num + 1");
  325. } else {
  326. // 审核不过自动设置不可接单
  327. $updateData['picker_status'] = 2;
  328. }
  329. if (!MemberModel::where(['id' => $orderUserId])->update($updateData)) {
  330. DB::rollBack();
  331. $this->error = '订单审核失败';
  332. return false;
  333. }
  334. DB::commit();
  335. RedisService::keyDel("caches:orders:checkOrder:*");
  336. RedisService::keyDel("caches:members:info*");
  337. ActionLogModel::setRecord(session('userId'), ['type' => 1, 'title' => "订单审核", 'content' => json_encode(request()->post(), 256), 'module' => 'admin']);
  338. ActionLogModel::record();
  339. $this->error = '订单审核成功';
  340. return ['id' => $id];
  341. }
  342. /**
  343. * 订单取消
  344. * @return bool
  345. */
  346. public function cancel($adminId, $params)
  347. {
  348. $id = isset($params['id']) ? intval($params['id']) : 0;
  349. $remark = isset($params['remark']) ? trim($params['remark']) : '';
  350. $info = $this->model->with(['user', 'goods'])->where(['id' => $id, 'mark' => 1])->first();
  351. $userInfo = isset($info['user']) ? $info['user'] : [];
  352. $goods = isset($info['goods']) ? $info['goods'] : [];
  353. $status = isset($info['status']) ? $info['status'] : 0;
  354. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  355. $goodsId = isset($info['goods_id']) ? $info['goods_id'] : 0;
  356. if (empty($info) || empty($goods) || empty($userInfo) || $goodsId <= 0 || $orderUserId <= 0) {
  357. $this->error = '订单信息不存在或参数错误';
  358. return false;
  359. }
  360. if ($status == 9) {
  361. $this->error = '订单已取消';
  362. return false;
  363. }
  364. if ($status == 3) {
  365. $this->error = '订单已完成';
  366. return false;
  367. }
  368. DB::beginTransaction();
  369. if (!$this->model->where(['id' => $id])->update(['status' => 9, 'confirm_admin_id' => $adminId, 'confirm_at' => date('Y-m-d H:i:s'), 'remark' => $remark, 'update_time' => time()])) {
  370. DB::rollBack();
  371. $this->error = '订单取消失败';
  372. return false;
  373. }
  374. $pickerOrderNum = isset($userInfo['picker_order_num']) ? $userInfo['picker_order_num'] : 0;
  375. if (!MemberModel::where(['id' => $orderUserId])->update(['picker_order_num' => $pickerOrderNum ? DB::raw("picker_order_num - 1") : 0, 'update_time' => time()])) {
  376. DB::rollBack();
  377. $this->error = '订单取消失败';
  378. return false;
  379. }
  380. if (!GoodsModel::where(['id' => $goodsId])->update(['picker_status' => 1, 'update_time' => time()])) {
  381. DB::rollBack();
  382. $this->error = '订单取消失败';
  383. return false;
  384. }
  385. DB::commit();
  386. RedisService::keyDel("caches:orders:checkOrder:*");
  387. ActionLogModel::setRecord(session('userId'), ['type' => 1, 'title' => "订单取消", 'content' => json_encode(request()->post(), 256), 'module' => 'admin']);
  388. ActionLogModel::record();
  389. $this->error = '订单取消成功';
  390. return ['id' => $id];
  391. }
  392. /**
  393. * 订单完成
  394. * @return bool
  395. */
  396. public function complete($adminId, $params)
  397. {
  398. $id = isset($params['id']) ? intval($params['id']) : 0;
  399. $remark = isset($params['remark']) ? trim($params['remark']) : '';
  400. $info = $this->model->with(['user', 'goods'])->where(['id' => $id, 'mark' => 1])->first();
  401. $userInfo = isset($info['user']) ? $info['user'] : [];
  402. $goods = isset($info['goods']) ? $info['goods'] : [];
  403. $status = isset($info['status']) ? $info['status'] : 0;
  404. $orderUserId = isset($info['user_id']) ? $info['user_id'] : 0;
  405. $goodsId = isset($info['goods_id']) ? $info['goods_id'] : 0;
  406. $bonus = isset($info['bonus']) ? $info['bonus'] : 0;
  407. $orderUser = isset($info['user']) ? $info['user'] : [];
  408. if (empty($info) || empty($goods) || empty($userInfo) || $goodsId <= 0 || $orderUserId <= 0) {
  409. $this->error = '订单信息不存在或参数错误';
  410. return false;
  411. }
  412. if ($status != 2) {
  413. $this->error = '订单状态不可操作';
  414. return false;
  415. }
  416. DB::beginTransaction();
  417. if (!$this->model->where(['id' => $id])->update(['status' => 3, 'confirm_admin_id' => $adminId, 'confirm_at' => date('Y-m-d H:i:s'), 'remark' => $remark, 'update_time' => time()])) {
  418. DB::rollBack();
  419. $this->error = '订单确认完成失败';
  420. return false;
  421. }
  422. // 收入结算
  423. if ($bonus > 0) {
  424. $updateData = [
  425. 'balance' => DB::raw("balance + {$bonus}"),
  426. 'income_total' => DB::raw("income_total + {$bonus}"),
  427. 'complete_order_num' => DB::raw("complete_order_num + 1"),
  428. 'update_time' => time()
  429. ];
  430. if (!MemberModel::where(['id' => $orderUserId])->update($updateData)) {
  431. DB::rollBack();
  432. $this->error = '订单确认完成收入结算失败';
  433. return false;
  434. }
  435. // 收入记录
  436. $balance = isset($userInfo['balance']) ? $userInfo['balance'] : 0;
  437. $log = [
  438. 'user_id' => $orderUserId,
  439. 'source_order_no' => isset($info['order_no']) ? $info['order_no'] : '',
  440. 'type' => 1,
  441. 'money' => $bonus,
  442. 'before_money' => $balance,
  443. 'date' => date('Y-m-d'),
  444. 'create_time' => time(),
  445. 'remark' => '订单收入',
  446. 'status' => 1,
  447. 'mark' => 1,
  448. ];
  449. if (!AccountLogModel::insertGetId($log)) {
  450. DB::rollBack();
  451. $this->error = '订单确认完成收入结算失败';
  452. return false;
  453. }
  454. }
  455. if (!GoodsModel::where(['id' => $goodsId])->update(['picker_status' => 3, 'update_time' => time()])) {
  456. DB::rollBack();
  457. $this->error = '订单确认完成失败';
  458. return false;
  459. }
  460. // 公告消息
  461. $realname = isset($orderUser['realname']) ? $orderUser['realname'] : '';
  462. $realname = $realname ? get_realname($realname) : '师傅';
  463. $shipperAddress = isset($goods['shipper_address']) ? get_address($goods['shipper_address']) : '';
  464. $receiverAddress = isset($goods['receiver_address']) ? get_address($goods['receiver_address']) : '';
  465. $title = "{$realname}已完成从{$shipperAddress}到{$receiverAddress}的订单";
  466. NoticeService::make()->saveNotice($title);
  467. RedisService::keyDel("caches:orders:checkOrder:*");
  468. ActionLogModel::setRecord(session('userId'), ['type' => 1, 'title' => "订单确认完成", 'content' => json_encode(request()->post(), 256), 'module' => 'admin']);
  469. ActionLogModel::record();
  470. DB::commit();
  471. $this->error = '订单确认完成成功';
  472. return ['id' => $id];
  473. }
  474. /**
  475. * 删除订单
  476. */
  477. public function delete()
  478. {
  479. $id = request()->post('id');
  480. if (!$id) {
  481. return ['code' => 1, 'msg' => '参数错误'];
  482. }
  483. if (is_array($id)) {
  484. $result = $this->model->whereIn('id', $id)->update(['mark' => 0]);
  485. } else {
  486. $result = $this->model->where('id', $id)->update(['mark' => 0]);
  487. }
  488. if ($result) {
  489. ActionLogModel::setTitle("删除订单");
  490. ActionLogModel::record();
  491. RedisService::keyDel("caches:orders:*");
  492. return ['code' => 0, 'msg' => '删除成功'];
  493. }
  494. return ['code' => 1, 'msg' => '删除失败'];
  495. }
  496. /**
  497. * 更新订单状态
  498. */
  499. public function status()
  500. {
  501. $id = request()->post('id');
  502. $status = request()->post('status');
  503. $refundStatus = request()->post('refund_status');
  504. $refundRemark = request()->post('refund_remark', '');
  505. if (!$id) {
  506. return ['code' => 1, 'msg' => '参数错误'];
  507. }
  508. $updateData = ['update_time' => time()];
  509. // 更新订单状态
  510. if ($status !== null) {
  511. $updateData['status'] = $status;
  512. // 如果是完成订单,计算佣金
  513. if ($status == 4) {
  514. $order = $this->model->find($id);
  515. if ($order) {
  516. $updateData['bonus'] = round($order->pay_total * 0.05, 2);
  517. }
  518. }
  519. }
  520. // 更新退款状态
  521. if ($refundStatus !== null) {
  522. $updateData['refund_status'] = $refundStatus;
  523. $updateData['refund_remark'] = $refundRemark;
  524. // 如果同意退款,保持原订单状态不变
  525. // 退款状态通过 refund_status 字段管理
  526. }
  527. $result = $this->model->where('id', $id)->update($updateData);
  528. if ($result !== false) {
  529. ActionLogModel::setTitle("更新订单状态");
  530. ActionLogModel::record();
  531. RedisService::keyDel("caches:orders:*");
  532. return ['code' => 0, 'msg' => '操作成功'];
  533. }
  534. return ['code' => 1, 'msg' => '操作失败'];
  535. }
  536. /**
  537. * 完成支付
  538. */
  539. public function completePay()
  540. {
  541. $id = request()->post('id');
  542. $transactionId = request()->post('transaction_id', '');
  543. if (!$id) {
  544. return ['code' => 1, 'msg' => '参数错误'];
  545. }
  546. $order = $this->model->find($id);
  547. if (!$order) {
  548. return ['code' => 1, 'msg' => '订单不存在'];
  549. }
  550. if ($order->status != 1) {
  551. return ['code' => 1, 'msg' => '订单状态不正确'];
  552. }
  553. $updateData = [
  554. 'status' => 2, // 已付款
  555. 'transaction_id' => $transactionId ?: 'PAY' . time() . rand(1000, 9999),
  556. 'update_time' => time()
  557. ];
  558. $result = $this->model->where('id', $id)->update($updateData);
  559. if ($result) {
  560. ActionLogModel::setTitle("订单完成支付");
  561. ActionLogModel::record();
  562. RedisService::keyDel("caches:orders:*");
  563. return ['code' => 0, 'msg' => '支付完成'];
  564. }
  565. return ['code' => 1, 'msg' => '操作失败'];
  566. }
  567. /**
  568. * 订单发货
  569. */
  570. public function deliverOrder()
  571. {
  572. $id = request()->post('id');
  573. $deliveryCompany = request()->post('delivery_company', '');
  574. $deliveryNo = request()->post('delivery_no', '');
  575. $deliveryCode = request()->post('delivery_code', '');
  576. if (!$id) {
  577. return ['code' => 1, 'msg' => '参数错误'];
  578. }
  579. $order = $this->model->find($id);
  580. if (!$order) {
  581. return ['code' => 1, 'msg' => '订单不存在'];
  582. }
  583. if ($order->status != 2) {
  584. return ['code' => 1, 'msg' => '订单状态不正确,只有已付款订单可以发货'];
  585. }
  586. if (!$deliveryNo) {
  587. return ['code' => 1, 'msg' => '请填写快递单号'];
  588. }
  589. $updateData = [
  590. 'status' => 3, // 已发货
  591. 'delivery_company' => $deliveryCompany,
  592. 'delivery_no' => $deliveryNo,
  593. 'delivery_code' => $deliveryCode,
  594. 'update_time' => time()
  595. ];
  596. $result = $this->model->where('id', $id)->update($updateData);
  597. if ($result) {
  598. ActionLogModel::setTitle("订单发货");
  599. ActionLogModel::record();
  600. RedisService::keyDel("caches:orders:*");
  601. return ['code' => 0, 'msg' => '发货成功'];
  602. }
  603. return ['code' => 1, 'msg' => '操作失败'];
  604. }
  605. /**
  606. * 订单完成(管理后台)
  607. */
  608. public function completeOrder()
  609. {
  610. $id = request()->post('id');
  611. if (!$id) {
  612. return ['code' => 1, 'msg' => '参数错误'];
  613. }
  614. $order = $this->model->find($id);
  615. if (!$order) {
  616. return ['code' => 1, 'msg' => '订单不存在'];
  617. }
  618. if ($order->status != 3) {
  619. return ['code' => 1, 'msg' => '订单状态不正确,只有已发货订单可以完成'];
  620. }
  621. // 调用用户端的订单完成方法,触发收益结算等业务逻辑
  622. $apiOrderService = \App\Services\Api\OrderService::make();
  623. $result = $apiOrderService->complete($order->user_id, $id);
  624. if ($result) {
  625. ActionLogModel::setTitle("订单完成");
  626. ActionLogModel::record();
  627. RedisService::keyDel("caches:orders:*");
  628. return ['code' => 0, 'msg' => '确认收货成功'];
  629. }
  630. // 获取错误信息
  631. $error = $apiOrderService->getError();
  632. return ['code' => 1, 'msg' => $error ?: '操作失败', 'error' => $error];
  633. }
  634. /**
  635. * 取消订单
  636. */
  637. public function cancelOrder()
  638. {
  639. $id = request()->post('id');
  640. $cancelReason = request()->post('cancel_reason', '');
  641. if (!$id) {
  642. return ['code' => 1, 'msg' => '参数错误'];
  643. }
  644. $order = $this->model->find($id);
  645. if (!$order) {
  646. return ['code' => 1, 'msg' => '订单不存在'];
  647. }
  648. if ($order->status != 1) {
  649. return ['code' => 1, 'msg' => '只有待付款订单可以取消'];
  650. }
  651. $updateData = [
  652. 'mark' => 0, // 标记为删除
  653. 'update_time' => time()
  654. ];
  655. $result = $this->model->where('id', $id)->update($updateData);
  656. if ($result) {
  657. ActionLogModel::setTitle("取消订单");
  658. ActionLogModel::record();
  659. RedisService::keyDel("caches:orders:*");
  660. return ['code' => 0, 'msg' => '订单已取消'];
  661. }
  662. return ['code' => 1, 'msg' => '操作失败'];
  663. }
  664. /**
  665. * 申请退款
  666. */
  667. public function applyRefund()
  668. {
  669. $id = request()->post('id');
  670. $afterType = request()->post('after_type', 2); // 默认退款
  671. $afterRealname = request()->post('after_realname', '');
  672. $afterPhone = request()->post('after_phone', '');
  673. $afterRemark = request()->post('after_remark', '');
  674. if (!$id) {
  675. return ['code' => 1, 'msg' => '参数错误'];
  676. }
  677. if (!$afterRealname) {
  678. return ['code' => 1, 'msg' => '请填写联系人姓名'];
  679. }
  680. if (!$afterPhone) {
  681. return ['code' => 1, 'msg' => '请填写联系电话'];
  682. }
  683. if (!$afterRemark) {
  684. return ['code' => 1, 'msg' => '请填写退款原因'];
  685. }
  686. $order = $this->model->find($id);
  687. if (!$order) {
  688. return ['code' => 1, 'msg' => '订单不存在'];
  689. }
  690. // 只有已付款、已发货、已完成的订单可以申请退款
  691. if (!in_array($order->status, [2, 3, 4])) {
  692. return ['code' => 1, 'msg' => '该订单状态不允许申请退款'];
  693. }
  694. if ($order->refund_status != 0) {
  695. return ['code' => 1, 'msg' => '该订单已申请过退款'];
  696. }
  697. $updateData = [
  698. 'refund_status' => 3, // 待审核
  699. 'after_type' => $afterType, // 1-售后,2-退款
  700. 'after_realname' => $afterRealname,
  701. 'after_phone' => $afterPhone,
  702. 'after_remark' => $afterRemark,
  703. 'update_time' => time()
  704. ];
  705. $result = $this->model->where('id', $id)->update($updateData);
  706. if ($result) {
  707. $typeText = $afterType == 1 ? '售后' : '退款';
  708. ActionLogModel::setTitle("申请{$typeText}");
  709. ActionLogModel::record();
  710. RedisService::keyDel("caches:orders:*");
  711. return ['code' => 0, 'msg' => "{$typeText}申请已提交"];
  712. }
  713. return ['code' => 1, 'msg' => '操作失败'];
  714. }
  715. /**
  716. * 同意退款(审核通过,状态变为已审核)
  717. */
  718. public function agreeRefund()
  719. {
  720. $id = request()->post('id');
  721. $refundRemark = request()->post('refund_remark', '');
  722. if (!$id) {
  723. return ['code' => 1, 'msg' => '参数错误'];
  724. }
  725. $order = $this->model->find($id);
  726. if (!$order) {
  727. return ['code' => 1, 'msg' => '订单不存在'];
  728. }
  729. if ($order->refund_status != 3) {
  730. return ['code' => 1, 'msg' => '该订单未申请退款或已处理'];
  731. }
  732. $updateData = [
  733. 'refund_status' => 2, // 已审核(待确认退款)
  734. 'refund_remark' => $refundRemark ?: '退款申请已通过,待确认退款',
  735. 'update_time' => time()
  736. ];
  737. $result = $this->model->where('id', $id)->update($updateData);
  738. if ($result) {
  739. ActionLogModel::setTitle("同意退款");
  740. ActionLogModel::record();
  741. RedisService::keyDel("caches:orders:*");
  742. return ['code' => 0, 'msg' => '已同意退款,请确认退款'];
  743. }
  744. return ['code' => 1, 'msg' => '操作失败'];
  745. }
  746. /**
  747. * 确认退款(最终完成退款)
  748. */
  749. public function confirmRefund()
  750. {
  751. $id = request()->post('id');
  752. $refundAmount = request()->post('refund_amount', 0);
  753. if (!$id) {
  754. return ['code' => 1, 'msg' => '参数错误'];
  755. }
  756. if ($refundAmount <= 0) {
  757. return ['code' => 1, 'msg' => '请输入退款金额'];
  758. }
  759. $order = $this->model->find($id);
  760. if (!$order) {
  761. return ['code' => 1, 'msg' => '订单不存在'];
  762. }
  763. // 允许待审核(3)和已审核(2)状态的订单进行退款
  764. if (!in_array($order->refund_status, [2, 3])) {
  765. return ['code' => 1, 'msg' => '该订单状态不允许退款'];
  766. }
  767. if ($refundAmount > $order->pay_total) {
  768. return ['code' => 1, 'msg' => '退款金额不能大于订单金额'];
  769. }
  770. // 使用事务
  771. DB::beginTransaction();
  772. try {
  773. // 调用支付服务退款
  774. $paymentService = \App\Services\PaymentService::make();
  775. $refundData = [
  776. 'money' => $refundAmount,
  777. 'pay_type' => $order->pay_type,
  778. 'order_no' => $order->order_no,
  779. 'out_trade_no' => $order->out_trade_no,
  780. 'transaction_id' => $order->transaction_id,
  781. 'remark' => '订单退款'
  782. ];
  783. $refundResult = $paymentService->refund($refundData, 'store');
  784. if (!$refundResult) {
  785. DB::rollBack();
  786. return ['code' => 1, 'msg' => '退款失败:' . $paymentService->getError() ?: '退款失败'];
  787. }
  788. // 更新订单状态
  789. $updateData = [
  790. 'refund_status' => 1, // 已退款
  791. 'refund_amount' => $refundAmount,
  792. 'update_time' => time()
  793. ];
  794. $result = $this->model->where('id', $id)->update($updateData);
  795. if ($result) {
  796. DB::commit();
  797. ActionLogModel::setTitle("确认退款");
  798. ActionLogModel::record();
  799. RedisService::keyDel("caches:orders:*");
  800. return ['code' => 0, 'msg' => '退款成功'];
  801. }
  802. DB::rollBack();
  803. return ['code' => 1, 'msg' => '更新订单状态失败'];
  804. } catch (\Exception $e) {
  805. DB::rollBack();
  806. return ['code' => 1, 'msg' => '退款失败:' . $e->getMessage()];
  807. }
  808. }
  809. /**
  810. * 拒绝退款
  811. */
  812. public function rejectRefund()
  813. {
  814. $id = request()->post('id');
  815. $refundRemark = request()->post('refund_remark', '');
  816. if (!$id) {
  817. return ['code' => 1, 'msg' => '参数错误'];
  818. }
  819. if (!$refundRemark) {
  820. return ['code' => 1, 'msg' => '请填写拒绝原因'];
  821. }
  822. $order = $this->model->find($id);
  823. if (!$order) {
  824. return ['code' => 1, 'msg' => '订单不存在'];
  825. }
  826. if ($order->refund_status != 3) {
  827. return ['code' => 1, 'msg' => '该订单未申请退款或已处理'];
  828. }
  829. $updateData = [
  830. 'refund_status' => 4, // 审核驳回
  831. 'refund_remark' => $refundRemark,
  832. 'update_time' => time()
  833. ];
  834. $result = $this->model->where('id', $id)->update($updateData);
  835. if ($result) {
  836. ActionLogModel::setTitle("拒绝退款");
  837. ActionLogModel::record();
  838. RedisService::keyDel("caches:orders:*");
  839. return ['code' => 0, 'msg' => '已拒绝退款'];
  840. }
  841. return ['code' => 1, 'msg' => '操作失败'];
  842. }
  843. /**
  844. * 订单统计
  845. * @param int $storeId 商户ID,0表示平台管理员查看全部数据
  846. */
  847. public function getStatistics($storeId = 0)
  848. {
  849. // 总订单数
  850. $total = $this->model->where('mark', 1)
  851. ->when($storeId > 0, function ($query) use ($storeId) {
  852. return $query->where('store_id', $storeId);
  853. })
  854. ->count();
  855. // 总交易额(已完成订单)
  856. $totalAmount = $this->model->where('mark', 1)
  857. ->where('status', 4)
  858. ->when($storeId > 0, function ($query) use ($storeId) {
  859. return $query->where('store_id', $storeId);
  860. })
  861. ->sum('pay_total');
  862. // 待处理订单(待付款 + 已付款)
  863. $pending = $this->model->where('mark', 1)
  864. ->whereIn('status', [1, 2])
  865. ->when($storeId > 0, function ($query) use ($storeId) {
  866. return $query->where('store_id', $storeId);
  867. })
  868. ->count();
  869. // 待退款订单
  870. $refunding = $this->model->where('mark', 1)
  871. ->where('refund_status', 3)
  872. ->when($storeId > 0, function ($query) use ($storeId) {
  873. return $query->where('store_id', $storeId);
  874. })
  875. ->count();
  876. return [
  877. 'code' => 0,
  878. 'msg' => '操作成功',
  879. 'data' => [
  880. 'total' => $total,
  881. 'totalAmount' => number_format($totalAmount, 2, '.', ''),
  882. 'pending' => $pending,
  883. 'refunding' => $refunding
  884. ]
  885. ];
  886. }
  887. /**
  888. * 导出订单数据
  889. */
  890. public function exportData($params)
  891. {
  892. $query = $this->model->where('mark', 1);
  893. // 店铺筛选
  894. if (isset($params['store_id']) && $params['store_id'] > 0) {
  895. $query->where('store_id', $params['store_id']);
  896. }
  897. // 用户筛选
  898. if (isset($params['user_id']) && $params['user_id'] > 0) {
  899. $query->where('user_id', $params['user_id']);
  900. }
  901. // 状态筛选
  902. if (isset($params['status']) && $params['status'] > 0) {
  903. $query->where('status', $params['status']);
  904. }
  905. // 售后类型筛选
  906. if (isset($params['after_type']) && $params['after_type'] > 0) {
  907. $query->where('after_type', $params['after_type']);
  908. }
  909. // 退款状态筛选
  910. if (isset($params['refund_status']) && $params['refund_status'] > 0) {
  911. $query->where('refund_status', $params['refund_status']);
  912. }
  913. // 关键词搜索
  914. if (isset($params['keyword']) && $params['keyword']) {
  915. $keyword = $params['keyword'];
  916. $query->where(function ($q) use ($keyword) {
  917. $q->where('order_no', 'like', '%' . $keyword . '%')
  918. ->orWhere('receiver_name', 'like', '%' . $keyword . '%')
  919. ->orWhere('receiver_mobile', 'like', '%' . $keyword . '%');
  920. });
  921. }
  922. $list = $query->with(['user', 'orderGoods', 'store'])
  923. ->orderBy('create_time', 'desc')
  924. ->limit(5000)
  925. ->get();
  926. if (!$list || $list->isEmpty()) {
  927. return response()->json(['code' => 1, 'msg' => '没有可导出的数据']);
  928. }
  929. // 状态映射
  930. $statusMap = [1 => '待付款', 2 => '已付款', 3 => '已发货', 4 => '已完成', 9 => '已取消'];
  931. $refundStatusMap = [0 => '无', 1 => '已退款', 2 => '已审核', 3 => '待审核'];
  932. // 构建导出数据
  933. $data = [];
  934. foreach ($list as $item) {
  935. $goodsNames = [];
  936. if ($item->orderGoods) {
  937. foreach ($item->orderGoods as $goods) {
  938. $goodsNames[] = $goods->goods_name . ' x' . $goods->num;
  939. }
  940. }
  941. $data[] = [
  942. $item->order_no,
  943. $item->user->nickname ?? '',
  944. $item->user->mobile ?? '',
  945. implode(';', $goodsNames),
  946. $item->total ?? 0,
  947. $item->pay_total ?? 0,
  948. $statusMap[$item->status] ?? '未知',
  949. $refundStatusMap[$item->refund_status] ?? '无',
  950. $item->receiver_name ?? '',
  951. $item->receiver_mobile ?? '',
  952. $item->receiver_address ?? '',
  953. $item->create_time ? date('Y-m-d H:i:s', strtotime($item->create_time)) : '',
  954. ];
  955. }
  956. $headings = ['订单号', '用户昵称', '用户手机', '商品信息', '订单金额', '实付金额', '订单状态', '退款状态', '收货人', '收货电话', '收货地址', '下单时间'];
  957. $export = new \App\Exports\Export($data, $headings, '订单列表');
  958. $filename = '订单列表_' . date('YmdHis') . '.xlsx';
  959. return \Maatwebsite\Excel\Facades\Excel::download($export, $filename);
  960. }
  961. }