love_php/app/Http/Controllers/Server/Admin/OrderController.php
2026-04-02 12:01:59 +08:00

2127 lines
95 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Http\Controllers\Server\Admin;
use App\Jobs\SendEarningMessageV2;
use App\Jobs\SyncTask;
use App\Models\Course\UserCourses;
use App\Models\MAdvanceEarning;
use App\Models\MerchantInfo;
use App\Models\Message;
use App\Models\SaasReservationConsultScheduling;
use App\Models\Server\MerchantService;
use App\Models\Server\OrderStatusLink;
use App\Models\Server\SaasMemberLevel;
use App\Models\Server\ServiceOrderOperation;
use App\Models\Server\ServiceOrderRole;
use App\Models\Server\ServiceRoleAdmin;
use App\Models\Server\WechatSubMerchant;
use App\Services\WechatService;
use App\Utils\Http;
use App\Utils\Messenger as Messengers;
use Illuminate\Container\Container as App;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Jobs\SendTemplateMsg;
use App\Models\ClientComment;
use App\Models\CommunityActivity;
use App\Models\ConsultAccount;
use App\Models\Consultation;
use App\Models\ConsultationRecords;
use App\Models\Course\Course;
use App\Models\Wechat;
use App\Models\Live\Anchor;
use App\Models\MerchantShop;
use App\Models\MerchantUsers;
use App\Models\RefundOrder;
use App\Models\Score\CashoutLog;
use App\Models\Server\MEarning;
use App\Models\Server\MEarningAccount;
use App\Models\Server\MerchantAccount;
use App\Models\Server\MerchantAdmins;
use App\Models\Server\MerchantUser;
use App\Models\Server\MerchantInformation;
use App\Models\Server\MerchantMembers;
use App\Models\Server\MOrderFollow;
use App\Models\Server\MRefundOrder;
use App\Models\Server\TouristOrder as Order;
use App\Models\Server\TouristOrder;
use App\Models\ShopRecive;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Repositories\Eloquent\SmsRepository as Sms;
use Log;
class OrderController extends Controller
{
//订单控制器
/**
* 订单
* @param Request $request
* @return JsonResponse|string
*/
public function platOrders(Request $request)
{
try {
$nopage = $request->input('nopage', 1);
$account_id = $request->account_id;
$account = MerchantAccount::where('id', $account_id)
->first();
$anchor = Anchor::where('m_id', $account->id)
->first();
// if(empty($anchor)) return $this->failure('获取列表失败,请联系开发人员');
if ($anchor) {
//我的社群服务id
$community_ids = CommunityActivity::withTrashed()
->where('anchor_id', $anchor->id)
->where('type', 'business')->where('class', 'many')
->pluck('id')
->toArray();
//我的社群活动id
$activity_ids = CommunityActivity::withTrashed()
->where('anchor_id', $anchor->id)
->where('type', 'business')->where('class', 'one')
->pluck('id')
->toArray();
//我的课程id
if (!$anchor->openid)
$anchor->openid = 'business';//未完善信息商户无数据
// $course_ids = Course::where('open_id',$anchor->openid)->where('type','business')->pluck('id')->toArray();
} else {
$community_ids = CommunityActivity::withTrashed()
->where('merchant_id', $account_id)
->where('type', 'business')->where('class', 'many')
->pluck('id')
->toArray();
//我的社群活动id
$activity_ids = CommunityActivity::withTrashed()
->where('merchant_id', $account_id)
->where('type', 'business')->where('class', 'one')
->pluck('id')
->toArray();
// $course_ids = Course::where('merchant_id',$account_id)->where('type','business')->pluck('id')->toArray();
}
if ($account_id == 88) {//袁大同
$course_ids = Course::withTrashed()
->where('merchant_id', $account_id)
->pluck('id')
->toArray();
} else {
$course_ids = Course::withTrashed()
->where('merchant_id', $account_id)
->where('type', 'business')
->pluck('id')
->toArray();
}
//我的咨询服务id
$consult_ids = ConsultAccount::where('merchant_id', $request->account_id)
->pluck('id')
->toArray();
$consult_ids = Consultation::withTrashed()
->whereIn('consult_account_id', $consult_ids)
->pluck('id')
->toArray();
//我的商品id
$shop_ids = MerchantShop::withTrashed()
->where('merchant_id', $request->account_id)
->pluck('id')
->toArray();
//我的所有活动和课程id
// $arr_all = array_merge($community_ids,$course_ids);
$type = $request->input('type');
$orders = Order::with('viewer:avatar,mobile,openid,sex,nickname', 'fromUser:avatar,mobile,openid,sex,nickname', 'merUser', 'alliance')
->withCount('follow');
if ($type == 'community') { //服务
$orders = $orders->where('type', $type)
->whereIn('type_id', $community_ids);
} elseif ($type == 'course') {//课程
$orders = $orders->where('type', $type)
->whereIn('type_id', $course_ids);
} elseif ($type == 'activity') {//活动
$orders = $orders->where('type', 'community')
->whereIn('type_id', $activity_ids);
} elseif ($type == 'shop') {
$orders = $orders->where('type', 'shop')
->whereIn('type_id', $shop_ids);
} elseif ($type == 'consult') {
$orders = $orders->where('type', 'consult')
->whereIn('type_id', $consult_ids);
} else {//总的
// dd($community_ids,$course_ids,$activity_ids,$shop_ids,$consult_ids);
$orders = $orders->where(function ($sql) use ($community_ids, $course_ids, $activity_ids, $shop_ids, $consult_ids) {
$sql->where('type', 'community')
->whereIn('type_id', $community_ids)
->orWhere('type', 'course')
->whereIn('type_id', $course_ids)
->orWhere('type', 'community')
->whereIn('type_id', $activity_ids)
->orWhere('type', 'shop')
->whereIn('type_id', $shop_ids)
->orWhere('type', 'consult')
->whereIn('type_id', $consult_ids);
});
}
$pay_status = $request->input('pay_status', 'all');
if ($pay_status == 1) { //已支付 已到账
$orders = $orders->whereIn('pay_status', [1, 4]);
} elseif ($pay_status == 'all') { //所有
$orders = $orders->whereIn('pay_status', [0, 1, 3, 4]);
} else {//034未支付 已退款 已到账
$orders = $orders->where('pay_status', $pay_status);
}
$keyword = $request->input('keyword');
if ($keyword) {
$keyword = trim($keyword);
$orders = $orders->where(function ($sql) use ($keyword) {
$sql->where('name', 'like', '%' . $keyword . '%')
->orWhere('mobile', 'like', '%' . $keyword . '%')
->orWhere('desc', 'like', '%' . $keyword . '%');
});
}
$paid_count = 0;
$paid_count = $orders->sum('price');
if ($nopage) {
$orders = $orders->orderBy('created_at', 'desc')
->paginate();
} else {
$orders = $orders->orderBy('created_at', 'desc')
->get();
}
// $can_withdraw_total = 0; //总收益
foreach ($orders as $key => $order) {
if ($order->mobile == '未获取') {
if ($order->open_id) {
$mobile = MerchantUser::where('openid', $order->open_id)->value('mobile');
if ($mobile) {
$orders[$key]['mobile'] = $mobile;
}
}
}
if ($order->created_at < '2022-3-21 18:00') {
$temp_sku = explode('-', $order->desc);
if (is_array($temp_sku) && count($temp_sku) >= 2) {
$order->goods = $temp_sku[1];
}
}
$max_refund = $this->getMaxRefund($order->trade_no);
$max_refund = number_format($max_refund, 2, '.', '');
$order->max_refund = $max_refund;
if ($order->type == 'community') {
$activity = CommunityActivity::withTrashed()
->where('id', $order->type_id)
->first();
if ($activity->class == 'one') {
if ($order->linkmen && $order->linkmen != 'null')
$order->linkmen = json_decode($order->linkmen);
/**
* $goods = CommunityActivityResource::withTrashed()
* ->where('id', $order->type_id)
* ->where('class', 'one')
* ->value('title');
* $order->goods = $goods;
* */
} elseif ($activity->class == 'many') {
/**
* $goods = CommunityActivityResource::withTrashed()
* ->where('id', $order->type_id)
* ->where('class', 'many')
* ->value('title');
* $order->goods = $goods;
* **/
}
}
if ($order->type == 'course') {
/**
* $goods = Course::withTrashed()
* ->where('id', $order->type_id)
* ->value('title');
* $order->goods = $goods;
* **/
$s_member = UserCourses::where('trade_no', $order->trade_no)
->first();
$order->s_member = $s_member;
}
if ($order->type == 'shop') {
/**
* $goods = MerchantShop::withTrashed()
* ->where('id', $order->type_id)
* ->value('title');
* $order->goods = $goods;
* **/
$addres = ShopRecive::where('order_id', $order->id)
->value('address');
$order->address = $addres;
}
if ($order->channel == '福恋小程序') {
$wechat = Wechat::where('openid', $order->open_id)
->first();
if ($wechat) {
$user = User::where('id', $wechat->user_id)
->first();
if ($user) {
$userinfo['nickname'] = $user->nickname;
$userinfo['pic'] = $user->photo ?: $user->circle_avatar;
$order->merchant_user = $userinfo;
}
}
} else {
$rand_str = $this->randString(8);
$nickname = '用户' . $rand_str;
if ($order->mobile && !($order->mobile == '匿名用户' || $order->mobile == '未获取')) {
$user = User::where('mobile', $order->mobile)
->select('nickname', 'circle_avatar as pic')
->first();
if ($user && ($user->nickname || $user->pic)) {
$order->merchant_user = $user;
} else {
$userinfo['pic'] = User::DefaultAvatar;
$userinfo['nickname'] = $nickname;
$order->merchant_user = $userinfo;
}
} elseif ($order->open_id) {
$wechat = Wechat::where('official_openid', $order->open_id)
->select('user_id', 'nickname', 'avatar as pic')
->first();
if ($wechat && ($wechat->nickname || $wechat->pic)) {
$order->merchant_user = $wechat;
} elseif ($wechat && $wechat->user_id) {
$user = User::where('id', $wechat->user_id)
->select('nickname', 'circle_avatar as pic')
->first();
if ($user && ($user->nickname || $user->pic)) {
$order->merchant_user = $user;
} else {
$userinfo['pic'] = User::DefaultAvatar;
$userinfo['nickname'] = $nickname;
$order->merchant_user = $userinfo;
}
} else {
$userinfo['pic'] = User::DefaultAvatar;
$userinfo['nickname'] = $nickname;
$order->merchant_user = $userinfo;
}
} else {
$userinfo['pic'] = User::DefaultAvatar;
$userinfo['nickname'] = $nickname;
$order->merchant_user = $userinfo;
}
}
if ($order->mobile == '匿名用户' || $order->mobile == '未获取') {
$order->mobile = null;
}
if (isset($order['merUser']['pic']) && $order['merUser']['pic'] == null) {
$order['merUser']['pic'] = User::DefaultAvatar;
}
if (isset($order['merUser']['nickname']) && $order['merUser']['nickname'] == null) {
$order['merUser']['nickname'] = '未获取';
}
$order->can_withdraw_count = ($order->price) * ($order->withdrawal_radio / 100);
$order->can_withdraw_count = number_format($order->can_withdraw_count, 2);
$order->registered_income = 0;
if ($account->registered_income >= 1)
$order->registered_income = ($order->price * $account->registered_income) / 100;
$order->pay_income = 0;
if ($account->pay_income >= 1)
$order->pay_income = ($order->price * $account->pay_income) / 100;
// $can_withdraw_total = $can_withdraw_total+$order->can_withdraw_count;
if (!empty($order->remark) && $order->remark != 'null')
$order->remark = json_decode($order->remark, true);
}
// $can_withdraw_total = $this->totalIncome($community_ids,$course_ids,$activity_ids,$consult_ids,$shop_ids,$request->account_id);//总收益
$can_cash_out_amount = $this->canCashoutMoney($community_ids, $course_ids, $activity_ids, $consult_ids, $shop_ids, $account->id);//可提现
$can_cash_out_amount = number_format($can_cash_out_amount, 2) ?? 0;
// $can_withdraw_total = number_format($can_withdraw_total,2);//总收益
// $used_withdraw_total = number_format($can_withdraw_total-$can_cash_out_amount,2);//已提现
//微信提现
$wechat_cash_out_amount = CashoutLog::where('status', 2)
->where('type', 'wechat')
->where('merchant_id', $account_id)
->sum('amount');
//支付宝提现
$ali_cash_out_amount = CashoutLog::where('status', 2)
->where('type', 'alipay')
->where('merchant_id', $account_id)
->sum('amount');
//计算已提现金额 has_cash_out_amount
$used_withdraw_total = $wechat_cash_out_amount + $ali_cash_out_amount;
return $this->success('ok', compact('orders', 'used_withdraw_total', 'can_cash_out_amount', 'account', 'paid_count'));
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息中,请稍后再试');
}
}
public function getMaxRefund($trade_no)
{
try {
$max_price = 0;
$has_refund = 0;
$order = Order::where('trade_no', $trade_no)->first();
if (!$order || $order->pay_status == 0 || $order->pay_status == 3)
return 0;
if ($order->pay_status == 4) { //收益已到账 退商家收益
//生成收益时间
$created_at = MEarning::where('m_order_id', $order->id)->value('created_at');
if ($created_at) {
$has_refund = MRefundOrder::where('trade_no', $trade_no)->where('is_hook', 1)->where('created_at', '>', $created_at)->sum('refund_fee');
}
$value = MEarning::where('m_order_id', $order->id)->where('m_user_id', 0)->sum('value');
$max_price = $value - $has_refund;
} else {
//已经退款金额 收益冻结(钱没分出去) 可退全款
$has_refund = MRefundOrder::where('trade_no', $trade_no)->where('is_hook', 1)->sum('refund_fee');
$max_price = $order->price - $has_refund;
}
if ($max_price < 0)
return 0;
return $max_price;
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息了,请稍后再试');
}
}
/**
* 商城商品订单
* @param Request $request
* @return JsonResponse|string
*/
public function shopOrders(Request $request)
{
try {
$merchant_id = $request->account_id;
$pay_status = $request->pay_status ?? 2;
$order_status = $request->order_status ?? 0;
$keyword = $request->keyword;
$nopage = $request->nopage ?? 1;
//我的商品id
if (isset($request->shop_id) && $request->shop_id) {
$shop_ids = [$request->shop_id];
} else {
$shop_ids = MerchantShop::withTrashed()
->where('merchant_id', $merchant_id)
->pluck('id')
->toArray();
}
$orders = Order::with('merUser', 'recive', 'alliance', 'mEarning:id,m_user_id,m_order_id,sharer,ratio,sub_ratio,value', 'mAdvanceEarning:id,m_user_id,m_order_id,sharer,ratio,sub_ratio,value', 'mEarning.user:id,pic,nickname,mobile', 'mAdvanceEarning.user:id,pic,nickname,mobile')
->withCount('follow')
->where('merchant_id', $merchant_id)
->where('type', 'shop')
->whereIn('type_id', $shop_ids);
if ($pay_status != 2) {
if ($pay_status == 1) {
$orders = $orders->whereIn('pay_status', [1, 4]);
} else {
$orders = $orders->where('pay_status', $pay_status);
}
}
if ($order_status) {
$orders = $orders->whereHas('recive', function ($query) use ($order_status) {
$query->where('order_status', $order_status);
});
}
if ($keyword) {
$keyword = trim($keyword);
$orders = $orders->where(function ($sql) use ($keyword) {
$sql->where('name', 'like', '%' . $keyword . '%')
->orWhere('mobile', 'like', '%' . $keyword . '%')
->orWhere('desc', 'like', '%' . $keyword . '%');
});
}
$paid_count = $orders->sum('price');
if ($nopage) {
$orders = $orders->orderBy('updated_at', 'desc')
->paginate();
} else {
$orders = $orders->orderBy('updated_at', 'desc')
->get();
}
$from_user_name = '';
$from_avatar = '';
foreach ($orders as $key => $order) {
if ($order->mobile == '匿名用户' || $order->mobile == '未获取') {
$order->mobile = null;
}
if ($order['merUser'] != null && $order['merUser']['pic'] == null) {
$order['merUser']['pic'] = User::DefaultAvatar;
}
if ($order['merUser'] != null && $order['merUser']['nickname'] == null) {
$order['merUser']['nickname'] = '未获取';
}
$order->address = ShopRecive::where('order_id', $order->id)
->value('address');
$order->sku_name = $order->goods;
$order->goods = MerchantShop::withTrashed()
->where('id', $order->type_id)
->value('title');
$order->photo = MerchantShop::withTrashed()
->where('id', $order->type_id)
->value('icon');
$order->from_user_name = $from_user_name;
$order->from_user_avatar = $from_avatar;
$order->paid_count = $paid_count;
if ($order->from_openid && $order->from_openid != 'null') {
$order->from_user_name = MerchantUser::where('openid', $order->from_openid)
->value('nickname');
$order->from_user_avatar = MerchantUser::where('openid', $order->from_openid)
->value('pic');
}
if ($order->remark && $order->remark != 'null') {
$order->remark = json_decode($order->remark, true) ?? [];
}
if ($order->linkmen && $order->linkmen != 'null') {
$order->linkmen = json_decode($order->linkmen, true) ?? [];
}
}
return $this->success('ok', $orders);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息中,请稍后再试');
}
}
/**
* 商品订单详情
* @param Request $request
* @param $id
* @return JsonResponse|string
*/
public function shopOrder(Request $request, $id)
{
try {
$order = Order::where('id', $id)
->first();
$recive = ShopRecive::where('order_id', $order->id)
->first();
$shop = MerchantShop::withTrashed()
->where('id', $order->type_id)
->first();
if (empty($recive) || empty($shop)) {
return $this->failure('订单不存在或已被删除');
}
$order->address = $recive->address;
$order->title = $shop->title;
$order->icon = $shop->icon;
if ($order->banners) {
$order->banners = json_decode($shop->banners) ?? [];
}
if ($order->remark) {
$order->remark = json_decode($shop->remark) ?? [];
}
$order->describe = $shop->describe;
return $this->success('ok', $order);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('获取订单详情失败,请稍后再试');
}
}
/**
* 咨询订单
* @param Request $request
* @return JsonResponse|string
*/
public function consultOrders(Request $request)
{
try {
$merchant_id = $request->account_id;
$status = $request->status ?? 3;
$pay_status = $request->pay_status ?? 2;
$keyword = $request->keyword;
$comment = $request->comment;
$nopage = $request->nopage ?? 1;
$records = ConsultationRecords::with('consulation', 'consulation.teacher')
->where('merchant_id', $merchant_id);
$consulation_id = $request->consulation_id;
if ($status != 3) {
$records = $records->where('status', $status);
}
if ($pay_status != 2) {
// $records = $records->where('pay_status', $pay_status);
if ($pay_status == 1) {
$records = $records->whereHas('torder', function ($query) use ($status) {
$query->whereIn('pay_status', [1, 4]);
});
} else {
$records = $records->whereHas('torder', function ($query) use ($pay_status) {
$query->where('pay_status', $pay_status);
});
}
}
if ($comment == 'comment') {
$records = $records->whereNotNull('comment')
->where('comment', '<>', '');
}
if ($consulation_id) {
$records = $records->where('consulation_id', $consulation_id);
}
if ($keyword) {
$keyword = trim($keyword);
$consult_ids = Consultation::where('title', 'like', '%' . $keyword . '%')
->pluck('id');
$records = $records->where(function ($sql) use ($keyword, $consult_ids) {
$sql->where('name', 'like', '%' . $keyword . '%')
->orWhere('phone', 'like', '%' . $keyword . '%')
->orWhereIn('consulation_id', $consult_ids);
});
}
$paid_count = $records->sum('price');
if ($nopage) {
$records = $records->orderBy('id', 'desc')
->paginate();
} else {
$records = $records->orderBy('id', 'desc')
->get();
}
foreach ($records as $value) {
$follow_count = MOrderFollow::where('order_id', $value->id)->count();
$value->follow_count = $follow_count;
if ($value->phone == '匿名用户' || $value->phone == '未获取') {
$value->phone = null;
}
if ($value->torder) {
$value->pay_status = $value->torder->pay_status;
}
//$value->channel = TouristOrder::where('trade_no',$value->trade_no)->value('channel');
$order = TouristOrder::with('alliance')
->where('trade_no', $value->trade_no)
->first();
$value->channel = $order->channel ?? 0;
$value->alliance = $order->alliance ?? null;
$merchant_user = MerchantUsers::where('id', $value->merchant_user_id)
->select('openid', 'pic', 'mobile', 'sex', 'nickname')
->first();
$value->openid = $merchant_user ? ($merchant_user->openid ?: '') : '';
$value->mer_user = $merchant_user;
if ($value['mer_user'] != null && $value['mer_user']['pic'] == null) {
$value['mer_user']['pic'] = User::DefaultAvatar;
}
if ($value['mer_user'] != null && $value['mer_user']['nickname'] == null) {
$value['mer_user']['nickname'] = '未获取';
}
$value->teacher_name = '未获取';
if (isset($value->consulation->teacher)) {
$value->teacher_name = $value->consulation->teacher->name;
}
$value->title = Consultation::withTrashed()
->where('id', $value->consulation_id)
->value('title');
if (!empty($value->remark) && $value->remark != 'null') {
$value->remark = json_decode($value->remark, true);
}
unset($value->consulation);
$value->paid_count = $paid_count;
if ($value->scheduling_id && empty($value->reservation_time)) {
$scheduling = SaasReservationConsultScheduling::find($value->scheduling_id);
$value->reservation_time = "{$scheduling->date} {$scheduling->date_range}";
}
}
return $this->success('ok', $records);
} catch (\Exception $e) {
DB::rollBack();
$this->getError($e);
return $this->failure('服务器休息,请稍后再试');
}
}
/**
* 订单数据统计
* @param Request $request
* @return JsonResponse|string
*/
public function weekOrdersStat(Request $request)
{
try {
$course_id = $request->course_id;//课程id
$community_id = $request->community_id;//社群id
$consulation_id = $request->consulation_id;
$shop_id = $request->shop_id;
$type = $request->type;
$week_consume_user_count = 0;//一周消费人数
$week_consume_cash_amount = 0;//一周支付金额
if ($request->start_time && $request->end_time) {
$start_time = $request->start_time;
$end_time = $request->end_time;
//间隔天数
$between_time = ceil((strtotime($end_time) - strtotime($start_time)) / 3600 / 24) + 1;
for ($i = 0; $i < $between_time; $i++) {
$date[] = date("Y-m-d", strtotime("+$i day", strtotime($start_time)));
}
}
if ($type == 'course') {
foreach ($date as $start_time) {
$date_arr[] = $start_time;
$start_time = $start_time . ' 00:00:00';
$end_time = date("Y-m-d 23:59:59", strtotime($start_time));
$week_consume_user_count = Order::where('type', 'course')
->where('type_id', $course_id)->whereIn('pay_status', [1, 4])
->whereBetween('created_at', [$start_time, $end_time])
->count();
$consume_user_count[] = $week_consume_user_count;
$week_consume_cash_amount = Order::where('type', 'course')
->where('type_id', $course_id)->whereIn('pay_status', [1, 4])
->whereBetween('created_at', [$start_time, $end_time])
->sum('price');
$consume_cash_amount[] = $week_consume_cash_amount;
}
} elseif ($type == 'activity') {
foreach ($date as $start_time) {
$date_arr[] = $start_time;
$start_time = $start_time . ' 00:00:00';
$end_time = date("Y-m-d 23:59:59", strtotime($start_time));
$week_consume_user_count = Order::where('type', 'community')
->where('type_id', $community_id)
->whereIn('pay_status', [1, 4])
->whereBetween('created_at', [$start_time, $end_time])
->count();
$consume_user_count[] = $week_consume_user_count;
$week_consume_cash_amount = Order::where('type', 'community')
->where('type_id', $community_id)
->whereIn('pay_status', [1, 4])
->whereBetween('created_at', [$start_time, $end_time])
->sum('price');
$consume_cash_amount[] = $week_consume_cash_amount;
}
} elseif ($type == 'consulation') {
foreach ($date as $start_time) {
$date_arr[] = $start_time;
$start_time = $start_time . ' 00:00:00';
$end_time = date("Y-m-d 23:59:59", strtotime($start_time));
$week_consume_user_count = ConsultationRecords::where('consulation_id', $consulation_id)
->whereIn('pay_status', [1, 4])
->whereBetween('created_at', [$start_time, $end_time])
->count();
$consume_user_count[] = $week_consume_user_count;
$week_consume_cash_amount = ConsultationRecords::where('consulation_id', $consulation_id)
->whereIn('pay_status', [1, 4])
->whereBetween('created_at', [$start_time, $end_time])
->sum('price');
$consume_cash_amount[] = $week_consume_cash_amount;
}
} elseif ($type == 'shop') {
foreach ($date as $start_time) {
$date_arr[] = $start_time;
$start_time = $start_time . ' 00:00:00';
$end_time = date("Y-m-d 23:59:59", strtotime($start_time));
$week_consume_user_count = Order::where('type', 'shop')
->where('type_id', $shop_id)
->whereIn('pay_status', [1, 4])
->whereBetween('created_at', [$start_time, $end_time])
->count();
$consume_user_count[] = $week_consume_user_count;
$week_consume_cash_amount = Order::where('type', 'shop')
->where('type_id', $shop_id)
->whereIn('pay_status', [1, 4])
->whereBetween('created_at', [$start_time, $end_time])
->sum('price');
$consume_cash_amount[] = $week_consume_cash_amount;
}
}
return $this->success('ok', compact('date_arr', 'consume_user_count', 'consume_cash_amount'));
} catch (\Exception $e) {
DB::rollBack();
$this->getError($e);
return $this->failure('服务器休息,请稍后再试');
}
}
/**
* 订单详情
* @param Request $request
* @param $id
* @return JsonResponse|string
*/
public function order(Request $request, $id)
{
try {
if ($request->type == 'consulation') {
$record = ConsultationRecords::where('id', $id)
->first();
$record->title = Consultation::withTrashed()
->where('id', $record->consulation_id)
->value('title');
$record->mobile = $record->phone;
}
if ($request->type == 'service') {
$record = Order::where('id', $id)
->first();
$record->title = CommunityActivity::withTrashed()
->where('id', $record->type_id)
->value('title');
}
if ($request->type == 'activity') {
$record = Order::where('id', $id)
->first();
$record->title = CommunityActivity::withTrashed()
->where('id', $record->type_id)
->value('title');
}
if ($request->type == 'course') {
$record = Order::where('id', $id)
->first();
$record->title = Course::withTrashed()
->where('id', $record->type_id)
->value('title');
}
if ($record->remark && $record->remark != 'null') {
$record->remark = json_decode($record->remark, true);
}
$fol = MOrderFollow::where('order_id', $record->id)->where('result', '订单状态修改')->first();
$is_start = !empty($fol) ? $fol->is_start : 0;
$record->is_start = $is_start;
return $this->success('ok', $record);
} catch (\Exception $e) {
DB::rollBack();
$this->getError($e);
return $this->failure('服务器休息,请稍后再试');
}
}
//统一订单跟进表
/**
* 订单增加徽标数
* @param Request $request
* @return JsonResponse|string
*/
public function newPlatNotice(Request $request)
{
try {
$account_id = $request->account_id;
$account = MerchantAccount::where('id', $account_id)->first();
$anchor = Anchor::where('m_id', $account->id)->first();
$service_ids = CommunityActivity::where('merchant_id', $account_id)->where('type', 'business')
->where('class', 'many')->pluck('id')
->toArray();
$market_service_ids = MerchantService::where('merchant_services.merchant_id', $account_id)
->join('community_activities', function ($join) use ($request) {
$join->on('community_activities.id', '=', 'merchant_services.type_id')
->where('community_activities.class', 'many');
}, null, null, 'right')
->where('merchant_services.type', 'community')
->where('merchant_services.service_type', 1)
->pluck('merchant_services.type_id')
->toArray();
$activity_ids = CommunityActivity::where('anchor_id', $anchor->id)->where('type', 'business')
->where('class', 'one')->pluck('id')
->toArray();
$market_activity_ids = MerchantService::where('merchant_services.merchant_id', $account_id)
->join('community_activities', function ($join) use ($request) {
$join->on('community_activities.id', '=', 'merchant_services.type_id')
->where('community_activities.class', 'one');
}, null, null, 'right')
->where('merchant_services.type', 'community')
->where('merchant_services.service_type', 1)
->pluck('merchant_services.type_id')
->toArray();
//已经跟进的订单id
$follow_order_ids = MOrderFollow::pluck('id')->toArray();
//未跟进订单数量
$course_count = TouristOrder::where('merchant_id', $account_id)->where('type', 'course')
->whereNotIn('id', $follow_order_ids)
->count();
$shop_count = TouristOrder::where('merchant_id', $account_id)->where('pay_status', '<>', 0)
->where('type', 'shop')->whereNotIn('id', $follow_order_ids)
->count();
$evaluate_count = TouristOrder::where('merchant_id', $account_id)->where('type', 'evaluate')
->whereNotIn('id', $follow_order_ids)
->count();
$activity_count = TouristOrder::where('type', 'community')
->where(function ($query) use ($activity_ids, $market_activity_ids, $account_id) {
$query->whereIn('type_id', $activity_ids);
if ($market_activity_ids) {
$query->orwhere(function ($orWhereQuery) use ($market_activity_ids, $account_id) {
$orWhereQuery->whereIn('type_id', $market_activity_ids)->where('merchant_id', $account_id);
});
}
})
->whereNotIn('id', $follow_order_ids)
->count();
$service_count = TouristOrder::where('type', 'community')
->where(function ($query) use ($service_ids, $market_service_ids, $account_id) {
$query->whereIn('type_id', $service_ids);
if ($market_service_ids) {
$query->orwhere(function ($orWhereQuery) use ($market_service_ids, $account_id) {
$orWhereQuery->whereIn('type_id', $market_service_ids)->where('merchant_id', $account_id);
});
}
})
->whereNotIn('id', $follow_order_ids)
->count();
$consulation_count = TouristOrder::where('merchant_id', $account_id)->where('type', 'consult')
->whereNotIn('id', $follow_order_ids)
->count();
$data['activity_count'] = $activity_count;
$data['service_count'] = $service_count;
$data['consulation_count'] = $consulation_count;
$data['course_count'] = $course_count;
$data['shop_count'] = $shop_count;
$data['evaluate_count'] = $evaluate_count;
return $this->success('ok', $data);
} catch (\Exception $e) {
DB::rollBack();
$this->getError($e);
return $this->failure('服务器休息,请稍后再试');
}
}
//获取订单类型(中文)
public function orderFollow(Request $request, $order_id)
{
try {
$merchant_id = $request->account_id;
$admin_id = $request->merchant_admin_id;
if (!$admin_id) {
//return $this->failure('不支持用主帐号添加跟进,请命名用管理员帐号添加跟进记录');
}
// $order = TouristOrder::where('id', $order_id)->first();
// if (empty($order)) return $this->failure('未查询到该订单');
// $trade_no = ConsultationRecords::where('id',$order_id)->value('trade_no');
$order = TouristOrder::where('id', $order_id)->first();
if (empty($order))
return $this->failure('未查询到该订单');
DB::beginTransaction();
MOrderFollow::create([
'order_id' => $order_id,
'merchant_id' => $merchant_id,
'admin_id' => !empty($admin_id) ? $admin_id : 0,
'way' => $request->way,
'content' => $request->input('content'),
'photo' => !empty($request->photo) ? json_encode($request->photo) : null,
'result' => $request->result
]);
// $user_id = Wechat::where('openid',$order->open_id)->orWhere('official_openid',$order->open_id)->value('user_id');
// if(!$user_id) $user_id = MerchantUser::where('id',$order->account_id)->value('user_id');
$user_id = $this->matchFulinkUser($order->account_id);
$maker_user_id = 0;//福恋操作人id
$admin = !empty($admin_id) ? MerchantAdmins::find($admin_id) : MerchantAccount::find($merchant_id);
$maker_user_id = User::where('mobile', $admin->mobile)->value('id');
$maker_user_id = $maker_user_id ?? 0;
$result = $this->getOrderType($order);
$text = '订单类型:' . $result . ' 订单号:' . $order->trade_no;
if ($request->way)
$text = $text . ' 跟进方式:' . $request->way;
if ($request->input('content'))
$text = $text . ' 跟进内容:' . $request->input('content');
if ($request->result)
$text = $text . ' 跟进结果:' . $request->result;
if ($maker_user_id) {
$nickname = User::where('id', $maker_user_id)->value('nickname');
$text = $text . ' 跟进人【' . $nickname . '】';
}
//同步一条该订单用户的用户备注
if ($user_id) {
ClientComment::create([
'user_id' => $user_id,
'maker_user_id' => $maker_user_id,
'type' => 'mobile',
'comment' => $text,
'pics' => !empty($request->photo) ? json_encode($request->photo) : null,
]);
}
DB::commit();
return $this->success('ok');
} catch (\Exception $e) {
DB::rollBack();
$this->getError($e);
return $this->failure($e->getMessage());
}
}
//订单跟进列表
public function getOrderType($order)
{
try {
switch ($order->type) {
case 'consult':
$result = '咨询';
break;
case 'shop':
$result = '商品';
break;
case 'community':
$class = CommunityActivity::where('id', $order->type_id)->value('class');
$result = $class == 'many' ? '服务' : '活动';
break;
case 'course':
$result = '课程';
break;
case 'evaluate':
$result = '测评';
break;
default:
$result = '系统';
break;
}
return $result;
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息了,请稍后再试');
}
}
//同步之前的跟进
public function orderFollows(Request $request, $order_id)
{
try {
// $order = TouristOrder::where('id', $order_id)->first();
// if (empty($order)) return $this->failure('未查询到该订单debug--'.$order_id,$order);
$follows = MOrderFollow::where('order_id', $order_id)->orderBy('id', 'desc')->paginate();
foreach ($follows as $key => $value) {
$value->photo = json_decode($value->photo, true);
if ($value->admin_id == 0) {
$anchor = Anchor::where('m_id', $value->merchant_id)->first();
$user['pic'] = !empty($anchor) ? $anchor->pic : User::DefaultAvatar;
$user['name'] = !empty($anchor) ? $anchor->name : '未获取';
} else {
$member = MerchantMembers::where('mch_id', $value->merchant_id)->where('admin_id', $value->admin_id)->first();
$user['pic'] = !empty($member) ? $member->avatar : User::DefaultAvatar;
$user['name'] = !empty($member) ? $member->name : '未获取';
}
$value->user = $user;
}
return $this->success('ok', $follows);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('获取列表失败,请稍后再试');
}
}
public function synOrderFollow(Request $request)
{
try {
$orders = TouristOrder::whereNotNull('remark')->select('id', 'remark', 'merchant_id')->get();
foreach ($orders as $key => $order) {
$order->remark = json_decode($order->remark);
foreach ($order->remark as $key => $value) {
MOrderFollow::create([
'order_id' => $order->id,
'merchant_id' => $order->merchant_id,
'admin_id' => 0,
'way' => $value->chat_way,
'content' => $value->chat_content,
'result' => $value->chat_result,
'created_at' => $value->time
]);
}
}
return $this->success('ok', $orders);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息了,请稍后再试');
}
}
/**
* 打赏列表
* @param Request $request
* @return JsonResponse|string
*/
public function payRewardList(Request $request)
{
try {
$id = $request->id;
$keyword = $request->keyword;
$merchant_id = $request->account_id;
$result = Order::select('id', 'price', 'type_id', 'pay_type', 'comment', 'account_id', 'type', 'channel', 'created_at')
->where('merchant_id', $merchant_id)
->whereIn('pay_status', [1, 4])
->wherein('type', ['reward_info', 'reward_activity'])
->orderBy('id', 'desc');
if ($id)
$result = $result->where('type_id', $id);
if ($keyword) {
$result = $result->whereHas('user', function ($query) use ($keyword) {
$query->where('nickname', 'like', '%' . $keyword . '%');
})
->orWhereHas('information', function ($query) use ($keyword, $merchant_id) {
$query->where('merchant_id', $merchant_id);
$query->where('title', 'like', '%' . $keyword . '%');
});
}
$result = $result->orderBy('id', 'desc')
->paginate();
foreach ($result as $key => $value) {
// return $value->information;
# code...
$value->name = $value->user->nickname ?? '匿名用户';
if ($value->type == 'reward_info') {
$value->title = $value->information->title ?? '';
$value->pic = $value->information->pic ?? '';
} elseif ($value->type == 'reward_activity') {
$activity = CommunityActivity::withTrashed()
->select('id', 'title', 'pic')
->where('id', $value->type_id)
->first();
$value->title = $activity->title ?? '';
$value->pic = $activity->pic ?? '';
}
unset($value->user);
unset($value->information);
}
return $this->success('ok', $result);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息了,请稍后再试');
}
}
/**
* 文章 活动打赏列表
* @param Request $request
* @return JsonResponse|string
*/
public function payRewardDetail(Request $request)
{
try {
$merchant_id = $request->account_id;
$type = $request->type ?? 'reward_info';
$type_id = $request->type_id;
$keyword = $request->keyword;
$result = Order::with('merUser')
->where('merchant_id', $merchant_id)
->whereIn('pay_status', [1, 4])
->where('type', $type)
->where('type_id', $type_id);
if ($keyword) {
$result = $result->whereHas('user', function ($query) use ($keyword) {
$query->where('nickname', 'like', '%' . $keyword . '%');
})
->orWhereHas('information', function ($query) use ($keyword, $merchant_id) {
$query->where('merchant_id', $merchant_id);
$query->where('title', 'like', '%' . $keyword . '%');
});
}
$result = $result->orderBy('id', 'desc')
->paginate();
foreach ($result as $key => $value) {
// return $value->information;
# code...
if (isset($value['merUser']['pic']) && $value['merUser']['pic'] == null) {
$value['merUser']['pic'] = User::DefaultAvatar;
}
if (isset($value['merUser']['nickname']) && $value['merUser']['nickname'] == null) {
$value['merUser']['nickname'] = '未获取';
}
$value->name = $value->user->nickname ?? '未获取';
if ($value->type == 'reward_info') {
$value->title = $value->information->title ?? '';
$value->pic = $value->information->pic ?? '';
} elseif ($value->type == 'reward_activity') {
$activity = CommunityActivity::withTrashed()
->select('id', 'title', 'pic')
->where('id', $value->type_id)
->first();
$value->title = $activity->title ?? '';
$value->pic = $activity->pic ?? '';
}
unset($value->user);
unset($value->information);
}
return $this->success('ok', $result);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息了,请稍后再试');
}
}
/**
* 订单列表
* @param Request $request
* @return JsonResponse|string
*/
public function phoneOrders(Request $request)
{
try {
$account_id = $request->account_id;
$account = MerchantAccount::where('id', $account_id)
->first();
$anchor = Anchor::where('m_id', $account->id)
->first();
if ($anchor) {
//我的社群服务id::
$community_ids = CommunityActivity::withTrashed()
->where('anchor_id', $anchor->id)
->where('type', 'business')
->where('class', 'many')
->pluck('id')
->toArray();
//我的社群活动id
$activity_ids = CommunityActivity::withTrashed()
->where('anchor_id', $anchor->id)
->where('type', 'business')
->where('class', 'one')
->pluck('id')
->toArray();
//我的课程id
// if(!$anchor->openid) $anchor->openid='business';//未完善信息商户无数据
$course_ids = Course::where('open_id', $anchor->openid)
->where('type', 'business')
->pluck('id')
->toArray();
} else {
$community_ids = CommunityActivity::withTrashed()
->where('merchant_id', $account_id)
->where('type', 'business')
->where('class', 'many')
->pluck('id')
->toArray();
//我的社群活动id
$activity_ids = CommunityActivity::withTrashed()
->where('merchant_id', $account_id)
->where('type', 'business')
->where('class', 'one')
->pluck('id')
->toArray();
// $course_ids = Course::where('merchant_id',$account_id)->where('type','business')->pluck('id')->toArray();
}
$course_ids = Course::withTrashed()
->where('merchant_id', $account_id)
->where('type', 'business')
->pluck('id')
->toArray();
//我的咨询服务id
$consult_ids = ConsultAccount::where('merchant_id', $request->account_id)
->pluck('id')
->toArray();
$consult_ids = Consultation::withTrashed()
->whereIn('consult_account_id', $consult_ids)
->pluck('id')
->toArray();
//我的商品id
$shop_ids = MerchantShop::withTrashed()
->where('merchant_id', $request->account_id)
->pluck('id')
->toArray();
//我的所有活动和课程id
// $arr_all = array_merge($community_ids,$course_ids);
$type = $request->input('type');
$orders = Order::select('id', 'open_id', 'type', 'pay_status', 'type_id', 'price', 'account_id', 'trade_no', 'created_at');
if ($type == 'community') { //服务
$orders = $orders->where('type', $type)
->whereIn('type_id', $community_ids);
} elseif ($type == 'course') {//课程
$orders = $orders->where('type', $type)
->whereIn('type_id', $course_ids);
} elseif ($type == 'activity') {//活动
$orders = $orders->where('type', 'community')
->whereIn('type_id', $activity_ids);
} elseif ($type == 'shop') {
$orders = $orders->where('type', 'shop')
->whereIn('type_id', $shop_ids);
} elseif ($type == 'consult') {
$orders = $orders->where('type', 'consult')
->whereIn('type_id', $consult_ids);
} elseif ($type == 'member') {
$orders = $orders->where('type', 'member');
} else {//总的
// dd($community_ids,$course_ids,$activity_ids,$shop_ids,$consult_ids);
// $orders = $orders->where(function ($sql) use ($community_ids, $course_ids, $activity_ids, $shop_ids, $consult_ids) {
// $sql->where('type', 'community')
// ->whereIn('type_id', $community_ids)
// ->orWhere('type', 'course')
// ->whereIn('type_id', $course_ids)
// ->orWhere('type', 'community')
// ->whereIn('type_id', $activity_ids)
// ->orWhere('type', 'shop')
// ->whereIn('type_id', $shop_ids)
// ->orWhere('type', 'consult')
// ->whereIn('type_id', $consult_ids);
// });
$orders = $orders->where('merchant_id', $request->account_id);
}
$pay_status = $request->input('pay_status', 'all');
if ($pay_status == 1) { //已支付
$orders = $orders->whereIn('pay_status', [1, 3, 4]);
} elseif ($pay_status == 'all') { //已支付和未支付
$orders = $orders->whereIn('pay_status', [0, 1, 3, 4]);
} else {//未支付
$orders = $orders->where('pay_status', 0);
}
$keyword = $request->input('keyword');
if ($keyword) {
$keyword = trim($keyword);
$orders = $orders->where(function ($sql) use ($keyword) {
$sql->where('name', 'like', '%' . $keyword . '%')
->orWhere('mobile', 'like', '%' . $keyword . '%');
});
}
$orders = $orders->orderBy('created_at', 'desc')
->paginate();
$can_withdraw_total = 0; //总收益
foreach ($orders as $key => $order) {
$is_hide = 1;
if ($order->type == 'community') {
$activity = CommunityActivity::withTrashed()
->where('id', $order->type_id)
->first();
if ($activity->class == 'one') {
$goods = CommunityActivity::withTrashed()
->where('id', $order->type_id)
->where('class', 'one')
->value('title');
$text = $order->created_at . ' 购买了 《' . $goods . '》';
$order->goods = $text;
$order->type = 'activity';
}
}
if ($order->type == 'community') {
$service = CommunityActivity::withTrashed()
->where('id', $order->type_id)
->first();
if ($service->class == 'many') {
$goods = CommunityActivity::withTrashed()
->where('id', $order->type_id)
->where('class', 'many')
->value('title');
$text = $order->created_at . ' 购买了 《' . $goods . '》';
$order->goods = $text;
$order->type = 'service';
}
}
if ($order->type == 'course') {
$goods = Course::withTrashed()
->where('id', $order->type_id)
->value('title');
$text = $order->created_at . ' 购买了 《' . $goods . '》';
$order->goods = $text;
}
if ($order->type == 'shop') {
$goods = MerchantShop::withTrashed()
->where('id', $order->type_id)
->value('title');
$addres = ShopRecive::where('order_id', $order->id)
->value('address');
$text = $order->created_at . ' 购买了 《' . $goods . '》';
$order->goods = $text;
$order->address = $addres;
}
if ($order->type == 'consult') {
$goods = Consultation::withTrashed()
->where('id', $order->type_id)
->value('title');
$text = $order->created_at . ' 购买了 《' . $goods . '》';
$order->goods = $text;
}
if ($order->type == 'member') {
$goods = SaasMemberLevel::where('id', $order->type_id)
->value('level_title');
$text = $order->created_at . '购买了VIP《' . $goods . "";
$order->goods = $text;
}
// $order->avatar = $order->viewer ? $order->viewer->avatar : User::DefaultAvatar;
$order->avatar = $order->merUser ? $order->merUser->pic : User::DefaultAvatar;
$order->nickname = $order->merUser ? $order->merUser->nickname : '匿名用户';
if (empty($order->avatar)) {
$order->avatar = User::DefaultAvatar;
}
if (empty(trim($order->nickname))) {
$order->nickname = '匿名用户';
}
if (strpos($order->nickname, '用户') !== false) {
$is_hide = 0;
}
// if($order->merUser){
// if(strstr($order->merUser->nickname,'用户')) $is_hide = 0;
// }
$order->is_hide = $is_hide;
unset($order->viewer);
unset($order->merUser);
}
return $this->success('ok', $orders);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息中,请稍后再试');
}
}
//获取该笔订单最大退款金额
/**
* 移动端订单详情
* @param Request $request
* @param $order_id
* @return JsonResponse|string
*/
public function phoneOrderDetail(Request $request, $order_id)
{
try {
$order = TouristOrder::where('id', $order_id)
->select('id', 'price', 'goods', 'num', 'pay_type', 'trade_no', 'type', 'type_id', 'created_at', 'comment', 'Praise', 'mobile', 'name', 'linkmen')
->first();
if (empty($order)) {
return $this->failure('未查询到该订单,请稍后再试');
}
if ($order->type == 'shop') {
$order->address = $order->recive->address;
$order->pic = MerchantShop::withTrashed()
->where('id', $order->type_id)
->value('icon');
$order->title = MerchantShop::withTrashed()
->where('id', $order->type_id)
->value('title');
unset($order->recive);
}
if ($order->type == 'course') {
$order->pic = Course::withTrashed()
->where('id', $order->type_id)
->value('thumb');
$order->title = Course::withTrashed()
->where('id', $order->type_id)
->value('title');
}
if ($order->type == 'community') {
$community = CommunityActivity::withTrashed()
->where('id', $order->type_id)
->first();
$order->pic = $community->pic;
$order->title = $community->title;
$order->type = $community->class == 'one' ? 'avtivity' : 'service';
}
if ($order->type == 'consult') {
$consulate = Consultation::withTrashed()
->where('id', $order->type_id)
->first();
$order->pic = $consulate->pic;
$order->title = $consulate->title;
$order->teacher = ConsultAccount::where('id', $consulate->consult_account_id)
->value('name');
$order->duration = $consulate->duration;
$order->desc = ConsultationRecords::where('consulation_id', $order->type_id)
->value('desc') ?? '无';
}
if ($order->type == 'reward_info') {
$infor = MerchantInformation::withTrashed()
->where('id', $order->type_id)
->first();
$order->pic = $infor->pic;
$order->title = $infor->title;
$order->name = $order->merUser ? $order->merUser->name : '匿名用户';
$order->mobile = $order->merUser ? $order->merUser->mobile : '匿名用户';
if (empty($order->name))
$order->name = '匿名用户';
if (empty($order->mobile))
$order->mobile = '匿名用户';
// $order->pv = Redis::zscore('information',$infor->id)??0;
}
if ($order->type == 'reward_activity') {
$Activity = CommunityActivity::withTrashed()
->where('id', $order->type_id)
->first();
$order->pic = $Activity->pic;
$order->title = $Activity->title;
$order->name = $order->merUser ? $order->merUser->name : '匿名用户';
$order->mobile = $order->merUser ? $order->merUser->mobile : '匿名用户';
if (empty($order->name)) {
$order->name = '匿名用户';
}
if (empty($order->mobile)) {
$order->mobile = '匿名用户';
}
// $order->pv = Redis::zscore('information',$Activity->id)??0;
}
$linkmen = [];
if ($order->linkmen && $order->linkmen != 'null') {
$linkmen = json_decode($order->linkmen);
}
$order->linkmen = $linkmen;
$order->goods = $order->goods ?? '默认规格';
$has_refund = MRefundOrder::where('trade_no', $order->trade_no)->where('is_hook', 1)->sum('refund_fee');
$order->has_refund = $has_refund;
return $this->success('ok', $order);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息了,请稍后再试');
}
}
/**
* 订单退款
* */
public function refundOrder(Request $request)
{
try {
$merchant_id = $request->account_id;
$trade_no = $request->trade_no;//订单号
$order = Order::where('trade_no', $trade_no)->first();
if (empty($order))
return $this->failure('退款失败,未查询到该订单');
// if($order->type == 'course')
// return $this->failure('退款功能维护中');
if ($order->pay_status == 0)
return $this->failure('订单未支付,无法退款');
if ($order->pay_status == 3)
return $this->failure('该订单已完成全部退款');
//商户收益账号
$m_earning_account = MEarningAccount::where('m_id', $merchant_id)->where('m_user_id', 0)->first();
if (!$m_earning_account)
return $this->failure('账号异常,无法发起退款');
//退款金额
$refund_price = $request->refund_price;
if ($refund_price <= 0)
return $this->failure('请输入合理价格');
$max_price = $this->getMaxRefund($trade_no);
$max_price = number_format($max_price, 2, '.', '');
if ($refund_price > $max_price)
return $this->failure('当前订单最大退款金额为:' . $max_price . '元');
if ($order->pay_status == 4) {
//商户当前余额
$balance = $m_earning_account->balance;
if ($refund_price > $balance)
return $this->failure('账户余额仅剩 ' . $balance . '元,请重新输入');
} else {
//当前订单剩余收益
$has_refund = MRefundOrder::where('trade_no', $trade_no)->where('is_hook', 1)->sum('refund_fee');
$balance = $order->price - $has_refund;
if ($refund_price > $balance)
return $this->failure('当前订单收益仅剩 ' . $balance . '元,请重新输入');
}
//退款订单号
$refund_trade_no = $this->getRefundTradeNo();
$refund = MRefundOrder::create([
'm_id' => $merchant_id,
'admin_id' => $request->merchant_admin_id ?: 0,
'm_user_id' => $order->account_id,
'type' => $order->type,
'trade_no' => $order->trade_no,
'refund_trade_no' => $refund_trade_no,
'total_fee' => $order->price,
'refund_fee' => $refund_price,
'is_hook' => 0,
'remark' => $request->remark,
]);
DB::beginTransaction();
if ($order->pay_status == 4) {
$m_earning_account->decrement('balance', $refund_price);
$m_earning_account->decrement('total_value', $refund_price);
}
//全部退款 订单状态修改为已退款
if ($refund_price == $max_price) {
$order->update(['pay_status' => 3, 'comment' => null, 'Praise' => null, 'pic' => null]);
$this->refundOperation($order, $trade_no);
}
// $array = ['refund_desc' => '订单退款'];
// $result = \WechatService::orderRefund($trade_no, $refund_trade_no, $order->price, $refund_price, $array);
$url = "https://love.ufutx.com/go/api/order/refund";
$data = [
"trade_no" => $trade_no,
"refund_no" => $refund_trade_no,
"reason" => "订单退款",
"refund_fee" => (int) number_format($order->price, 2, '', ''),
"total_fee" => (int) number_format($refund_price, 2, '', ''),
"notify_url" => "https://love.ufutx.com/api/admin/order/refun/callback",
"token" => "7ujm,ki8"
];
$result = Http::post($url, $data);
Log::info($result);
$result = json_decode($result, true);
if (isset($result["code"]) && $result["code"] == 1) {//退款失败
$refund->update(['err_msg' => $result['message']]);
DB::commit();
return $this->failure('退款失败,', $result['message']);
}
$refund->update(['is_hook' => 1]);
DB::commit();
$admin_id = $request->merchant_admin_id;
$user_id = $this->matchFulinkUser($order->account_id);
$result_type = $this->getOrderType($order);
if ($user_id) {
$maker_user_id = 0;//福恋操作人id
$admin = !empty($admin_id) ? MerchantAdmins::find($admin_id) : MerchantAccount::find($merchant_id);
$maker_user_id = User::where('mobile', $admin->mobile)->value('id');
$maker_user_id = $maker_user_id ?? 0;
$text = '订单类型:' . $result_type . ' 订单号:' . $order->trade_no . ' 发起退款' . $refund_price . '元 理由:' . $request->remark;
if ($maker_user_id) {
$nickname = User::where('id', $maker_user_id)->value('nickname');
$text = $text . ' 操作人【' . $nickname . '】';
}
//同步一条该订单用户的用户备注
ClientComment::create([
'user_id' => $user_id,
'maker_user_id' => $maker_user_id,
'type' => 'mobile',
'comment' => $text,
]);
}
\CommonUtilsService::refundNotice($order, $refund_price, $result_type);
//未结算订单重新计算收益
if ($order->pay_status == 1) {//重新计算预分成
SendEarningMessageV2::dispatch($order->id)->onQueue('order');
} elseif ($order->pay_status == 3) {//删除预分成记录
MAdvanceEarning::where('m_order_id', $order->id)->delete();
}
DB::commit();
return $this->success('退款成功');
} catch (\Exception $e) {
DB::rollBack();
$this->getError($e);
return $this->failure('服务器休息,请稍后再试');
}
}
/**
* 退款后操作
* */
public function refundOperation($type, $trade_no)
{
try {
switch ($type) {
case 'course':
UserCourses::where('trade_no', $trade_no)->update(['status' => 2]);
break;
case 'consult':
ConsultationRecords::where('trade_no', $trade_no)->update(['pay_status' => 2, 'comment' => null, 'Praise' => null]);
break;
case 'community':
break;
case 'shop':
TouristOrder::where('trade_no', $trade_no)->update(['comment' => null, 'Praise' => null, 'pic' => null]);
break;
default:
return true;
break;
}
return true;
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息了,请稍后再试');
}
}
//退款列表
public function refunds(Request $request)
{
try {
$m_id = $request->account_id;
$keyword = $request->keyword;
$refunds = MRefundOrder::with('mUser:id,mobile,nickname,pic,created_at')->where('m_id', $m_id);
if ($request->keyword) {
$keyword = trim($keyword);
$refunds = $refunds->whereHas('mUser', function ($sql) use ($keyword) {
$sql->where('nickname', 'like', '%' . $keyword . '%')
->orWhere('mobile', 'like', '%' . $keyword . '%');
});
}
$refunds = $refunds->orderBy('id', 'desc')->paginate();
return $this->success('ok', $refunds);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息了,请稍后再试');
}
}
//退款详情
public function refundDetail(Request $request)
{
try {
$trade_no = $request->trade_no;
if (empty($trade_no))
return $this->failure('缺少必要参数 trade_no');
$order = Order::where('trade_no', $trade_no)->first();
if (!$order) {
return $this->failure('订单不存在');
}
$max_refund = $this->getMaxRefund($trade_no);
$max_refund = number_format($max_refund, 2, '.', '');
$has_refund = MRefundOrder::where('trade_no', $trade_no)->where('is_hook', 1)->sum('refund_fee');
$total_price = $order->price;
//不可退款金额
$no_refund = MEarning::where('m_order_id', $order->id)->where('m_user_id', '<>', 0)->sum('value');
$refunds = MRefundOrder::where('trade_no', $trade_no)->where('is_hook', 1)->orderBy('id', 'desc')->select('id', 'refund_fee', 'remark', 'created_at', 'is_hook', 'total_fee', 'm_id', 'admin_id')->paginate();
foreach ($refunds as $key => $value) {
if ($value->admin_id) {
$member = MerchantMembers::withTrashed()->where(['mch_id' => $value->m_id, 'admin_id' => $value->admin_id])->first();
$user['name'] = $member->name;
$user['avatar'] = $member->avatar;
} else {
$anchor = Anchor::where('m_id', $value->m_id)->first();
$user['name'] = $anchor->name;
$user['avatar'] = $anchor->pic;
}
$value->user = $user;
}
return $this->success('ok', compact('max_refund', 'has_refund', 'refunds', 'no_refund', 'total_price'));
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息了,请稍后再试');
}
}
/**
* 订单跟进查询
*/
public function getOrderFollowList(Request $request)
{
$start_time = $request->start_time;
$end_time = $request->end_time;
$keyword = $request->keyword;
$return = MOrderFollow::with('order:id,price,pay_status,name,mobile,desc,created_at')
->where('merchant_id', $request->account_id);
if ($start_time) {
$return = $return->where('m_order_follows.created_at', '>=', $start_time . ' 00:00:01');
}
if ($end_time) {
$return = $return->where('m_order_follows.created_at', '<=', $end_time . ' 23:59:59');
}
$return = $return->join('merchant_admin_links', function ($join) use ($request) {
$join->on('m_order_follows.admin_id', '=', 'merchant_admin_links.admin_id')
->where('m_order_follows.merchant_id', $request->account_id)
->where('merchant_admin_links.mch_id', $request->account_id)
->where('merchant_admin_links.user_role', 2);
}, null, null, 'left');
$return = $return->join('merchant_admins', function ($join) use ($request) {
$join->on('m_order_follows.admin_id', '=', 'merchant_admins.id');
}, null, null, 'left');
$return = $return->join('merchant_members', function ($join) use ($request) {
$join->on('m_order_follows.admin_id', '=', 'merchant_members.admin_id')
->where('merchant_members.mch_id', $request->account_id);
}, null, null, 'left');
if ($keyword) {
$return = $return->where(function ($query) use ($keyword) {
$query->orWhere('merchant_admins.mobile', 'like', "%$keyword%")
->orWhere('merchant_admins.id', "like", "%$keyword%")
->orWhere('merchant_members.name', "like", "%$keyword%");
});
}
$return = $return->select('m_order_follows.*', 'merchant_admins.mobile', 'merchant_members.name', 'merchant_members.avatar')
->orderBy('m_order_follows.id', 'desc')
->paginate();
return $this->success('ok', $return);
}
/**
* 添加分帐接收方
* @param Request $request
*/
public function addReceiver(Request $request)
{
try {
$sub_mch_id = WechatSubMerchant::where('merchant_id', $request->merchant_id)
->value('sub_mch_id');
$sub_mch_id = '1626601973';
$receiver = [
"type" => "PERSONAL_OPENID",
"account" => "oPC_2vu1AxIQtqPf8gmUoJg515Ik",//PERSONAL_OPENID个人openid
//"name" => "张三",//接收方真实姓名
"relation_type" => "PARTNER"
];
\WechatService::addReceivers($receiver, $sub_mch_id);
$receiver = [
"type" => "MERCHANT_ID",
"account" => "1581887811",//MERCHANT_ID商户ID
"name" => "深圳福恋智能信息科技有限公司",//商户全称
"relation_type" => "SERVICE_PROVIDER"
];
\WechatService::addReceivers($receiver, $sub_mch_id);
$receiver = [
"type" => "MERCHANT_ID",
"account" => "1581903621",//MERCHANT_ID商户ID
"name" => "深圳福恋智能信息科技有限公司",//商户全称
"relation_type" => "PARTNER"
];
\WechatService::addReceivers($receiver, $sub_mch_id);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息了,请稍后再试');
}
}
/**
* 单次分帐
* @param Request $request
*/
public function wechatShare(Request $request)
{
$order_id = $request->order_id;
$order = TouristOrder::where('id', $order_id)->first();
$transaction_id = $order->wechat_transaction_id;
$out_trade_no = $order->trade_no;
$sub_mch_id = WechatSubMerchant::where('merchant_id', $request->merchant_id)
->value('sub_mch_id');
$sub_mch_id = '1626601973';
$receivers = [
[
"type" => "PERSONAL_OPENID",
"account" => "oPC_2vu1AxIQtqPf8gmUoJg515Ik",
"amount" => 2,
"description" => "个人销售奖励"
],
[
"type" => "MERCHANT_ID",
"account" => "1581887811",
"amount" => 1,
"description" => "服务费用"
],
[
"type" => "MERCHANT_ID",
"account" => "1581903621",
"amount" => 1,
"description" => "合作伙伴提成"
]
];
$return = \WechatService::wechatShare($transaction_id, $out_trade_no, $receivers, $sub_mch_id);
if ($return) {
return $this->success('分帐成功');
} else {
return $this->fail('分帐失败');
}
}
/**
* 完成分帐 单次分帐不用调用
*/
public function markOrderAsFinished(Request $request)
{
$order_id = $request->order_id;
$order = TouristOrder::where('id', $order_id)->first();
$transaction_id = $order->wechat_transaction_id;
$out_trade_no = $order->trade_no;
$sub_mch_id = WechatSubMerchant::where('merchant_id', $request->merchant_id)
->value('sub_mch_id');
$sub_mch_id = '1626601973';
$return = \WechatService::markOrderAsFinished($transaction_id, $out_trade_no, $sub_mch_id);
if ($return) {
return $this->success('分帐成功');
} else {
return $this->fail('分帐失败');
}
}
/**
* 分帐查询
*/
public function wechatShareQuery(Request $request)
{
$order_id = $request->order_id;
$order = TouristOrder::where('id', $order_id)->first();
$transaction_id = $order->wechat_transaction_id;
$out_trade_no = $order->trade_no;
$sub_mch_id = WechatSubMerchant::where('merchant_id', $request->merchant_id)
->value('sub_mch_id');
$sub_mch_id = '1626601973';
$return = \WechatService::wechatShareQuery($transaction_id, $out_trade_no, $sub_mch_id);
if ($return) {
return $this->success('分帐成功');
} else {
return $this->fail('分帐失败');
}
}
/**
* 订单状态表
*/
public function getOrderStatus(Request $request)
{
try {
$merchant_id = $request->account_id;
$order_id = $request->order_id;
if (!$order_id) {
return $this->fail('订单号不能为空');
}
$order = TouristOrder::where('id', $order_id)->where('merchant_id', $merchant_id)
->first();
if (!$order) {
return $this->fail('订单不存在');
}
$order_status = OrderStatusLink::where('order_id', $order->id)->where('merchant_id', $merchant_id)
->first();
return $this->success('ok', $order_status);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息中,请稍后再试');
}
}
/**
* 更新订单状态
*/
public function updateOrderStatus(Request $request)
{
try {
$merchant_id = $request->account_id;
$order_id = $request->order_id;
$status = $request->status;
if (!$order_id) {
return $this->fail('订单号不能为空');
}
if (!$status) {
return $this->fail('订单状态值不能为空');
}
$order = TouristOrder::where('id', $order_id)->where('merchant_id', $merchant_id)
->first();
if (!$order) {
return $this->fail('订单不存在');
}
$order_status = OrderStatusLink::where('order_id', $order->id)->where('merchant_id', $merchant_id)
->first();
if (!$order_status) {
$order_status = new OrderStatusLink();
$order_status->order_id = $order->id;
$order_status->status = $status;
$order_status->merchant_id = $merchant_id;
$order_status->merchant_user_id = $order->account_id;
$order_status->save();
} else {
$order_status->status = $status;
$order_status->save();
}
return $this->success('ok');
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息中,请稍后再试');
}
}
/**
* 邀请商家跟进订单
*/
public function inviteMerchantProcessOrderRole(Request $request)
{
try {
$order_id = $request->order_id;
$role_id = $request->role_id;
if (config('app.debug')) {
if (!$order_id || !$role_id) {
return $this->failure('参数不全');
}
}
//检查订单是否存在
$order = TouristOrder::where('id', $order_id)->where('merchant_id', $request->account_id)
->first();
if (!$order) {
return $this->failure('订单不存在');
}
$jump_url = urlencode(env('APP_SADMIN_URL') . '/pu_m/#/thirdPartyBinding?merchant_id=' . $request->account_id .
'&order_id=' . $order_id . '&role_id=' . $role_id);
$share_url = env('APP_URL') . '/api/official/live/wechat/inviteMerchantProcessOrderAuth?merchant_id=' .
$request->account_id . '&order_id=' . $order_id . '&role_id=' . $role_id . '&url=' . $jump_url;
$qr_code = Redis::get('inviteMerchantProcessOrder_' . $request->account_id . '_' . $order_id . '_' . $role_id);
if (!$qr_code) {
$qr_code = $this->getPreviewQrcode($share_url);
Redis::setex('inviteMerchantProcessOrder_' . $request->account_id . '_' . $order_id . '_' . $role_id, 60 * 60 * 24 * 30, $qr_code);
$qr_code = Redis::get('inviteMerchantProcessOrder_' . $request->account_id . '_' . $order_id . '_' . $role_id);
}
$data['share_url'] = $share_url;
$data['qr_code'] = $qr_code;
return $this->success('ok', $data);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器休息中,请稍后再试');
}
}
/**
* 邀请的商家绑定角色
*/
public function bindMerchantToRole(Request $request)
{
$wechatUser = session('wechat.oauth_user.new');
if (empty($wechatUser)) {
$new_openId = $request->openid;
} else {
$new_openId = $wechatUser->getId();
}
$openid = $new_openId ?? $request->openid;
$mobile = $request->mobile;
$code = $request->code;
$role_id = $request->role_id;
$order_id = $request->order_id;
if (config('app.debug')) {
if (!$role_id || !$order_id) {
return $this->failure('参数不全');
}
}
if ($mobile) {
if (!$code) {
return $this->failure('验证码不能为空');
}
$sms = new Sms(new App);
$result = $sms->check($mobile, $code);
if ($result) {
switch ($result) {
case '请填写验证码':
return $this->resp($result, ['status' => 7, 'message' => '请填写验证码']);
break;
case '验证码有误':
return $this->resp($result, ['status' => 8, 'message' => '验证码有误']);
break;
case '验证码过期':
return $this->resp($result, ['status' => 9, 'message' => '验证码过期']);
break;
case '验证码已使用':
return $this->resp($result, ['status' => 10, 'message' => '验证码已使用']);
break;
default:
# code...
break;
}
}
$name = $this->randString(6);
$merchant = MerchantAccount::where('mobile', $mobile)->orWhere('openid', $openid)->first();
if (!$merchant) {
$merchant = new MerchantAccount();
$merchant->mobile = $mobile;
$merchant->openid = $openid;
$merchant->share_icon = User::DefaultAvatar;
$merchant->share_title = $name;
$merchant->share_subtitle = $name;
$password = $this->randString(6);
$merchant->password = encrypt($password);
$merchant->save();
$merchant->api_token = encrypt($merchant->id . '-' . $merchant->mobile . '-' . time() . '-' . '' . "-" . '');
$merchant->save();
$content = '恭喜您,成功绑定福恋智能商家版服务流程订单,欢迎使用,您的用户名 :' . $request->mobile . ' 密码 :' . $password;
;
Message::create([
'phone' => $mobile,
'message' => $content,
'confirmed' => 1,
'ip' => request() ? request()->ip() : '127.0.0.1',
]);
Messengers::sendSMS($mobile, $content);
} else {
if ($merchant->openid != $openid) {
$merchant_new = MerchantAccount::where('openid', $openid)->first();
if (!$merchant_new) {
$merchant->openid = $openid;
$merchant->save();
}
}
}
$anchor = Anchor::where('mobile', $mobile)->orWhere('openid', $openid)->first();
if (!$anchor) {
$anchor = new Anchor();
$anchor->m_id = $merchant->id;
$anchor->name = $name;
$anchor->introduction = '新入驻商家';
$anchor->pic = User::DefaultAvatar;
$anchor->mobile = $mobile;
$anchor->openid = $openid;
$anchor->save();
} else {
if ($anchor->openid != $openid) {
$anchor_new = Anchor::where('openid', $openid)->first();
if (!$anchor_new) {
$anchor->openid = $openid;
$anchor->save();
}
}
}
} else {
$merchant = MerchantAccount::where('openid', $openid)->first();
}
if (!$merchant) {
return $this->failure('商家不存在');
}
$order = TouristOrder::find($order_id);
if (!$order) {
return $this->failure('订单不存在');
}
if ($order->merchant_id == $merchant->id) {
return $this->failure('不能邀请自己处理自己的角色');
}
$admin = ServiceRoleAdmin::where('order_id', $order_id)->where('order_role_id', $role_id)
->where('m_id', $order->merchant_id)
->where('merchant_id', $merchant->id)
->where('admin_id', 0)
->first();
if ($admin) {
return $this->failure('此商家已绑定了该订单角色,不能重复绑定');
}
$admin = new ServiceRoleAdmin();
$admin->m_id = $order->merchant_id;
$admin->order_id = $order_id;
$admin->order_role_id = $role_id;
$admin->merchant_id = $merchant->id;
$admin->admin_name = $merchant->share_title;
$admin->save();
$account = $merchant;
$anchor = Anchor::where('m_id', $merchant->id)
->select('openid', 'name', 'pic', 'mobile', 'service_nature')
->first();
$api_token = $merchant->api_token;
$account->is_admin = 0;
$info = MerchantInfo::where(['m_id' => $account->id])->first();
//同步任務到任務清單
$this->syncTask($merchant->mobile, $role_id, $order);
return $this->success('ok', compact('account', 'anchor', 'api_token', 'info'));
}
public function syncTask($mobile, $role_id, $order)
{
$role = ServiceOrderRole::find($role_id);
//第三方任务创建
$task_no = $role->task_no ?: 'love_' . uniqid();
$cate_name = '任务清单一';
$operates = ServiceOrderOperation::where("order_role_id", $role->id)->get();
$sub_tasks = [];
$callback = env('APP_URL') . '/api/s/admin/tp/service/orders/operate/callback?task_no=';
foreach ($operates as $operate) {
$sub_task_no = $operate->task_no ?: 'love_' . uniqid();
$task['title'] = $operate->title;
$task['task_no'] = $sub_task_no;
$task['callback'] = $callback . $sub_task_no;
$sub_tasks[] = $task;
ServiceOrderOperation::where('id', $operate->id)->update(['task_no' => $sub_task_no]);
}
$data = [
'mobile' => $mobile,
'cate_name' => $cate_name,
'title' => '用户【' . $order->name . '】,订单【' . $order->desc . '】,服务角色【' . $role->name . '】',
'task_no' => $task_no,
'callback' => null,
'sub_task' => $sub_tasks,
];
ServiceOrderRole::where('id', $role->id)->update(['task_no' => $task_no]);
SyncTask::dispatch($data)->onQueue('sync.task');
}
/**
* 设置不参与匹配标记
*/
public function updateMatchConfigFlag(Request $request)
{
$order_id = $request->order_id;
$match_config = $request->match_config;
$tourist_order = TouristOrder::find($order_id);
if ($tourist_order && $tourist_order->type == 'community') {
$community = CommunityActivity::find($tourist_order->type_id);
if ($community && $community->class == 'one') {
$tourist_order->match_config = $match_config;
$tourist_order->save();
}
}
return $this->success('ok');
}
}