| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027 |
- <?php
- // +----------------------------------------------------------------------
- // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
- // +----------------------------------------------------------------------
- // | 版权所有 2017~2021 LARAVEL研发中心
- // +----------------------------------------------------------------------
- // | 官方网站: http://www.laravel.cn
- // +----------------------------------------------------------------------
- // | Author: laravel开发员 <laravel.qq.com>
- // +----------------------------------------------------------------------
- namespace App\Services\Common;
- use App\Models\AccountLogModel;
- use App\Models\ActionLogModel;
- use App\Models\GoodsModel;
- use App\Models\MemberModel;
- use App\Models\MessageModel;
- use App\Models\OrderModel;
- use App\Models\OrderGoodsModel;
- use App\Models\PayOrdersModel;
- use App\Models\StoreModel;
- use App\Services\Api\SettleService;
- use App\Services\BaseService;
- use App\Services\Kd100Service;
- use App\Services\MpService;
- use App\Services\RedisService;
- use Illuminate\Support\Facades\DB;
- /**
- * 订单管理-服务类
- * @author laravel开发员
- * @since 2020/11/11
- * Class OrderService
- * @package App\Services\Common
- */
- class OrderService extends BaseService
- {
- // 静态对象
- protected static $instance = null;
- /**
- * 构造函数
- * @author laravel开发员
- * @since 2020/11/11
- * OrderService constructor.
- */
- public function __construct()
- {
- $this->model = new OrderModel();
- }
- /**
- * 静态入口
- * @return static|null
- */
- public static function make()
- {
- if (!self::$instance) {
- self::$instance = (new static());
- }
- return self::$instance;
- }
- /**
- * @param $params
- * @param int $pageSize
- * @return array
- */
- public function getDataList($params, $pageSize = 15)
- {
- $query = $this->model->where('mark', 1);
- // 店铺筛选
- if (isset($params['store_id']) && $params['store_id'] > 0) {
- $query->where('store_id', $params['store_id']);
- }
- // 用户筛选
- if (isset($params['user_id']) && $params['user_id'] > 0) {
- $query->where('user_id', $params['user_id']);
- }
- // 状态筛选
- if (isset($params['status']) && $params['status'] > 0) {
- $query->where('status', $params['status']);
- }
- // 售后类型筛选(1-售后,2-退款)
- if (isset($params['after_type']) && $params['after_type'] > 0) {
- $query->where('after_type', $params['after_type']);
- }
- // 退款状态筛选
- if (isset($params['refund_status']) && $params['refund_status'] > 0) {
- $query->where('refund_status', $params['refund_status']);
- }
- // 关键词搜索(订单号、商品名称、收货人手机)
- if (isset($params['keyword']) && $params['keyword']) {
- $keyword = $params['keyword'];
- $query->where(function ($q) use ($keyword) {
- $q->where('order_no', 'like', '%' . $keyword . '%')
- ->orWhere('receiver_name', 'like', '%' . $keyword . '%')
- ->orWhere('receiver_mobile', 'like', '%' . $keyword . '%')
- ->orWhereHas('orderGoods', function ($q2) use ($keyword) {
- $q2->where('goods_name', 'like', '%' . $keyword . '%');
- });
- });
- }
- $list = $query->with(['user', 'orderGoods', 'store'])
- ->orderBy('create_time', 'desc')
- ->orderBy('id', 'desc')
- ->paginate($pageSize);
- $list = $list ? $list->toArray() : [];
- if ($list && isset($list['data'])) {
- foreach ($list['data'] as &$item) {
- $item['create_time'] = $item['create_time'] ? datetime($item['create_time']) : '';$item['user'] = $item['user'] ?? [];
- $item['store'] = $item['store'] ?? [];
- // 获取第一个商品信息(thumb已通过Model访问器处理)
- $item['goods'] = isset($item['order_goods'][0]) ? $item['order_goods'][0] : null;
- }
- }
- return [
- 'msg' => '操作成功',
- 'code' => 0,
- 'data' => $list['data'] ?? [],
- 'count' => $list['total'] ?? 0,
- ];
- }
- /**
- * 获取订单详情
- */
- public function getInfo($id)
- {
- $info = $this->model->where('id', $id)->where('mark', 1)
- ->with(['user', 'orderGoods', 'store','recUser'])
- ->first();
- if (!$info) {
- return ['code' => 1, 'msg' => '订单不存在'];
- }
- $info = $info->toArray();
- $info['create_time'] = $info['create_time'] ? date('Y-m-d H:i:s', strtotime($info['create_time'])) : '';
- $info['update_time'] = $info['update_time'] ? date('Y-m-d H:i:s', strtotime($info['update_time'])) : '';
- if (isset($info['order_goods'])) {
- foreach ($info['order_goods'] as &$goods) {
- $goods['thumb'] = $goods['thumb'] ? get_image_url($goods['thumb']) : '';
- $goods['create_time'] = $goods['create_time'] ? date('Y-m-d H:i:s', strtotime($goods['create_time'])) : '';
- $goods['update_time'] = $goods['update_time'] ? date('Y-m-d H:i:s', strtotime($goods['update_time'])) : '';
- }
- }
- return ['code' => 0, 'msg' => '操作成功', 'data' => $info];
- }
- /**
- * 查询
- * @param $params
- * @return \Illuminate\Database\Eloquent\Builder
- */
- public function getQuery($params)
- {
- $where = ['a.mark' => 1];
- $userId = isset($params['user_id']) ? $params['user_id'] : 0;
- return $this->model->with(['user', 'goods'])->from('orders as a')
- ->leftJoin('member as b', 'a.user_id', '=', 'b.id')
- ->leftJoin('goods as c', 'c.id', '=', 'a.goods_id')
- ->where($where)
- ->where(function ($query) use ($params) {
- $keyword = isset($params['keyword']) ? $params['keyword'] : '';
- if ($keyword) {
- $query->where('a.order_no', 'like', "%{$keyword}%");
- }
- // 接单人
- $account = isset($params['account']) ? $params['account'] : '';
- if ($account) {
- $query->where(function ($query) use ($account) {
- $query->where('b.nickname', 'like', "%{$account}%")->orWhere('b.mobile', 'like', "%{$account}%");
- });
- }
- // 商品
- $goodsId = isset($params['goods_id']) ? intval($params['goods_id']) : 0;
- $goods = isset($params['goods']) ? trim($params['goods']) : '';
- if ($goods) {
- $query->where(function ($query) use ($goods) {
- $query->where('c.goods_name', 'like', "%{$goods}%");
- if (preg_match("/^(1[0-9]+|[1-9]+)$/", $goods)) {
- $query->where('a.goods_id', intval($goods));
- } else {
- $query->where('c.goods_name', 'like', "%{$goods}%");
- }
- });
- }
- if ($goodsId > 0) {
- $query->where('a.goods_id', intval($goodsId));
- }
- })
- ->where(function ($query) use ($params) {
- $status = isset($params['status']) ? $params['status'] : 0;
- if ($status == 0) {
- $query->whereIn('a.status', [2, 3]);
- } else if ($status) {
- $query->where('a.status', $status);
- }
- })
- ->where(function ($query) use ($userId) {
- if ($userId) {
- $query->where('a.user_id', '=', $userId);
- }
- });
- }
- /**
- * 物流查询
- * @param $id
- * @return array|false|mixed
- */
- public function getDelivery($id)
- {
- $info = $this->model->where(['id' => $id, 'mark' => 1])->first();
- $deliveryType = isset($info['delivery_type']) ? $info['delivery_type'] : 1;
- $deliveryNo = isset($info['delivery_no']) ? $info['delivery_no'] : '';
- $deliveryCode = isset($info['delivery_code']) ? $info['delivery_code'] : '';
- $deliveryName = isset($info['delivery_name']) ? $info['delivery_name'] : '';
- $deliveryMobile = isset($info['delivery_mobile']) ? $info['delivery_mobile'] : '';
- $deliveryAt = isset($info['delivery_at']) ? $info['delivery_at'] : '';
- $mobile = isset($info['receiver_mobile']) ? $info['receiver_mobile'] : '';
- $receiverArea = isset($info['receiver_area']) && $info['receiver_area']? $info['receiver_area'] : '';
- if (empty($info)) {
- return ['code'=>1,'msg'=>'请选择订单'];
- }
- if($deliveryType==2){
- return['code'=>0,'data'=> ['info'=>['deliveryManName'=>$deliveryName,'deliveryPhone'=>$deliveryMobile,'deliveryManPhone'=>[$deliveryMobile]],'arrivalData'=>['arrivalTime'=>$deliveryAt]]];
- }
- $cacheKey = "caches:kd100:order_admin_{$id}";
- $data = RedisService::get($cacheKey);
- if ($data) {
- return ['code'=>0,'data'=>$data];
- }
- $result = Kd100Service::make()->query($deliveryNo, $mobile, $deliveryCode,$receiverArea);
- RedisService::set($cacheKey.'_result', $result, 300);
- $status = isset($result['status'])?$result['status']:0;
- $data = isset($result['data'])?$result['data']:[];
- $courierInfo = isset($result['courierInfo'])?$result['courierInfo']:[];
- $arrivalTime = isset($result['arrivalTime'])?$result['arrivalTime']:'';
- $message = isset($result['message'])?$result['message']:'';
- $predictedRoute = isset($result['predictedRoute'])?$result['predictedRoute']:[];
- $predictedData = $predictedRoute?end($predictedRoute):[];
- $arrivalData = [];
- if($arrivalTime){
- $arrivalData['arrivalTime'] = dayFormat(strtotime($arrivalTime.':00:00'));
- $arrivalData['predictedData'] = $predictedData;
- }
- if($courierInfo && $courierInfo['deliveryManPhone']){
- $courierInfo['deliveryManPhone'] = explode(',', $courierInfo['deliveryManPhone']);
- $courierInfo['deliveryPhone'] = $courierInfo['deliveryManPhone'][1]?$courierInfo['deliveryManPhone'][1]:$courierInfo['deliveryManPhone'][0];
- }
- if ($data && $status==200) {
- RedisService::set($cacheKey, ['info'=>$courierInfo,'arrivalData'=>$arrivalData,'list'=>$data], 1200);
- }else{
- return ['code'=>1,'msg'=>'查询物流信息失败:'.$message];
- }
- return ['code'=>0,'data'=>['info'=>$courierInfo,'arrivalData'=>$arrivalData,'list'=>$data]];
- }
- /**
- * 按日期统计订单数
- * @param string $beginAt 开始时间
- * @param string $endAt 结束时间
- * @param int[] $status 状态:数组或数值
- * @return mixed
- */
- public function getCountByTime($beginAt = '', $endAt = '', $status = 3)
- {
- $cacheKey = "caches:orders:count_{$status}_{$beginAt}_{$endAt}";
- $data = RedisService::get($cacheKey);
- if ($data) {
- return $data;
- }
- $where = ['mark' => 1];
- $data = $this->model->where($where)->where(function ($query) use ($beginAt, $endAt, $status) {
- if ($beginAt && $endAt) {
- $query->whereBetween('create_time', [strtotime($beginAt), strtotime($endAt)]);
- } else if ($beginAt) {
- $query->where('create_time', '>=', strtotime($beginAt));
- }
- if ($status && is_array($status)) {
- $query->whereIn('status', $status);
- } else if ($status) {
- $query->where('status', $status);
- }
- })->count('id');
- if ($data) {
- RedisService::set($cacheKey, $data, rand(300, 600));
- }
- return $data;
- }
- /**
- * 按日期统计订单金额
- * @param string $beginAt 开始时间
- * @param string $endAt 结束时间
- * @param int[] $status 状态:数组或数值
- * @return mixed
- */
- public function getTotalByTime($beginAt = '', $endAt = '', $status = 3)
- {
- $cacheKey = "caches:orders:total_{$status}_{$beginAt}_{$endAt}";
- $data = RedisService::get($cacheKey);
- if ($data) {
- return $data;
- }
- $where = ['mark' => 1];
- $data = $this->model->where($where)->where(function ($query) use ($beginAt, $endAt, $status) {
- if ($beginAt && $endAt) {
- $query->whereBetween('create_time', [strtotime($beginAt), strtotime($endAt)]);
- } else if ($beginAt) {
- $query->where('create_time', '>=', strtotime($beginAt));
- }
- if ($status && is_array($status)) {
- $query->whereIn('status', $status);
- } else if ($status) {
- $query->where('status', $status);
- }
- })->sum('total');
- if ($data) {
- RedisService::set($cacheKey, $data, rand(300, 600));
- }
- return $data;
- }
- /**
- * 添加或编辑
- * @return array
- * @since 2020/11/11
- * @author laravel开发员
- */
- public function edit()
- {
- $params = request()->post();
- return parent::edit($params); // TODO: Change the autogenerated stub
- }
- /**
- * 完成支付
- */
- public function completePay()
- {
- $id = request()->post('id');
- $transactionId = request()->post('transaction_id', '');
- if (!$id) {
- return ['code' => 1, 'msg' => '参数错误'];
- }
- $order = $this->model->find($id);
- if (!$order) {
- return ['code' => 1, 'msg' => '订单不存在'];
- }
- if ($order->status != 1) {
- return ['code' => 1, 'msg' => '订单状态不正确'];
- }
- $updateData = [
- 'status' => 2, // 已付款
- 'transaction_id' => $transactionId ?: 'PAY' . time() . rand(1000, 9999),
- 'pay_at'=> date('Y-m-d H:i:s'),
- 'remark'=> '人工审核支付',
- 'update_time' => time()
- ];
- $result = $this->model->where('id', $id)->update($updateData);
- if ($result) {
- ActionLogModel::setTitle("订单完成支付");
- ActionLogModel::record();
- RedisService::keyDel("caches:orders:*");
- return ['code' => 0, 'msg' => '支付完成'];
- }
- return ['code' => 1, 'msg' => '操作失败'];
- }
- /**
- * 订单发货
- */
- public function deliverOrder()
- {
- $id = request()->post('id');
- $deliveryCompany = request()->post('delivery_company', '');
- $deliveryNo = request()->post('delivery_no', '');
- $deliveryType = request()->post('delivery_type', 1);
- $deliveryName = request()->post('delivery_name', '');
- $deliveryMobile = request()->post('delivery_mobile', '');
- $deliveryAt = request()->post('delivery_at', '');
- $deliveryCode = request()->post('delivery_code', '');
- if (!$id) {
- return ['code' => 1, 'msg' => '参数错误'];
- }
- $order = $this->model->find($id);
- if (!$order) {
- return ['code' => 1, 'msg' => '订单不存在'];
- }
- if ($order->status != 2) {
- return ['code' => 1, 'msg' => '订单状态不正确,只有已付款订单可以发货'];
- }
- if($deliveryType == 2){
- if (!$deliveryName) {
- return ['code' => 1, 'msg' => '请填写送货人姓名'];
- }
- if (!$deliveryMobile) {
- return ['code' => 1, 'msg' => '请填写送货人手机号'];
- }
- }else{
- if (!$deliveryNo) {
- return ['code' => 1, 'msg' => '请填写快递单号'];
- }
- if (!$deliveryCompany) {
- return ['code' => 1, 'msg' => '请选择快递公司'];
- }
- }
- $updateData = [
- 'status' => 3, // 已发货
- 'delivery_type' => $deliveryType,
- 'delivery_company' => $deliveryCompany,
- 'delivery_no' => $deliveryNo,
- 'delivery_code' => $deliveryCode,
- 'delivery_name' => $deliveryName,
- 'delivery_mobile' => $deliveryMobile,
- 'delivery_at' => $deliveryAt,
- 'update_time' => time()
- ];
- $result = $this->model->where('id', $id)->update($updateData);
- // 调用小程序发货信息同步接口
- $msg = '发货成功';
- if($deliveryType == 1 && $openid){
- $sendData = [
- 'order_key' => [
- "order_number_type" => 2,
- "transaction_id" => isset($order['transaction_id']) ? $order['transaction_id'] : '',
- "out_trade_no" => isset($order['out_trade_no']) ? $order['out_trade_no'] : ''
- ],
- "delivery_mode" => 1,
- "logistics_type" => 1,
- "shipping_list" => [
- [
- "tracking_no" => $deliveryNo,
- "express_company" => $deliveryCompany,
- "item_desc" => $goodsName."*".$goodsNum.$goodsUnit,
- "contact" => [
- "receiver_contact" => isset($order['receiver_mobile']) && $order['receiver_mobile'] ? format_mobile($order['receiver_mobile']) : format_mobile($mobile)
- ]
- ]
- ],
- "upload_time" => date('Y-m-d\TH:i:s.vP'),
- "payer" => [
- "openid" => $openid
- ]
- ];
- $result = MpService::make()->requestApi('deliverySend',$sendData);
- $errcode = isset($result['errcode'])?$result['errcode'] : -1;
- $errmsg = isset($result['errmsg']) && $result['errmsg']?$result['errmsg'] : '请求失败';
- if($errcode != 0){
- $msg = '发货成功,但上传发货信息到小程序失败:'.$errmsg;
- }else {
- $msg = '发货成功,上传发货信息到小程序成功';
- }
- }
- if ($result) {
- ActionLogModel::setTitle("订单发货");
- ActionLogModel::record();
- RedisService::keyDel("caches:orders:*");
- return ['code' => 0, 'msg' => $msg];
- }
- return ['code' => 1, 'msg' => '操作失败'];
- }
- /**
- * 订单完成(管理后台)
- */
- public function completeOrder()
- {
- $id = request()->post('id');
- if (!$id) {
- return ['code' => 1, 'msg' => '参数错误'];
- }
- $order = $this->model->find($id);
- if (!$order) {
- return ['code' => 1, 'msg' => '订单不存在'];
- }
- if ($order->status != 3) {
- return ['code' => 1, 'msg' => '订单状态不正确,只有已发货订单可以完成'];
- }
- // 调用用户端的订单完成方法,触发收益结算等业务逻辑
- $apiOrderService = \App\Services\Api\OrderService::make();
- $result = $apiOrderService->complete($order->user_id, $id);
- if ($result) {
- ActionLogModel::setTitle("订单完成");
- ActionLogModel::record();
- RedisService::keyDel("caches:orders:*");
- return ['code' => 0, 'msg' => '确认收货成功'];
- }
- // 获取错误信息
- $error = $apiOrderService->getError();
- return ['code' => 1, 'msg' => $error ?: '操作失败', 'error' => $error];
- }
- /**
- * 取消订单
- */
- public function settleOrder()
- {
- $id = request()->post('id');
- if (!$id) {
- return ['code' => 1, 'msg' => '参数错误'];
- }
- $cacheLockKey = "caches:orders:settle_".$id.'_lock';
- if(RedisService::get($cacheLockKey)){
- return ['code' => 1, 'msg' => '结算中'];
- }
- $order = $this->model->find($id);
- $orderNo = isset($order['order_no'])?$order['order_no']:'';
- $storeId = isset($order['store_id'])?$order['store_id']:0;
- $userId = isset($order['user_id'])?$order['user_id']:0;
- if (!$order) {
- return ['code' => 1, 'msg' => '订单不存在'];
- }
- if ($order->bonus_settle == 1) {
- return ['code' => 1, 'msg' => '佣金收益已结算'];
- }
- if ($order->status != 4) {
- return ['code' => 1, 'msg' => '订单未完成'];
- }
- RedisService::set($cacheLockKey, $order, rand(10,20));
- DB::beginTransaction();
- // 结算商家收益
- $result = SettleService::make()->storeBonus($storeId, $order['bonus'], $order);
- if ($result < 0) {
- DB::rollBack();
- $this->error = SettleService::make()->getError();
- RedisService::clear($cacheLockKey);
- \App\Services\Api\OrderService::make()->saveLog("caches:settle:{$orderNo}:store_{$storeId}_error",SettleService::make()->getError());
- return false;
- }
- \App\Services\Api\OrderService::make()->saveLog("caches:settle:{$orderNo}:store_{$storeId}",['msg'=>SettleService::make()->getError(),'result'=>$result]);
- // 代理佣金结算
- $result1 = SettleService::make()->agentBonus($userId, $order['rec_bonus'], $order, $order['rec_bonus_id']);
- if ($result1 < 0) {
- DB::rollBack();
- $this->error = SettleService::make()->getError();
- RedisService::clear($cacheLockKey);
- \App\Services\Api\OrderService::make()->saveLog("caches:settle:{$orderNo}:agent_{$userId}_error",SettleService::make()->getError());
- return false;
- }
- \App\Services\Api\OrderService::make()->saveLog("caches:settle:{$orderNo}:agent_{$userId}",['msg'=>SettleService::make()->getError(),'result'=>$result1]);
- // 更新订单结算状态
- if(!$this->model->where(['id'=>$id])->update(['bonus_settle'=>1,'update_time'=>time()])){
- DB::rollBack();
- $this->error = '收益结算状态更新失败';
- RedisService::clear($cacheLockKey);
- return false;
- }
- DB::commit();
- ActionLogModel::setTitle("订单结算");
- ActionLogModel::record();
- RedisService::keyDel("caches:orders:*");
- return ['code' => 0, 'msg' => '订单结算'];
- }
- /**
- * 取消订单
- */
- public function cancelOrder()
- {
- $id = request()->post('id');
- $cancelReason = request()->post('cancel_reason', '');
- if (!$id) {
- return ['code' => 1, 'msg' => '参数错误'];
- }
- $order = $this->model->find($id);
- if (!$order) {
- return ['code' => 1, 'msg' => '订单不存在'];
- }
- if ($order->status != 1) {
- return ['code' => 1, 'msg' => '只有待付款订单可以取消'];
- }
- $updateData = [
- 'mark' => 0, // 标记为删除
- 'update_time' => time()
- ];
- $result = $this->model->where('id', $id)->update($updateData);
- if ($result) {
- ActionLogModel::setTitle("取消订单");
- ActionLogModel::record();
- RedisService::keyDel("caches:orders:*");
- return ['code' => 0, 'msg' => '订单已取消'];
- }
- return ['code' => 1, 'msg' => '操作失败'];
- }
- /**
- * 申请退款
- */
- public function applyRefund()
- {
- $id = request()->post('id');
- $afterType = request()->post('after_type', 2); // 默认退款
- $afterRealname = request()->post('after_realname', '');
- $afterPhone = request()->post('after_phone', '');
- $afterRemark = request()->post('after_remark', '');
- if (!$id) {
- return ['code' => 1, 'msg' => '参数错误'];
- }
- if (!$afterRealname) {
- return ['code' => 1, 'msg' => '请填写联系人姓名'];
- }
- if (!$afterPhone) {
- return ['code' => 1, 'msg' => '请填写联系电话'];
- }
- if (!$afterRemark) {
- return ['code' => 1, 'msg' => '请填写退款原因'];
- }
- $order = $this->model->find($id);
- if (!$order) {
- return ['code' => 1, 'msg' => '订单不存在'];
- }
- // 只有已付款、已发货、已完成的订单可以申请退款
- if (!in_array($order->status, [2, 3, 4])) {
- return ['code' => 1, 'msg' => '该订单状态不允许申请退款'];
- }
- if ($order->refund_status != 0) {
- return ['code' => 1, 'msg' => '该订单已申请过退款'];
- }
- $updateData = [
- 'refund_status' => 3, // 待审核
- 'after_type' => $afterType, // 1-售后,2-退款
- 'after_realname' => $afterRealname,
- 'after_phone' => $afterPhone,
- 'after_remark' => $afterRemark,
- 'update_time' => time()
- ];
- $result = $this->model->where('id', $id)->update($updateData);
- if ($result) {
- $typeText = $afterType == 1 ? '售后' : '退款';
- ActionLogModel::setTitle("申请{$typeText}");
- ActionLogModel::record();
- RedisService::keyDel("caches:orders:*");
- return ['code' => 0, 'msg' => "{$typeText}申请已提交"];
- }
- return ['code' => 1, 'msg' => '操作失败'];
- }
- /**
- * 同意退款(审核通过,状态变为已审核)
- */
- public function agreeRefund()
- {
- $id = request()->post('id');
- $refundRemark = request()->post('refund_remark', '');
- if (!$id) {
- return ['code' => 1, 'msg' => '参数错误'];
- }
- $order = $this->model->find($id);
- if (!$order) {
- return ['code' => 1, 'msg' => '订单不存在'];
- }
- if ($order->refund_status != 3) {
- return ['code' => 1, 'msg' => '该订单未申请退款或已处理'];
- }
- $updateData = [
- 'refund_status' => 2, // 已审核(待确认退款)
- 'refund_remark' => $refundRemark ?: '退款申请已通过,待确认退款',
- 'update_time' => time()
- ];
- $result = $this->model->where('id', $id)->update($updateData);
- if ($result) {
- ActionLogModel::setTitle("同意退款");
- ActionLogModel::record();
- RedisService::keyDel("caches:orders:*");
- return ['code' => 0, 'msg' => '已同意退款,请确认退款'];
- }
- return ['code' => 1, 'msg' => '操作失败'];
- }
- /**
- * 确认退款(最终完成退款)
- */
- public function confirmRefund()
- {
- $id = request()->post('id');
- $refundAmount = request()->post('refund_amount', 0);
- if (!$id) {
- return ['code' => 1, 'msg' => '参数错误'];
- }
- if ($refundAmount <= 0) {
- return ['code' => 1, 'msg' => '请输入退款金额'];
- }
- $order = $this->model->find($id);
- if (!$order) {
- return ['code' => 1, 'msg' => '订单不存在'];
- }
- // 允许待审核(3)和已审核(2)状态的订单进行退款
- if (!in_array($order->refund_status, [2, 3])) {
- return ['code' => 1, 'msg' => '该订单状态不允许退款'];
- }
- if ($refundAmount > $order->pay_total) {
- return ['code' => 1, 'msg' => '退款金额不能大于订单金额'];
- }
- // 使用事务
- DB::beginTransaction();
- try {
- // 调用支付服务退款
- $paymentService = \App\Services\PaymentService::make();
- $refundData = [
- 'money' => $refundAmount,
- 'pay_type' => $order->pay_type,
- 'order_no' => $order->order_no,
- 'out_trade_no' => $order->out_trade_no,
- 'transaction_id' => $order->transaction_id,
- 'remark' => '订单退款'
- ];
- $refundResult = $paymentService->refund($refundData, 'store');
- if (!$refundResult) {
- DB::rollBack();
- return ['code' => 1, 'msg' => '退款失败:' . $paymentService->getError() ?: '退款失败'];
- }
- // 更新订单状态
- $updateData = [
- 'refund_status' => 1, // 已退款
- 'refund_amount' => $refundAmount,
- 'update_time' => time()
- ];
- $result = $this->model->where('id', $id)->update($updateData);
- if ($result) {
- DB::commit();
- ActionLogModel::setTitle("确认退款");
- ActionLogModel::record();
- RedisService::keyDel("caches:orders:*");
- return ['code' => 0, 'msg' => '退款成功'];
- }
- DB::rollBack();
- return ['code' => 1, 'msg' => '更新订单状态失败'];
- } catch (\Exception $e) {
- DB::rollBack();
- return ['code' => 1, 'msg' => '退款失败:' . $e->getMessage()];
- }
- }
- /**
- * 拒绝退款
- */
- public function rejectRefund()
- {
- $id = request()->post('id');
- $refundRemark = request()->post('refund_remark', '');
- if (!$id) {
- return ['code' => 1, 'msg' => '参数错误'];
- }
- if (!$refundRemark) {
- return ['code' => 1, 'msg' => '请填写拒绝原因'];
- }
- $order = $this->model->find($id);
- if (!$order) {
- return ['code' => 1, 'msg' => '订单不存在'];
- }
- if ($order->refund_status != 3) {
- return ['code' => 1, 'msg' => '该订单未申请退款或已处理'];
- }
- $updateData = [
- 'refund_status' => 4, // 审核驳回
- 'refund_remark' => $refundRemark,
- 'update_time' => time()
- ];
- $result = $this->model->where('id', $id)->update($updateData);
- if ($result) {
- ActionLogModel::setTitle("拒绝退款");
- ActionLogModel::record();
- RedisService::keyDel("caches:orders:*");
- return ['code' => 0, 'msg' => '已拒绝退款'];
- }
- return ['code' => 1, 'msg' => '操作失败'];
- }
- /**
- * 订单统计
- * @param int $storeId 商户ID,0表示平台管理员查看全部数据
- */
- public function getStatistics($storeId = 0)
- {
- // 总订单数
- $params = request()->all();
- $userId = isset($params['user_id'])?$params['user_id']:0;
- $where = ['user_id'=>$userId,'mark'=>1];
- if($userId<=0){
- unset($where['user_id']);
- }
- $total = $this->model->where($where)
- ->when($storeId > 0, function ($query) use ($storeId) {
- return $query->where('store_id', $storeId);
- })
- ->count();
- // 总交易额(已完成订单)
- $totalAmount = $this->model->where($where)
- ->where('status', 4)
- ->when($storeId > 0, function ($query) use ($storeId) {
- return $query->where('store_id', $storeId);
- })
- ->sum('pay_total');
- // 待处理订单(待付款 + 已付款)
- $pending = $this->model->where($where)
- ->whereIn('status', [1, 2])
- ->when($storeId > 0, function ($query) use ($storeId) {
- return $query->where('store_id', $storeId);
- })
- ->count();
- // 待退款订单
- $refunding = $this->model->where($where)
- ->where('refund_status', 3)
- ->when($storeId > 0, function ($query) use ($storeId) {
- return $query->where('store_id', $storeId);
- })
- ->count();
- return [
- 'code' => 0,
- 'msg' => '操作成功',
- 'data' => [
- 'total' => $total,
- 'totalAmount' => number_format($totalAmount, 2, '.', ''),
- 'pending' => $pending,
- 'refunding' => $refunding
- ]
- ];
- }
- /**
- * 导出订单数据
- */
- public function exportData($params)
- {
- $query = $this->model->where('mark', 1);
- // 店铺筛选
- if (isset($params['store_id']) && $params['store_id'] > 0) {
- $query->where('store_id', $params['store_id']);
- }
- // 用户筛选
- if (isset($params['user_id']) && $params['user_id'] > 0) {
- $query->where('user_id', $params['user_id']);
- }
- // 状态筛选
- if (isset($params['status']) && $params['status'] > 0) {
- $query->where('status', $params['status']);
- }
- // 售后类型筛选
- if (isset($params['after_type']) && $params['after_type'] > 0) {
- $query->where('after_type', $params['after_type']);
- }
- // 退款状态筛选
- if (isset($params['refund_status']) && $params['refund_status'] > 0) {
- $query->where('refund_status', $params['refund_status']);
- }
- // 关键词搜索
- if (isset($params['keyword']) && $params['keyword']) {
- $keyword = $params['keyword'];
- $query->where(function ($q) use ($keyword) {
- $q->where('order_no', 'like', '%' . $keyword . '%')
- ->orWhere('receiver_name', 'like', '%' . $keyword . '%')
- ->orWhere('receiver_mobile', 'like', '%' . $keyword . '%');
- });
- }
- $list = $query->with(['user', 'orderGoods', 'store'])
- ->orderBy('create_time', 'desc')
- ->limit(5000)
- ->get();
- if (!$list || $list->isEmpty()) {
- return response()->json(['code' => 1, 'msg' => '没有可导出的数据']);
- }
- // 状态映射
- $statusMap = [1 => '待付款', 2 => '已付款', 3 => '已发货', 4 => '已完成', 9 => '已取消'];
- $refundStatusMap = [0 => '无', 1 => '已退款', 2 => '已审核', 3 => '待审核'];
- // 构建导出数据
- $data = [];
- foreach ($list as $item) {
- $goodsNames = [];
- if ($item->orderGoods) {
- foreach ($item->orderGoods as $goods) {
- $goodsNames[] = $goods->goods_name . ' x' . $goods->num;
- }
- }
- $data[] = [
- $item->order_no,
- $item->user->nickname ?? '',
- $item->user->mobile ?? '',
- implode(';', $goodsNames),
- $item->total ?? 0,
- $item->pay_total ?? 0,
- $statusMap[$item->status] ?? '未知',
- $refundStatusMap[$item->refund_status] ?? '无',
- $item->receiver_name ?? '',
- $item->receiver_mobile ?? '',
- $item->receiver_address ?? '',
- $item->create_time ? date('Y-m-d H:i:s', strtotime($item->create_time)) : '',
- ];
- }
- $headings = ['订单号', '用户昵称', '用户手机', '商品信息', '订单金额', '实付金额', '订单状态', '退款状态', '收货人', '收货电话', '收货地址', '下单时间'];
- $export = new \App\Exports\Export($data, $headings, '订单列表');
- $filename = '订单列表_' . date('YmdHis') . '.xlsx';
- return \Maatwebsite\Excel\Facades\Excel::download($export, $filename);
- }
- }
|