123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152 |
- <?php
- namespace App\Services\Client;
- use App\Models\AgentConfig;
- use App\Models\AgentInfo;
- use App\Models\CoachConfig;
- use App\Models\CoachUser;
- use App\Models\MemberUser;
- use App\Models\Order;
- use App\Models\OrderGrabRecord;
- use App\Models\OrderRecord;
- use App\Models\Project;
- use App\Models\SysConfig;
- use App\Models\User;
- use App\Models\WalletPaymentRecord;
- use App\Models\WalletRefundRecord;
- use Exception;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- class OrderService
- {
- protected AgentService $agentService;
- protected ProjectService $projectService;
- public function __construct(
- AgentService $agentService,
- ProjectService $projectService
- ) {
- $this->agentService = $agentService;
- $this->projectService = $projectService;
- }
- /**
- * 订单初始化
- *
- * 初始化订单信息,包括用户钱包、技师信息、项目信息、地址信息和订单金额等
- *
- * @param int $userId 用户ID
- * @param array $data 订单数据
- * @return array 返回初始化的订单信息
- *
- * @throws \Exception 初始化失败时抛出异常
- */
- public function initialize(int $userId, array $data): array
- {
- try {
- // 参数验证
- abort_if(empty($data['project_id']), 400, '项目ID不能为空');
- abort_if(empty($data['coach_id']), 400, '技师ID不能为空');
- return DB::transaction(function () use ($userId, $data) {
- $user = MemberUser::find($userId);
- abort_if(! $user || $user->state != 'enable', 400, '用户状态异常');
- // 查询用户钱包
- $wallet = $user->wallet;
- // 查询默认地址
- $address = $user->address;
- $areaCode = $address ? $address->area_code : ($data['area_code'] ?? null);
- abort_if(empty($areaCode), 400, '区域编码不能为空');
- // 查询技师数据
- $coach = $this->validateCoach($data['coach_id']);
- // 获取项目详情
- $project = $this->projectService->getProjectDetail($data['project_id'], $areaCode);
- abort_if(! $project, 400, '项目不存在');
- // 计算订单金额
- $amounts = $this->calculateOrderAmount(
- $userId,
- $address?->id ?? 0,
- $data['coach_id'],
- $data['project_id'],
- $project->agent_id
- );
- return [
- 'wallet' => $wallet,
- 'coach' => $coach,
- 'project' => $project,
- 'address' => $address,
- 'amounts' => $amounts,
- ];
- });
- } catch (Exception $e) {
- Log::error('订单初始化失败', [
- 'userId' => $userId,
- 'data' => $data,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
- throw $e;
- }
- }
- /**
- * 创建订单
- */
- public function createOrder(int $userId, array $data): array
- {
- return DB::transaction(function () use ($userId, $data) {
- // 1. 参数校验
- $user = MemberUser::where('id', $userId)
- ->where('state', 'enable')
- ->firstOrFail();
- $project = Project::where('id', $data['project_id'])
- ->where('state', 'enable')
- ->firstOrFail();
- // 2. 订单类型判断
- $orderType = isset($data['order_id']) ? 'add_time' : 'normal';
- // 关键操作:验证必要参数
- abort_if(empty($data['project_id']), 400, '项目ID不能为空');
- abort_if(empty($data['service_time']), 400, '服务时间不能为空');
- abort_if($orderType == 'normal' && empty($data['coach_id']), 400, '技师ID不能为空');
- abort_if($orderType == 'normal' && empty($data['address_id']), 400, '地址ID不能为空');
- // 3. 验证地址
- $address = $user->addresses()
- ->where('id', $data['address_id'])
- ->firstOrFail();
- // 4. 根据订单类型处理
- if ($orderType == 'normal') {
- $coach = $this->validateCoach($data['coach_id']);
- } else {
- $originalOrder = $this->getOriginalOrder($user, $data['order_id']);
- $coach = $this->validateCoach($originalOrder->coach_id);
- abort_if(! in_array($originalOrder->state, ['service_ing', 'service_end']), 400, '原订单状态不允许加钟');
- $data = $this->prepareAddTimeData($originalOrder, $data);
- }
- // 5. 计算订单金额
- $amounts = $this->calculateOrderAmount(
- $userId,
- $address->id,
- $data['coach_id'],
- $data['project_id'],
- $project->agent_id,
- $data['use_balance'] ?? false
- );
- // 6. 验证金额和余额
- abort_if($amounts['total_amount'] <= 0, 400, '订单金额异常');
- if ($data['payment_type'] == 'balance') {
- $wallet = $user->wallet;
- abort_if($wallet->available_balance < $amounts['balance_amount'], 400, '可用余额不足');
- }
- // 7. 创建订单记录
- $order = $this->createOrderRecord($userId, $data, $orderType, $address, $data['payment_type'], (object) $amounts);
- // 8. 余额支付处理
- if ($order->payment_type == 'balance') {
- $this->handleBalancePayment($user, $order, $orderType);
- }
- return [
- 'order_id' => $order->id,
- 'payment_type' => $order->payment_type,
- ];
- });
- }
- // 提取方法:验证技师
- public function validateCoach(int $coachId): CoachUser
- {
- $coach = CoachUser::where('id', $coachId)
- ->where('state', 'enable')
- ->whereHas('info', fn ($q) => $q->where('state', 'approved'))
- ->whereHas('qual', fn ($q) => $q->where('state', 'approved'))
- ->whereHas('real', fn ($q) => $q->where('state', 'approved'))
- ->firstOrFail();
- return $coach;
- }
- // 提取方法:获取原始订单
- private function getOriginalOrder($user, $orderId): Order
- {
- $originalOrder = $user->orders->where('id', $orderId)
- ->whereIn('state', ['service_ing', 'service_end'])
- ->firstOrFail();
- return $originalOrder;
- }
- // 提取方法:准备加钟订单数据
- private function prepareAddTimeData($originalOrder, $data): array
- {
- if ($originalOrder->state == 'service_ing') {
- $startTime = now();
- } else {
- $startTime = now();
- }
- return [
- ...$data,
- 'order_id' => $data['order_id'],
- 'address_id' => $originalOrder->address_id,
- 'service_time' => $startTime,
- 'coach_id' => $originalOrder->coach_id,
- ];
- }
- // 提取方法:创建订单记录
- private function createOrderRecord($userId, $data, $orderType, $address, $payment_type, object $amounts): Order
- {
- $order = new Order;
- $order->user_id = $userId;
- $order->project_id = $data['project_id'];
- $order->coach_id = $data['coach_id'];
- $order->type = $orderType;
- $order->state = 'wait_pay';
- $order->source = 'platform';
- $order->total_amount = $amounts->total_amount;
- $order->balance_amount = $amounts->balance_amount;
- $order->pay_amount = $amounts->pay_amount;
- $order->project_amount = $amounts->project_amount;
- $order->traffic_amount = $orderType == 'add_time' ? 0 : $amounts->delivery_fee;
- $order->payment_type = ($data['use_balance'] && $amounts->pay_amount == 0) ? 'balance' : $payment_type;
- $order->service_time = $data['service_time'];
- $order->address_id = $data['address_id'];
- $order->longitude = $address->longitude;
- $order->latitude = $address->latitude;
- $order->location = $address->location;
- $order->address = $address->address;
- $order->area_code = $address->area_code;
- $order->save();
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => $orderType == 'add_time' ? 'add_time' : 'create',
- 'remark' => $orderType == 'add_time' ? '加钟订单' : '创建订单',
- ]);
- return $order;
- }
- // 提取方法:处理余额支付
- private function handleBalancePayment($user, $order, $orderType): void
- {
- $order->state = $orderType == 'normal' ? 'wait_receive' : 'service_ing';
- $order->save();
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $user->id,
- 'object_type' => MemberUser::class,
- 'state' => 'pay',
- 'remark' => '余额支付',
- ]);
- $user->wallet->decrement('total_balance', $order->balance_amount);
- $user->wallet->decrement('available_balance', $order->balance_amount);
- }
- /**
- * 取消订单
- */
- public function cancelOrder(int $userId, int $orderId): array
- {
- return DB::transaction(function () use ($userId, $orderId) {
- try {
- // 1. 验证用户和订单
- $order = $this->validateOrderForCancel($userId, $orderId);
- abort_if($order->state == 'cancel', 400, '订单已取消');
- // 2. 处理退款
- if (in_array($order->state, ['wait_receive', 'on_the_way'])) {
- $this->handleCancelRefund($order);
- }
- // 3. 完成订单取消
- $this->completeCancel($order, $userId);
- // 4. 通知技师
- if ($order->coach_id) {
- // event(new OrderCancelledEvent($order));
- }
- return ['message' => '订单已取消'];
- } catch (Exception $e) {
- $this->logCancelOrderError($e, $userId, $orderId);
- throw $e;
- }
- });
- }
- /**
- * 验证订单取消条件
- */
- private function validateOrderForCancel(int $userId, int $orderId): Order
- {
- // 复用之前的用户验证逻辑
- $user = MemberUser::where('id', $userId)
- ->where('state', 'enable')
- ->firstOrFail();
- // 验证订单状态
- $order = Order::where('user_id', $userId)
- ->where('id', $orderId)
- ->whereIn('state', ['wait_pay', 'wait_receive', 'on_the_way'])
- ->lockForUpdate()
- ->firstOrFail();
- return $order;
- }
- /**
- * 处理订单取消退款
- */
- private function handleCancelRefund(Order $order): void
- {
- $user = $order->user;
- switch ($order->state) {
- case 'wait_receive': // 已接单
- // 扣除20%费用
- $deductAmount = ($order->payment_amount + $order->balance_amount - $order->traffic_amount) * 0.2;
- $this->handleRefund($user, $order, $deductAmount, false);
- break;
- case 'on_the_way': // 已出发
- // 扣除50%费用并扣除路费
- $deductAmount = ($order->payment_amount + $order->balance_amount - $order->traffic_amount) * 0.5;
- $this->handleRefund($user, $order, $deductAmount, true);
- break;
- case 'wait_pay':
- // 待支付状态直接取消,无需退款
- break;
- default:
- abort(400, '当前订单状态不允许取消');
- }
- }
- /**
- * 完成订单取消
- */
- private function completeCancel(Order $order, int $userId): void
- {
- // 添加订单取消记录
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => 'cancel',
- 'remark' => '用户取消订单',
- ]);
- // 修改订单状态
- $order->state = 'cancel';
- $order->cancel_time = now(); // 添加取消时间
- $order->save();
- // 如果有技师,可能需要通知技师订单已取消
- if ($order->coach_id) {
- // TODO: 发送通知给技师
- // event(new OrderCancelledEvent($order));
- }
- }
- /**
- * 处理退款
- */
- private function handleRefund(MemberUser $user, Order $order, float $deductAmount, bool $deductTrafficFee): void
- {
- // 关键操作:计算实际退款金额
- $refundAmount = $order->payment_amount + $order->balance_amount;
- if ($deductTrafficFee) {
- $refundAmount -= $order->traffic_amount;
- // TODO: 记录技师路费收入
- }
- $refundAmount -= $deductAmount;
- // 优先从余额支付金额中扣除
- $balanceRefund = min($order->balance_amount, $refundAmount);
- if ($balanceRefund > 0) {
- $this->createRefundRecords($user, $order, $balanceRefund);
- }
- // 剩余退款金额从支付金额中退还
- $paymentRefund = $refundAmount - $balanceRefund;
- if ($paymentRefund > 0) {
- $this->createRefundRecords($user, $order, $paymentRefund, 'payment');
- }
- // 记录平台收入
- if ($deductAmount > 0) {
- // TODO: 添加平台收入记录
- // PlatformIncome::create([...]);
- }
- }
- /**
- * 创建退款记录
- */
- private function createRefundRecords($user, $order, $amount, $type = 'balance'): void
- {
- $refundMethod = $type;
- $remark = $type == 'balance' ? '订单取消退还余额' : '订单取消退还支付金额';
- // 创建退款记录
- $refundRecord = $user->wallet->refundRecords()->create([
- 'refund_method' => $refundMethod,
- 'total_refund_amount' => $order->payment_amount + $order->balance_amount,
- 'actual_refund_amount' => '0.00',
- 'wallet_balance_refund_amount' => $type == 'balance' ? $amount : '0.00',
- 'recharge_balance_refund_amount' => '0.00',
- 'remark' => $remark,
- 'order_id' => $order->id,
- ]);
- // 创建交易记录
- $user->wallet->transRecords()->create([
- 'amount' => $amount,
- 'owner_type' => get_class($refundRecord),
- 'owner_id' => $refundRecord->id,
- 'remark' => $remark,
- 'trans_type' => 'income',
- 'storage_type' => 'balance',
- 'before_balance' => $user->wallet->total_balance,
- 'after_balance' => $user->wallet->total_balance + $amount,
- 'before_recharge_balance' => '0.00',
- 'after_recharge_balance' => '0.00',
- 'trans_time' => now(),
- 'state' => 'success',
- ]);
- // 更新钱包余额
- $user->wallet->increment('total_balance', $amount);
- $user->wallet->increment('available_balance', $amount);
- $user->wallet->save();
- }
- /**
- * 记录订单取消错误日志
- */
- private function logCancelOrderError(Exception $e, int $userId, int $orderId): void
- {
- // 复用之前的日志记录方法
- Log::error('取消订单失败:', [
- 'message' => $e->getMessage(),
- 'user_id' => $userId,
- 'order_id' => $orderId,
- 'trace' => $e->getTraceAsString(),
- ]);
- }
- /**
- * 结束订单
- */
- public function finishOrder(int $userId, int $orderId): array
- {
- return DB::transaction(function () use ($userId, $orderId) {
- try {
- // 1. 验证用户和订单
- $order = $this->validateOrderForFinish($userId, $orderId);
- abort_if($order->state == 'service_end', 400, '订单已完成');
- // 2. 验证技师状态
- $coach = $this->validateCoach($order->coach_id);
- // 3. 验证服务时长
- $this->validateServiceDuration($order);
- // 4. 完成订单
- $this->completeOrder($order, $userId);
- // 5. 通知技师
- // event(new OrderFinishedEvent($order));
- return ['message' => '订单已完成'];
- } catch (Exception $e) {
- $this->logFinishOrderError($e, $userId, $orderId);
- throw $e;
- }
- });
- }
- /**
- * 验证订单完成条件
- */
- private function validateOrderForFinish(int $userId, int $orderId): Order
- {
- // 验证用户状态
- $user = MemberUser::where('id', $userId)
- ->where('state', 'enable')
- ->firstOrFail();
- // 验证订单状态
- $order = Order::where('user_id', $userId)
- ->where('id', $orderId)
- ->where('state', 'service_ing')
- ->lockForUpdate()
- ->firstOrFail();
- return $order;
- }
- /**
- * 验证服务时长
- */
- private function validateServiceDuration(Order $order): void
- {
- // 计算服务时长
- $serviceStartTime = $order->service_start_time ?? $order->created_at;
- $serviceDuration = now()->diffInMinutes($serviceStartTime);
- // 获取项目要求的最短服务时长
- $minDuration = $order->project->duration ?? 0;
- abort_if($serviceDuration < $minDuration, 400, "服务时长不足{$minDuration}分钟");
- }
- /**
- * 完成订单
- */
- private function completeOrder(Order $order, int $userId): void
- {
- // 1. 创建订单记录
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => 'finish',
- 'remark' => '服务完成',
- ]);
- // 2. 更新订单状态
- $order->state = 'service_end';
- $order->finish_time = now();
- $order->save();
- }
- /**
- * 记录订单完成错误日志
- */
- private function logFinishOrderError(Exception $e, int $userId, int $orderId): void
- {
- Log::error('结束订单失败:', [
- 'message' => $e->getMessage(),
- 'user_id' => $userId,
- 'order_id' => $orderId,
- 'trace' => $e->getTraceAsString(),
- ]);
- }
- /**
- * 确认技师离开
- */
- public function confirmLeave(int $userId, int $orderId): array
- {
- return DB::transaction(function () use ($userId, $orderId) {
- try {
- // 1. 参数校验
- $order = Order::where('user_id', $userId)
- ->where('id', $orderId)
- ->where('state', 'service_end') // 订单状态必须是服务结束
- ->firstOrFail();
- if (! $order) {
- throw new Exception('订单不能撤离');
- }
- // 2. 添加订单撤离记录
- OrderRecord::create([
- 'order_id' => $orderId,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => 'leave',
- 'remark' => '技师已离开',
- ]);
- // 3. 修改订单状态为撤离
- $order->state = 'leave';
- $order->save();
- return ['message' => '已确技师离开'];
- } catch (Exception $e) {
- Log::error('确认技师离开失败:', [
- 'message' => $e->getMessage(),
- 'user_id' => $userId,
- 'order_id' => $orderId,
- ]);
- throw $e;
- }
- });
- }
- /**
- * 获取订单列表
- */
- public function getOrderList(int $user_id): \Illuminate\Contracts\Pagination\LengthAwarePaginator
- {
- $user = MemberUser::find($user_id);
- return $user->orders()
- ->with([
- 'coach.info:id,nickname,avatar,gender',
- ])
- ->orderBy('created_at', 'desc')
- ->paginate(10);
- }
- /**
- * 获取订单详情
- */
- public function getOrderDetail(int $userId, int $orderId): Order
- {
- $user = MemberUser::find($userId);
- return $user->orders()
- ->where('id', $orderId) // 需要添加订单ID条件
- ->with([
- 'coach.info:id,nickname,avatar,gender',
- 'records' => function ($query) {
- $query->orderBy('created_at', 'asc');
- },
- ])
- ->firstOrFail();
- }
- /**
- * 订单退款
- */
- public function refundOrder(int $orderId): array
- {
- // 使用 Auth::user() 获取用户对象
- $user = Auth::user();
- return DB::transaction(function () use ($orderId, $user) {
- // 查询并锁定订单
- $order = Order::where('id', $orderId)
- ->where('user_id', $user->id)
- ->where('state', 'pending')
- ->lockForUpdate()
- ->firstOrFail();
- // 更新订单状态
- $order->state = 'refunded';
- $order->save();
- // 添加订单记录
- OrderRecord::create([
- 'order_id' => $orderId,
- 'object_id' => $user->id,
- 'object_type' => 'user',
- 'state' => 'refund',
- 'remark' => '订单退款',
- ]);
- // 创建退款记录
- WalletRefundRecord::create([
- 'order_id' => $orderId,
- 'user_id' => $user->id,
- 'amount' => $order->total_amount,
- 'state' => 'success',
- ]);
- return ['message' => '退款成功'];
- });
- }
- /**
- * 获取代理商配置
- */
- public function getAgentConfig(int $agentId): array
- {
- $agent = AgentInfo::where('id', $agentId)
- ->where('state', 'enable')
- ->firstOrFail();
- // $config = AgentConfig::where('agent_id', $agentId)->firstOrFail();
- return [
- // 'min_distance' => $config->min_distance,
- // 'min_fee' => $config->min_fee,
- // 'per_km_fee' => $config->per_km_fee
- ];
- }
- /**
- * 获取技师配置
- */
- public function getCoachConfig(int $coachId): array
- {
- $coach = CoachUser::where('id', $coachId)
- ->where('state', 'enable')
- ->where('auth_state', 'passed')
- ->firstOrFail();
- // $config = CoachConfig::where('coach_id', $coachId)->firstOrFail();
- return [
- // 'delivery_fee_type' => $config->delivery_fee_type,
- // 'charge_delivery_fee' => $config->charge_delivery_fee
- ];
- }
- /**
- * 计算路费金额
- *
- * @param int $coachId 技师ID
- * @param int $projectId 项目ID
- * @param int|null $agentId 代理商ID
- * @param float $distance 距离(公里)
- * @return float 路费金额
- *
- * @throws Exception
- */
- public function calculateDeliveryFee(
- int $coachId,
- int $projectId,
- ?int $agentId,
- float $distance
- ): float {
- try {
- // 1. 校验技师
- $coach = CoachUser::where('state', 'enable')
- ->whereHas('info', fn ($q) => $q->where('state', 'approved'))
- ->whereHas('real', fn ($q) => $q->where('state', 'approved'))
- ->whereHas('qual', fn ($q) => $q->where('state', 'approved'))
- ->with(['projects' => fn ($q) => $q->where('project_id', $projectId)])
- ->find($coachId);
- abort_if(! $coach, 404, '技师不存在或状态异常');
- // 2. 校验技师项目
- $coachProject = $coach->projects->first();
- abort_if(! $coachProject, 404, '技师项目不存在');
- // 3. 判断是否免收路费
- if ($coachProject->traffic_fee_type == 'free') {
- return 0;
- }
- // 4. 获取路费配置
- $config = $this->getDeliveryFeeConfig($agentId);
- abort_if(! $config, 404, '路费配置不存在');
- // 5. 计算路费
- $fee = $this->calculateFee($distance, $config);
- // 6. 判断是否往返
- return $coachProject->delivery_fee_type == 'round_trip'
- ? bcmul($fee, '2', 2)
- : $fee;
- } catch (Exception $e) {
- Log::error(__CLASS__.'->'.__FUNCTION__.'计算路费失败:', [
- 'message' => $e->getMessage(),
- 'coach_id' => $coachId,
- 'project_id' => $projectId,
- 'agent_id' => $agentId,
- 'distance' => $distance,
- 'trace' => $e->getTraceAsString(),
- ]);
- throw $e;
- }
- }
- /**
- * 获取路费配置
- */
- private function getDeliveryFeeConfig(?int $agentId): ?object
- {
- // 优先获取代理商配置
- if ($agentId) {
- $agent = AgentInfo::where('state', 'enable')
- ->with(['projectConfig'])
- ->find($agentId);
- if ($agent && $agent->projectConfig) {
- return $agent->projectConfig;
- }
- }
- // 获取系统配置
- return SysConfig::where('key', 'delivery_fee')->first();
- }
- /**
- * 计算路费
- */
- private function calculateFee(float $distance, object $config): float
- {
- // 最小距离内按起步价计算
- if ($distance <= $config->min_distance) {
- return (float) $config->min_fee;
- }
- // 超出最小距离部分按每公里费用计算
- $extraDistance = bcsub($distance, $config->min_distance, 2);
- $extraFee = bcmul($extraDistance, $config->per_km_fee, 2);
- return bcadd($config->min_fee, $extraFee, 2);
- }
- /**
- * 计算订单金额
- *
- * @param int $userId 用户ID
- * @param int $addressId 地址ID
- * @param int $coachId 技师ID
- * @param int $projectId 项目ID
- * @param int $agentId 代理商ID
- * @param bool $useBalance 是否使用余额
- * @param float $distance 距离
- *
- * @throws Exception
- */
- public function calculateOrderAmount(
- int $userId,
- int $addressId,
- int $coachId,
- int $projectId,
- ?int $agentId = null,
- bool $useBalance = false,
- float $distance = 0
- ): array {
- try {
- // 1. 参数校验
- $user = MemberUser::find($userId);
- abort_if(! $user || $user->state != 'enable', 404, '用户不存在或状态异常');
- // 2. 查询技师项目
- $coach = $this->validateCoach($coachId);
- abort_if(! $coach, 404, '技师不存在或状态异常');
- $coachProject = $coach->projects()
- ->where('state', 'enable')
- ->where('project_id', $projectId)
- ->first();
- abort_if(! $coachProject, 404, '技师项目不存在');
- // 3. 查询基础项目
- $project = Project::where('id', $projectId)
- ->where('state', 'enable')
- ->first();
- abort_if(! $project, 404, '项目不存在或状态异常');
- // 4. 计算距离
- if ($distance <= 0) {
- $address = $user->addresses()->findOrFail($addressId);
- $coachService = app(CoachService::class);
- $coachDetail = $coachService->getCoachDetail($coachId, $address->latitude, $address->longitude);
- $distance = $coachDetail['distance'] ?? 0;
- }
- // 5. 获取项目价格
- $projectAmount = $this->getProjectPrice($project, $agentId, $projectId);
- // 6. 计算路费
- $deliveryFee = $this->calculateDeliveryFee($coachId, $projectId, $agentId, $distance);
- // 7. 计算优惠券金额
- $couponAmount = $this->calculateCouponAmount();
- // 8. 计算总金额
- $totalAmount = bcadd($projectAmount, $deliveryFee, 2);
- $totalAmount = bcsub($totalAmount, $couponAmount, 2);
- $totalAmount = max(0, $totalAmount);
- // 9. 计算余额支付金额
- $balanceAmount = 0;
- $payAmount = $totalAmount;
- if ($useBalance && $totalAmount > 0) {
- $wallet = $user->wallet;
- abort_if(! $wallet, 404, '用户钱包不存在');
- if ($wallet->available_balance >= $totalAmount) {
- $balanceAmount = $totalAmount;
- $payAmount = 0;
- } else {
- $balanceAmount = $wallet->available_balance;
- $payAmount = bcsub($totalAmount, $balanceAmount, 2);
- }
- }
- return [
- 'total_amount' => $totalAmount,
- 'balance_amount' => $balanceAmount,
- 'pay_amount' => $payAmount,
- 'coupon_amount' => $couponAmount,
- 'project_amount' => $projectAmount,
- 'delivery_fee' => $deliveryFee,
- ];
- } catch (Exception $e) {
- Log::error(__CLASS__.'->'.__FUNCTION__.'计算订单金额失败:', [
- 'message' => $e->getMessage(),
- 'user_id' => $userId,
- 'project_id' => $projectId,
- 'trace' => $e->getTraceAsString(),
- ]);
- throw $e;
- }
- }
- /**
- * 获取项目价格
- */
- private function getProjectPrice($project, ?int $agentId, int $projectId): float
- {
- $price = $project->price;
- if ($agentId) {
- $agent = AgentInfo::where('state', 'enable')->find($agentId);
- if ($agent) {
- $agentProject = $agent->projects()
- ->where('state', 'enable')
- ->where('project_id', $projectId)
- ->first();
- if ($agentProject) {
- $price = $agentProject->price;
- }
- }
- }
- return (float) $price;
- }
- /**
- * 计算优惠券金额
- */
- private function calculateCouponAmount(): float
- {
- $couponAmount = 0;
- if (request()->has('coupon_id')) {
- // TODO: 优惠券逻辑
- }
- return $couponAmount;
- }
- /**
- * 计算支付金额分配
- */
- private function calculatePaymentAmounts($user, float $totalAmount, bool $useBalance): array
- {
- $balanceAmount = 0;
- $payAmount = $totalAmount;
- if ($useBalance) {
- $wallet = $user->wallet;
- if (! $wallet) {
- throw new Exception('用户钱包不存在');
- }
- if ($wallet->available_balance >= $totalAmount) {
- $balanceAmount = $totalAmount;
- $payAmount = 0;
- } else {
- $balanceAmount = $wallet->available_balance;
- $payAmount = bcsub($totalAmount, $balanceAmount, 2);
- }
- }
- return [$balanceAmount, $payAmount];
- }
- /**
- * 指定技师
- */
- public function assignCoach(int $userId, int $orderId, int $coachId): bool
- {
- return DB::transaction(function () use ($userId, $orderId, $coachId) {
- try {
- // 1. 验证参数
- $order = $this->validateAssignOrder($userId, $orderId);
- // 2. 验证技师
- $coach = $this->validateCoach($coachId);
- // 3. 更新订单信息
- $this->updateOrderForAssign($order, $coachId);
- // 4. 创建订单记录(指派)
- $this->createAssignRecord($order, $userId);
- // 5. 处理支付
- if ($order->payment_type == 'balance') {
- $this->handleBalancePaymentForAssign($order, $userId, $coachId);
- }
- return true;
- } catch (Exception $e) {
- $this->logAssignCoachError($e, $userId, $orderId, $coachId);
- throw $e;
- }
- });
- }
- /**
- * 创建指派记录
- */
- private function createAssignRecord(Order $order, int $userId): void
- {
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => 'assigned',
- 'remark' => '指定技师',
- ]);
- }
- /**
- * 处理指派订单的余额支付
- */
- private function handleBalancePaymentForAssign(Order $order, int $userId, int $coachId): void
- {
- // 验证余额
- $user = MemberUser::find($userId);
- $wallet = $user->wallet;
- abort_if($wallet->available_balance < $order->balance_amount, 400, '可用余额不足');
- // 扣除余额
- $wallet->decrement('total_balance', $order->balance_amount);
- $wallet->decrement('available_balance', $order->balance_amount);
- // 更新订单状态
- $order->update(['state' => 'wait_service']);
- // 创建钱包支付记录
- WalletPaymentRecord::create([
- 'order_id' => $order->id,
- 'wallet_id' => $wallet->id,
- 'payment_no' => 'balance_'.$order->id,
- 'payment_method' => 'balance',
- 'total_amount' => $order->balance_amount,
- 'actual_amount' => 0,
- 'used_wallet_balance' => $order->balance_amount,
- 'used_recharge_balance' => 0,
- 'state' => 'success',
- ]);
- // 创建支付成功记录
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => 'pay',
- 'remark' => '余额支付成功',
- ]);
- // 创建接单记录
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_type' => CoachUser::class,
- 'object_id' => $coachId,
- 'state' => 'accepted',
- 'remark' => '抢单成功',
- ]);
- // 更新抢单记录
- $this->updateGrabRecords($order->id, $coachId);
- }
- /**
- * 验证指定技师的订单条件
- */
- private function validateAssignOrder(int $userId, int $orderId): Order
- {
- // 验证用户状态
- $user = MemberUser::where('id', $userId)
- ->where('state', 'enable')
- ->firstOrFail();
- // 验证订单状态
- $order = Order::where('user_id', $userId)
- ->where('id', $orderId)
- ->whereIn('state', ['wait_pay', 'wait_receive'])
- ->lockForUpdate()
- ->firstOrFail();
- return $order;
- }
- /**
- * 更新订单信息
- */
- private function updateOrderForAssign(Order $order, int $coachId): void
- {
- // 修改订单技师
- $order->coach_id = $coachId;
- // 待支付订单需要重新计算金额
- if ($order->state == 'wait_pay') {
- $amounts = $this->calculateOrderAmount(
- $order->user_id,
- $order->address_id,
- $coachId,
- $order->project_id,
- $order->agent_id,
- $order->payment_type === 'balance'
- );
- // 更新订单金额
- $order->total_amount = $amounts['total_amount'];
- $order->balance_amount = $amounts['balance_amount'];
- $order->pay_amount = $amounts['pay_amount'];
- $order->discount_amount = $amounts['coupon_amount'];
- $order->project_amount = $amounts['project_amount'];
- $order->traffic_amount = $amounts['delivery_fee'];
- }
- $order->save();
- }
- /**
- * 更新抢单记录
- */
- private function updateGrabRecords(int $orderId, int $coachId): void
- {
- OrderGrabRecord::where('order_id', $orderId)
- ->update([
- 'state' => 'success',
- 'coach_id' => $coachId,
- ]);
- }
- /**
- * 记录指派技师错误日志
- */
- private function logAssignCoachError(Exception $e, int $userId, int $orderId, int $coachId): void
- {
- Log::error('分配技师失败:', [
- 'message' => $e->getMessage(),
- 'user_id' => $userId,
- 'order_id' => $orderId,
- 'coach_id' => $coachId,
- ]);
- }
- }
|