OrderService.php 34 KB

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