OrderService.php 36 KB

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