123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795 |
- <?php
- namespace App\Services\Coach;
- use App\Enums\OrderStatus;
- use App\Enums\TechnicianAuthStatus;
- use App\Enums\TechnicianLocationType;
- use App\Enums\TechnicianWorkStatus;
- use App\Models\CoachSchedule;
- use App\Models\MemberUser;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Redis;
- class AccountService
- {
- private const CACHE_KEY_PREFIX = 'coach_info_';
- private const CACHE_TTL = 300; // 5分钟
- /**
- * 提交技师基本信息
- */
- public function submitBaseInfo($user, array $data)
- {
- DB::beginTransaction();
- try {
- $this->setTransactionConfig();
- abort_if(! $user->coach, 404, '技师信息不存在');
- // 检查是否有待审核的记录
- $pendingRecord = $user->coach->infoRecords()
- ->where('state', TechnicianAuthStatus::AUDITING->value)
- ->exists();
- abort_if($pendingRecord, 422, '已有待审核的基本信息记录');
- // 创建技师信息
- $record = $user->coach->infoRecords()->create(array_merge($data, [
- 'state' => TechnicianAuthStatus::AUDITING->value,
- ]));
- // 清除技师信息缓存
- $this->clearCoachCache($user->coach->id);
- DB::commit();
- $this->logInfo('技师提交基本信息成功', $user, $data);
- return ['message' => '基本信息提交成功'];
- } catch (\Exception $e) {
- DB::rollBack();
- $this->logError('提交技师基本信息失败', $user, $data, $e);
- throw $e;
- }
- }
- /**
- * 提交技师资质信息
- */
- public function submitQualification($user, array $data)
- {
- DB::beginTransaction();
- try {
- $this->setTransactionConfig();
- abort_if(! $user->coach, 404, '技师信息不存在');
- // 检查是否有待审核的记录
- $pendingRecord = $user->coach->qualRecords()
- ->where('state', TechnicianAuthStatus::AUDITING->value)
- ->exists();
- abort_if($pendingRecord, 422, '已有待审核的资质信息记录');
- // 创建资质信息
- $record = $user->coach->qualRecords()->create(array_merge($data, [
- 'state' => TechnicianAuthStatus::AUDITING->value,
- ]));
- // 清除技师信息缓存
- $this->clearCoachCache($user->coach->id);
- DB::commit();
- $this->logInfo('技师提交资质信息成功', $user, $data);
- return ['message' => '资质信息提交成功'];
- } catch (\Exception $e) {
- DB::rollBack();
- $this->logError('提交技师资质信息失败', $user, $data, $e);
- throw $e;
- }
- }
- /**
- * 提交实名认证信息
- */
- public function submitRealName($user, array $data)
- {
- DB::beginTransaction();
- try {
- $this->setTransactionConfig();
- abort_if(! $user->coach, 404, '技师信息不存在');
- // 检查是否有待审核的记录
- $pendingRecord = $user->coach->realRecords()
- ->where('state', TechnicianAuthStatus::AUDITING->value)
- ->exists();
- abort_if($pendingRecord, 422, '已有待审核的实名认证信息');
- // 创建实名认证信息
- $record = $user->coach->realRecords()->create(array_merge($data, [
- 'state' => TechnicianAuthStatus::AUDITING->value,
- ]));
- // 清除技师信息缓存
- $this->clearCoachCache($user->coach->id);
- DB::commit();
- $this->logInfo('技师提交实名认证信息成功', $user, $this->maskSensitiveData($data));
- return ['message' => '实名认证信息提交成功'];
- } catch (\Exception $e) {
- DB::rollBack();
- $this->logError('提交实名认证信息失败', $user, $this->maskSensitiveData($data), $e);
- throw $e;
- }
- }
- /**
- * 获取技师信息
- */
- public function getCoachInfo($user)
- {
- try {
- 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);
- }
- );
- } catch (\Exception $e) {
- $this->logError('获取技师信息失败', $user, [], $e);
- throw $e;
- }
- }
- /**
- * 设置事务配置
- */
- private function setTransactionConfig()
- {
- DB::statement('SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED');
- DB::statement('SET SESSION innodb_lock_wait_timeout=10');
- }
- /**
- * 记录信息日志
- */
- private function logInfo(string $message, $user, array $data)
- {
- Log::info($message, [
- 'user_id' => $user->id,
- 'coach_id' => $user->coach->id,
- 'data' => $data,
- 'ip' => request()->ip(),
- 'timestamp' => now()->toDateTimeString(),
- ]);
- }
- /**
- * 记录错误日志
- */
- private function logError(string $message, $user, array $data, \Exception $e)
- {
- Log::error($message, [
- 'user_id' => $user->id,
- 'coach_id' => $user->coach->id ?? null,
- 'data' => $data,
- 'error' => $e->getMessage(),
- 'file' => $e->getFile(),
- 'line' => $e->getLine(),
- 'ip' => request()->ip(),
- 'timestamp' => now()->toDateTimeString(),
- ]);
- }
- /**
- * 获取技师详细信息
- */
- 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,
- ];
- }
- /**
- * 格式化资质信息
- */
- private function formatQualification($qual)
- {
- return [
- 'qual_type' => $qual->qual_type,
- 'qual_no' => $qual->qual_no,
- 'qual_photo' => $qual->qual_photo,
- 'valid_start' => $qual->valid_start,
- 'valid_end' => $qual->valid_end,
- '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 maskSensitiveData(array $data)
- {
- if (isset($data['id_card'])) {
- $data['id_card'] = $this->maskIdCard($data['id_card']);
- }
- if (isset($data['mobile'])) {
- $data['mobile'] = $this->maskMobile($data['mobile']);
- }
- return $data;
- }
- /**
- * 清除技师信息缓存
- */
- 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(),
- ]);
- // 缓存更新失败不影响主流程
- }
- }
- }
|