OrderService.php 35 KB

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