123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949 |
- <?php
- namespace App\Services\Coach;
- use App\Models\CoachUser;
- use App\Enums\OrderStatus;
- use App\Models\MemberUser;
- use App\Models\CoachSchedule;
- use Illuminate\Support\Facades\DB;
- use App\Enums\TechnicianAuthStatus;
- use App\Enums\TechnicianWorkStatus;
- use Illuminate\Support\Facades\Log;
- use App\Enums\TechnicianLocationType;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\Redis;
- class AccountService
- {
- private const CACHE_KEY_PREFIX = 'coach_info_';
- private const CACHE_TTL = 300; // 5分钟
- /**
- * 提交技师基本信息
- * 包括个人基础资料的提交和审核
- *
- * 业务流程:
- * 1. 验证技师信息存在性
- * 2. 检查是否有待审核的记录
- * 3. 创建新的基本信息记录
- * 4. 清除相关缓存
- *
- * 注意事项:
- * - 同一时间只能有一条待审核记录
- * - 审核不通过可以重新提交
- * - 头像图片数据不限制格式
- * - 除性别和手机号外,其他字段均为可选
- * - 手机号会进行脱敏处理
- *
- * @param User $user 当前认证用户
- * @param array $data 基本信息数据,包含:
- * - nickname: string|null 昵称(可选)
- * - avatar: string|null 头像图片(可选)
- * - gender: string 性别(1:男 2:女)
- * - mobile: string 手机号
- * - birthday: string|null 出生日期(可选)
- * - work_years: int|null 工作年限(可选)
- * - intention_city: string|null 意向城市(可选)
- * - introduction: string|null 个人简介(可选)
- * @return array 返回结果
- * @throws \Exception 当验证失败或保存失败时抛出异常
- */
- public function submitBaseInfo($user, array $data)
- {
- DB::beginTransaction();
- try {
- // 验证技师信息是否存在
- abort_if(!$user->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();
- }
- }
|