coach, 404, '技师信息不存在'); // 检查是否有待审核的记录,避免重复提交 $pendingRecord = $this->hasPendingRecord($user->coach, 'info'); abort_if($pendingRecord, 422, '已有待审核的基本信息记录'); // 创建技师信息 $user->coach->infoRecords()->create(array_merge($data, [ 'state' => TechnicianAuthStatus::AUDITING->value, ])); // 清除技师信息缓存,确保数据一致性 $this->clearCoachCache($user->coach->id); // 提交事务 DB::commit(); // 返回成功结果 return ['message' => '基本信息提交成功']; } catch (\Exception $e) { // 发生异常时回滚事务 DB::rollBack(); throw $e; } } /** * 提交技师资质信息 * 包括资质证书照片、营业执照和健康证照片的提交和审核 * * 业务流程: * 1. 验证技师信息存在性 * 2. 检查是否有待审核的记录 * 3. 创建新的资质审核记录 * 4. 清除相关缓存 * * 注意事项: * - 同一时间只能有一条待审核记录 * - 审核不通过可以重新提交 * - 所有图片数据不限制格式 * * @param User $user 当前认证用户 * @param array $data 资质信息数据,包含: * - qual_type: string 资质类型(如:高级按摩师) * - qual_photo: string 资质证书照片 * - business_license: string 营业执照照片 * - health_cert: string 健康证照片 * @return array 返回结果,包含: * - message: string 提示信息 * - data: array 详细数据 * - record_id: int 记录ID * - state: int 状态值 * - state_text: string 状态文本 * @throws \Exception 当验证失败或保存失败时抛出异常 */ public function submitQualification($user, array $data) { // 开启数据库事务 DB::beginTransaction(); try { // 验证技师信息是否存在 abort_if(!$user->coach, 404, '技师信息不存在'); // 检查是否有待审核的记录,避免重复提交 $pendingRecord = $this->hasPendingRecord($user->coach, 'qual'); abort_if($pendingRecord, 422, '已有待审核的资质信息记录'); // 创建新的资质审核记录,设置为待审核状态 $record = $user->coach->qualRecords()->create(array_merge($data, [ 'state' => TechnicianAuthStatus::AUDITING->value, ])); // 清除技师信息缓存,确保数据一致性 $this->clearCoachCache($user->coach->id); // 提交事务 DB::commit(); // 返回成功结果 return [ 'message' => '资质信息提交成功', 'data' => [ 'record_id' => $record->id, 'state' => TechnicianAuthStatus::AUDITING->value, 'state_text' => TechnicianAuthStatus::fromValue(TechnicianAuthStatus::AUDITING->value)->label(), ] ]; } catch (\Exception $e) { // 发生异常时回滚事务 DB::rollBack(); throw $e; } } /** * 提交实名认证信息 * 包括姓名(可选)、身份证号(可选)和三张身份证照片的提交和审核 * * 业务流程: * 1. 验证技师信息存在性 * 2. 检查是否有待审核的记录 * 3. 创建新的实名认证记录 * 4. 清除相关缓存 * * 注意事项: * - 同一时间只能有一条待审核记录 * - 审核不通过可以重新提交 * - 所有图片数据不限制格式 * - 姓名和身份证号为可选字段 * - 敏感信息会进行脱敏处理 * * @param User $user 当前认证用户 * @param array $data 实名认证数据,包含: * - real_name: string|null 真实姓名(可选) * - id_card: string|null 身份证号(可选) * - id_card_front_photo: string 身份证正面照片 * - id_card_back_photo: string 身份证反面照片 * - id_card_hand_photo: string 手持身份证照片 * @return array 返回结果 * @throws \Exception 当验证失败或保存失败时抛出异常 */ public function submitRealName($user, array $data) { // 开启数据库事务 DB::beginTransaction(); try { // 验证技师信息是否存在 abort_if(!$user->coach, 404, '技师信息不存在'); // 检查是否有待审核的记录,避免重复提交 $pendingRecord = $this->hasPendingRecord($user->coach, 'real'); abort_if($pendingRecord, 422, '已有待审核的实名认证信息'); // 创建新的实名认证记录,设置为待审核状态 $user->coach->realRecords()->create(array_merge($data, [ 'state' => TechnicianAuthStatus::AUDITING->value, ])); // 清除技师信息缓存,确保数据一致性 $this->clearCoachCache($user->coach->id); // 提交事务 DB::commit(); // 返回成功结果 return ['message' => '实名认证信息提交成功']; } catch (\Exception $e) { // 发生异常时回滚事务 DB::rollBack(); throw $e; } } /** * 获取技师信息 */ public function getCoachInfo($user) { abort_if(! $user, 404, '用户不存在'); abort_if(! $user->coach, 404, '技师信息不存在'); return Cache::remember( self::CACHE_KEY_PREFIX . $user->coach->id, self::CACHE_TTL, function () use ($user) { return $this->fetchCoachInfo($user->coach); } ); } /** * 获取技师详细信息 */ private function fetchCoachInfo($coach) { $baseInfo = $coach->infoRecords()->latest()->first(); $qualification = $coach->qualRecords()->latest()->first(); $realName = $coach->realRecords()->latest()->first(); return [ 'base_info' => $baseInfo ? $this->formatBaseInfo($baseInfo) : null, 'qualification' => $qualification ? $this->formatQualification($qualification) : null, 'real_name' => $realName ? $this->formatRealName($realName) : null, ]; } /** * 格式化基本信息 */ private function formatBaseInfo($info) { return [ 'nickname' => $info->nickname, 'avatar' => $info->avatar, 'gender' => $info->gender, 'mobile' => $this->maskMobile($info->mobile), 'birthday' => $info->birthday, 'work_years' => $info->work_years, 'intention_city' => $info->intention_city, 'introduction' => $info->introduction, 'state' => $info->state, 'state_text' => TechnicianAuthStatus::fromValue($info->state)->label(), 'audit_remark' => $info->audit_remark, ]; } /** * 格式化资质信息 * * @param object $qual 资质记录对象 * @return array 格式化后的资质信息 */ private function formatQualification($qual) { return [ 'qual_type' => $qual->qual_type, 'qual_photo' => $qual->qual_photo, 'business_license' => $qual->business_license, 'health_cert' => $qual->health_cert, 'state' => $qual->state, 'state_text' => TechnicianAuthStatus::fromValue($qual->state)->label(), 'audit_remark' => $qual->audit_remark, ]; } /** * 格式化实名信息 */ private function formatRealName($real) { return [ 'real_name' => $real->real_name, 'id_card' => $this->maskIdCard($real->id_card), 'id_card_front_photo' => $real->id_card_front_photo, 'id_card_back_photo' => $real->id_card_back_photo, 'id_card_hand_photo' => $real->id_card_hand_photo, 'state' => $real->state, 'state_text' => TechnicianAuthStatus::fromValue($real->state)->label(), 'audit_remark' => $real->audit_remark, ]; } /** * 手机号脱敏 */ private function maskMobile($mobile) { return substr_replace($mobile, '****', 3, 4); } /** * 身份证脱敏 */ private function maskIdCard($idCard) { return substr_replace($idCard, '****', 6, 8); } /** * 清除技师信息缓存 */ private function clearCoachCache($coachId) { Cache::forget(self::CACHE_KEY_PREFIX . $coachId); } /** * 设置定位信息 * * @param int $coachId 技师ID * @param float $latitude 纬度 * @param float $longitude 经度 * @param int $type 位置类型 (current:1|common:2) * @return bool * * @throws \Exception */ public function setLocation($coachId, $latitude, $longitude, $type = TechnicianLocationType::COMMON->value) { DB::beginTransaction(); try { // 验证经纬度参数 if (! is_numeric($latitude) || ! is_numeric($longitude)) { throw new \Exception('无效的经纬度坐标'); } // 验证位置类型 if (! in_array($type, [TechnicianLocationType::CURRENT->value, TechnicianLocationType::COMMON->value])) { throw new \Exception('无效的位置类型'); } // 生成Redis键 $key = $coachId . '_' . $type; // 将置信息写入Redis $result = Redis::geoadd('coach_locations', $longitude, $latitude, $key); // 同时写入数据库保存历史记录 DB::table('coach_locations')->updateOrInsert( ['coach_id' => $coachId, 'type' => $type], [ 'latitude' => $latitude, 'longitude' => $longitude, 'updated_at' => now(), ] ); DB::commit(); Log::info('技师位置信息设置成功', [ 'coach_id' => $coachId, 'type' => $type, 'latitude' => $latitude, 'longitude' => $longitude, ]); return $result; } catch (\Exception $e) { DB::rollBack(); Log::error('技师位置信息设置异常', [ 'coach_id' => $coachId, 'latitude' => $latitude, 'longitude' => $longitude, 'type' => $type, 'error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), ]); throw $e; } } /** * 获取技师位置信息 * * @param int $userId 用户ID * @return array 位置信息 */ public function getLocation($userId) { try { // 改进:直接使用 coach 模型 $user = MemberUser::find($userId); abort_if(! $user, 404, '用户不存在'); abort_if(! $user->coach, 404, '技师信息不存在'); // 获取常用位置信息 $location = $user->coach->locations() ->where('type', TechnicianLocationType::COMMON->value) ->first(); $result = [ 'address' => $location ? $location->location : null, ]; // 记录日志 Log::info('获取技师常用位置信息成功', [ 'coach_id' => $user->coach->id, 'location' => $result, ]); return $result; } catch (\Exception $e) { Log::error('获取技师常用位置信息异常', [ 'coach_id' => $user->coach->id ?? null, 'error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), ]); throw $e; } } /** * 设置技师排班时间(每天通用) * * @param int $userId 技师用户ID * @param array $timeRanges 时间段数组 格式: [ * ['start_time' => '09:00', 'end_time' => '12:00'], * ['start_time' => '14:00', 'end_time' => '18:00'] * ] * * @throws \Exception */ public function setSchedule(int $userId, array $timeRanges): array { return DB::transaction(function () use ($userId, $timeRanges) { try { // 获取技师信息 $user = MemberUser::with(['coach'])->findOrFail($userId); $coach = $user->coach; abort_if(! $coach, 404, '技师信息不存在'); // 验证并排序时间段 $sortedRanges = $this->validateAndSortTimeRanges($timeRanges); // 创建或更新排班记录 $schedule = CoachSchedule::updateOrCreate( [ 'coach_id' => $coach->id, ], [ 'time_ranges' => json_encode($sortedRanges), 'state' => 1, ] ); // 更新Redis缓存 $this->updateScheduleCache($coach->id, $sortedRanges); // 记录日志 Log::info('技师排班设置成功', [ 'coach_id' => $coach->id, 'time_ranges' => $sortedRanges, ]); return [ 'status' => true, 'message' => '排班设置成功', 'data' => [ 'coach_id' => $coach->id, 'time_ranges' => $sortedRanges, 'updated_at' => $schedule->updated_at->toDateTimeString(), ], ]; } catch (\Exception $e) { Log::error('技师排班设置败', [ 'user_id' => $userId, 'time_ranges' => $timeRanges, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); throw $e; } }); } /** * 验证并排序时间段 */ private function validateAndSortTimeRanges(array $timeRanges): array { // 验证时间段数组 abort_if(empty($timeRanges), 400, '必须至少设置一个时间段'); // 验证每个时间段格式并转换为分钟数进行比较 $ranges = collect($timeRanges)->map(function ($range) { abort_if( ! isset($range['start_time'], $range['end_time']), 400, '时间段格式错误' ); // 验证时间格式 foreach (['start_time', 'end_time'] as $field) { abort_if( ! preg_match('/^([01][0-9]|2[0-3]):[0-5][0-9]$/', $range[$field]), 400, '时间格式错,应为HH:mm格式' ); } // 转换为分钟数便于比较 $startMinutes = $this->timeToMinutes($range['start_time']); $endMinutes = $this->timeToMinutes($range['end_time']); // 验证时间先后 abort_if( $startMinutes >= $endMinutes, 400, "时间段 {$range['start_time']}-{$range['end_time']} 结束时间必须大于开始时间" ); return [ 'start_time' => $range['start_time'], 'end_time' => $range['end_time'], 'start_minutes' => $startMinutes, 'end_minutes' => $endMinutes, ]; }) ->sortBy('start_minutes') ->values(); // 验证时间段是否重叠 $ranges->each(function ($range, $index) use ($ranges) { if ($index > 0) { $prevRange = $ranges[$index - 1]; abort_if( $range['start_minutes'] <= $prevRange['end_minutes'], 400, "时间段 {$prevRange['start_time']}-{$prevRange['end_time']} 和 " . "{$range['start_time']}-{$range['end_time']} 之间存在重叠" ); } }); // 返回排序后的时间,只保留需要的字段 return $ranges->map(function ($range) { return [ 'start_time' => $range['start_time'], 'end_time' => $range['end_time'], ]; })->toArray(); } /** * 将时间转换为分钟数 */ private function timeToMinutes(string $time): int { [$hours, $minutes] = explode(':', $time); return (int) $hours * 60 + (int) $minutes; } /** * 更新Redis缓存 */ private function updateScheduleCache(int $coachId, array $timeRanges): void { try { $cacheKey = "coach:schedule:{$coachId}"; $cacheData = [ 'updated_at' => now()->toDateTimeString(), 'time_ranges' => $timeRanges, ]; Redis::setex($cacheKey, 86400, json_encode($cacheData)); // 清除相关的可预约时间段缓存 $this->clearTimeSlotCache($coachId); } catch (\Exception $e) { Log::error('更新排班缓存失败', [ 'coach_id' => $coachId, 'error' => $e->getMessage(), ]); // 缓存更新失败不影响主流程 } } /** * 清除可预约时间段缓存 */ public function clearTimeSlotCache(int $coachId): void { try { $pattern = "coach:timeslots:{$coachId}:*"; $keys = Redis::keys($pattern); if (! empty($keys)) { Redis::del($keys); } } catch (\Exception $e) { Log::error('清除时间段缓存失败', [ 'coach_id' => $coachId, 'error' => $e->getMessage(), ]); } } /** * 更改技师工作状态 * * @param int $userId 用户ID * @param int $status 状态(1:休息中 2:工作中) */ public function updateWorkStatus(int $userId, int $status): array { DB::beginTransaction(); try { // 获取技师信息 $user = MemberUser::with(['coach', 'coach.infoRecords', 'coach.qualRecords', 'coach.realRecords']) ->findOrFail($userId); $coach = $user->coach; abort_if(! $coach, 404, '技师信息不存在'); // 验证状态值 abort_if(! in_array($status, [1, 2]), 400, '无效的状态值'); // 验证技师认证状态 $this->validateCoachStatus($coach); // 获取当前时间是否在排班时间内 $isInSchedule = $this->checkScheduleTime($coach->id); $currentStatus = $coach->work_status; $newStatus = $status; // 如果要切换到休息状态 if ($status === 1) { // 验证当前状态是否允许切换到休息 $this->validateRestStatus($currentStatus); $newStatus = TechnicianWorkStatus::REST->value; } // 如果要切换到工作状态 elseif ($status === 2) { // 验证是否在排班时间内 abort_if(! $isInSchedule, 422, '当前时间不在排班时间内,无法切换到工作状态'); // 检查是否有进行中的订单 $hasActiveOrder = $coach->orders() ->whereIn('state', [ OrderStatus::ACCEPTED->value, // 已接单 OrderStatus::DEPARTED->value, // 已出发 OrderStatus::ARRIVED->value, // 已到达 OrderStatus::SERVING->value, // 服务中 ]) ->exists(); // 根据是否有进行中订单决定状态 $newStatus = $hasActiveOrder ? TechnicianWorkStatus::BUSY->value : TechnicianWorkStatus::FREE->value; } // 如果状态没有变,则不需要更新 if ($currentStatus === $newStatus) { DB::rollBack(); return [ 'status' => true, 'message' => '状态未发生变化', 'data' => [ 'work_status' => $newStatus, 'work_status_text' => TechnicianWorkStatus::fromValue($newStatus)->label(), 'updated_at' => now()->toDateTimeString(), ], ]; } // 更新状态 $coach->work_status = $newStatus; $coach->save(); // 更新Redis缓存 $this->updateWorkStatusCache($coach->id, $newStatus); DB::commit(); // 记录日志 Log::info('技师工作状态更新成功', [ 'coach_id' => $coach->id, 'old_status' => $currentStatus, 'new_status' => $newStatus, 'updated_at' => now()->toDateTimeString(), 'in_schedule' => $isInSchedule, ]); return [ 'status' => true, 'message' => '状态更新成功', 'data' => [ 'work_status' => $newStatus, 'work_status_text' => TechnicianWorkStatus::fromValue($newStatus)->label(), 'updated_at' => now()->toDateTimeString(), ], ]; } catch (\Exception $e) { DB::rollBack(); Log::error('技师工作状态更新失败', [ 'user_id' => $userId, 'status' => $status, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); throw $e; } } /** * 验证技师认证状态 */ private function validateCoachStatus($coach): void { // 验证基本信息认证 $baseInfo = $coach->info; abort_if( ! $baseInfo || $baseInfo->state !== TechnicianAuthStatus::PASSED->value, 422, '基本信息未认证通过' ); // 验证资质认证 $qualification = $coach->qual; abort_if( ! $qualification || $qualification->state !== TechnicianAuthStatus::PASSED->value, 422, '资质信息未认证通过' ); // 验证实名认证 $realName = $coach->real; abort_if( ! $realName || $realName->state !== TechnicianAuthStatus::PASSED->value, 422, '实名信息未认证通过' ); } /** * 验证是否可以切换到休息状态 */ private function validateRestStatus(int $currentStatus): void { // 只有在空闲或忙碌状态下才能更改为休息状态 abort_if(! in_array($currentStatus, [ TechnicianWorkStatus::FREE->value, TechnicianWorkStatus::BUSY->value, ]), 422, '当前状态不能更改为休息状态'); } /** * 检查当前时间是否在排班时间内 */ private function checkScheduleTime(int $coachId): bool { try { $schedule = CoachSchedule::where('coach_id', $coachId) ->where('state', 1) ->first(); if (! $schedule) { return false; } $timeRanges = json_decode($schedule->time_ranges, true); if (empty($timeRanges)) { return false; } $currentTime = now()->format('H:i'); foreach ($timeRanges as $range) { if ($currentTime >= $range['start_time'] && $currentTime <= $range['end_time']) { return true; } } return false; } catch (\Exception $e) { Log::error('检查排班时间异常', [ 'coach_id' => $coachId, 'error' => $e->getMessage(), ]); return false; } } /** * 更新工作状态缓存 */ private function updateWorkStatusCache(int $coachId, int $status): void { try { $cacheKey = "coach:work_status:{$coachId}"; $cacheData = [ 'status' => $status, 'updated_at' => now()->toDateTimeString(), ]; Redis::setex($cacheKey, 86400, json_encode($cacheData)); } catch (\Exception $e) { Log::error('更新工作状态缓存失败', [ 'coach_id' => $coachId, 'error' => $e->getMessage(), ]); // 缓存更新失败不影响主流程 } } /** * 获取技师工作状态 * * @param int $coachId 技师ID */ public function getWorkStatus(int $coachId): array { try { // 验证技师信息 $coach = CoachUser::find($coachId); abort_if(! $coach, 404, '技师不存在'); // 直接获取技师信息里的work_status $workStatus = $coach->work_status; return [ 'work_status' => $workStatus, 'work_status_text' => TechnicianWorkStatus::fromValue($workStatus)->label(), 'updated_at' => now()->toDateTimeString(), ]; } catch (\Exception $e) { Log::error('获取技师工作状态失败', [ 'coach_id' => $coachId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); throw $e; } } /** * 获取技师排班信息 * * @param int $userId 用户ID */ public function getSchedule(int $userId): array { try { // 获取技师信息 $user = MemberUser::with(['coach'])->findOrFail($userId); $coach = $user->coach; abort_if(! $coach, 404, '技师信息不存在'); // 先尝试从缓存获取 $cacheKey = "coach:schedule:{$coach->id}"; $cached = Redis::get($cacheKey); if ($cached) { return json_decode($cached, true); } // 缓存不存在,从数据库获取 $schedule = CoachSchedule::where('coach_id', $coach->id) ->where('state', 1) ->first(); $result = [ 'time_ranges' => $schedule ? json_decode($schedule->time_ranges, true) : [], 'updated_at' => $schedule ? $schedule->updated_at->toDateTimeString() : now()->toDateTimeString(), ]; // 写入缓存 Redis::setex($cacheKey, 86400, json_encode($result)); // 记录日志 Log::info('获取技师排班信息成功', [ 'coach_id' => $coach->id, 'schedule' => $result, ]); return $result; } catch (\Exception $e) { Log::error('获取技师排班信息失败', [ 'user_id' => $userId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); throw $e; } } /** * 验证技师基础信息 * * @param User $user 用户对象 * @param bool $throwError 是否抛出异常 * @return bool */ private function validateBasicCoach($user, bool $throwError = true): bool { if (!$user || !$user->coach) { if ($throwError) { abort_if(!$user, 404, '用户不存在'); abort_if(!$user->coach, 404, '技师信息不存在'); } return false; } return true; } /** * 检查是否存在审核记录 * * @param CoachUser $coach 技师象 * @param string $type 记录类型(info|qual|real) * @return bool */ private function hasPendingRecord($coach, string $type): bool { $method = match ($type) { 'info' => 'infoRecords', 'qual' => 'qualRecords', 'real' => 'realRecords', default => throw new \InvalidArgumentException('Invalid record type') }; return $coach->{$method}() ->where('state', TechnicianAuthStatus::AUDITING->value) ->exists(); } }