12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514 |
- <?php
- namespace App\Services\Coach;
- use App\Models\Order;
- use App\Models\ShopInfo;
- use App\Models\CoachUser;
- use App\Enums\OrderStatus;
- use App\Models\MemberUser;
- use App\Enums\ProjectStatus;
- use App\Models\CoachProject;
- use App\Models\CoachLocation;
- use App\Models\CoachSchedule;
- use App\Models\CoachStatistic;
- use App\Enums\TechnicianStatus;
- use App\Models\CoachInfoRecord;
- use App\Models\OrderGrabRecord;
- use Illuminate\Support\Facades\DB;
- use App\Enums\TechnicianAuthStatus;
- use App\Enums\TechnicianWorkStatus;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Auth;
- use App\Enums\TechnicianLocationType;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\Redis;
- use App\Traits\LocationValidationTrait;
- class AccountService
- {
- use LocationValidationTrait;
- private const CACHE_KEY_PREFIX = 'coach_info_';
- private const CACHE_TTL = 300;
-
- public function submitBaseInfo($user, array $data)
- {
- return DB::transaction(function () use ($user, $data) {
-
- abort_if(!$user->coach, 404, '技师信息不存在');
-
-
- $pendingRecord = $this->hasPendingRecord($user->coach, 'info');
- abort_if($pendingRecord, 422, '已有待审核的基本信息记录');
-
-
- if (isset($data['life_photos'])) {
-
- $data['life_photos'] = json_encode(array_values($data['life_photos']));
- }
-
-
- $user->coach->infoRecords()->create(array_merge($data, [
- 'state' => TechnicianAuthStatus::AUDITING->value,
- ]));
-
-
- $this->clearCoachCache($user->coach->id);
- return ['message' => '基本信息提交成功'];
- });
- }
-
- 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;
- }
- }
-
- public function submitRealName($user, array $data)
- {
-
- DB::beginTransaction();
- try {
-
- abort_if(!$user->coach, 404, '技师信息不存在');
-
- $this->clearCoachCache($user->coach->id);
-
- $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);
- }
- );
- }
-
- public function getCoachDetail(): array
- {
- $coach = Auth::user()->coach->load([
- 'latestInfoRecord',
- 'latestRealRecord',
- 'latestQualRecord',
- 'commonLocation',
- 'shop',
- 'statistics',
- ]);
-
- $baseInfo = $this->formatBaseInfo($coach->latestInfoRecord);
-
- $orderStats = $this->getOrderStatistics($coach->id);
-
- $statistics = $this->formatStatistics($coach->statistics);
-
- $statistics = array_merge($orderStats, $statistics);
-
- $coachNo = str_pad($coach->id, 8, '0', STR_PAD_LEFT);
-
- $inviteCode = $this->generateInviteCode($coach->id);
-
- $wallet = $this->getWalletInfo($coach->id);
-
- $authStatus = $this->formatAuthStatus($coach);
-
- $location = $this->formatLocation($coach->commonLocation);
-
- $shop = $this->formatShop($coach->shop);
-
- return array_merge(
- [
- 'coach_no' => $coachNo,
- 'invite_code' => $inviteCode,
- 'wallet' => $wallet,
- ],
- $baseInfo,
- [
- 'state' => $coach->state,
- 'state_text' => TechnicianStatus::fromValue($coach->state)?->label(),
- 'work_status' => $coach->work_status,
- 'work_status_text' => TechnicianWorkStatus::fromValue($coach->work_status)?->label(),
- ],
- [
- 'auth_status' => $authStatus,
- 'location' => $location,
- 'shop' => $shop,
- 'statistics' => $statistics,
- ]
- );
- }
-
- private function formatAuthStatus(CoachUser $coach): array
- {
- return [
- 'base_info' => [
- 'state' => $coach->latestInfoRecord?->state,
- 'state_text' => TechnicianAuthStatus::fromValue($coach->latestInfoRecord?->state)?->label(),
- 'audit_remark' => $coach->latestInfoRecord?->audit_remark,
- 'updated_at' => $coach->latestInfoRecord?->updated_at?->format('Y-m-d H:i:s'),
- ],
- 'real_name' => [
- 'state' => $coach->latestRealRecord?->state,
- 'state_text' => TechnicianAuthStatus::fromValue($coach->latestRealRecord?->state)?->label(),
- 'audit_remark' => $coach->latestRealRecord?->audit_remark,
- 'updated_at' => $coach->latestRealRecord?->updated_at?->format('Y-m-d H:i:s'),
- ],
- 'qualification' => [
- 'state' => $coach->latestQualRecord?->state,
- 'state_text' => TechnicianAuthStatus::fromValue($coach->latestQualRecord?->state)?->label(),
- 'audit_remark' => $coach->latestQualRecord?->audit_remark,
- 'updated_at' => $coach->latestQualRecord?->updated_at?->format('Y-m-d H:i:s'),
- ],
- ];
- }
-
- private function formatLocation(?CoachLocation $location): ?array
- {
-
- if (!$location) {
- return null;
- }
-
- return [
- 'province' => $location->province,
- 'city' => $location->city,
- 'district' => $location->district,
- 'address' => $location->address,
- 'adcode' => $location->adcode,
- 'longitude' => $location->longitude,
- 'latitude' => $location->latitude,
- ];
- }
-
- private function formatShop(?ShopInfo $shop): ?array
- {
-
- if (!$shop) {
- return null;
- }
-
- return [
- 'id' => $shop->id,
- 'name' => $shop->name,
- 'address' => $shop->address,
- 'phone' => $shop->phone,
- ];
- }
-
- private function formatStatistics(?CoachStatistic $statistics): array
- {
- if (!$statistics) {
- return [
- 'level' => 1,
- 'level_text' => $this->getLevelText(1),
- 'rating' => 5.0,
- ];
- }
- return [
- 'level' => $statistics->level ?? 1,
- 'level_text' => $this->getLevelText($statistics->level ?? 1),
- 'rating' => $statistics->rating ?? 5.0,
- ];
- }
-
- 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,
- 'life_photos' => $info->life_photos ?? [],
- '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)
- {
-
- $qualTypeMap = [
- 1 => '初级按摩师',
- 2 => '中级按摩师',
- 3 => '高级按摩师',
- ];
-
- return [
- 'qual_type' => $qual->qual_type,
- 'qual_type_text' => $qualTypeMap[$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)
- {
- if (!$idCard) {
- return null;
- }
- return substr_replace($idCard, '****', 6, 8);
- }
-
- private function clearCoachCache($coachId)
- {
- Cache::forget(self::CACHE_KEY_PREFIX . $coachId);
- }
-
- public function setLocation($coachId, $latitude, $longitude, $type = TechnicianLocationType::COMMON->value, array $locationInfo = [])
- {
-
- return DB::transaction(function () use ($coachId, $latitude, $longitude, $type, $locationInfo) {
-
- $this->validateCoordinates($latitude, $longitude);
-
- $this->validateLocationType($type);
-
- $formattedLocation = $this->formatLocationInfo($locationInfo);
-
- $result = $this->updateLocationCache($coachId, $longitude, $latitude, $type);
-
- CoachLocation::updateOrCreate(
-
- ['coach_id' => $coachId, 'type' => $type],
-
- array_merge([
- 'latitude' => $latitude,
- 'longitude' => $longitude,
- ], $formattedLocation)
- );
- return $result;
- });
- }
-
- public function getLocation($user, int $type): array
- {
-
- $location = $this->getLocationByType($user->coach, $type);
-
- return $this->formatLocationResponse($location);
- }
-
- private function getLocationByType(CoachUser $coach, int $type): CoachLocation
- {
-
- $location = $coach->locations()
- ->where('type', $type)
- ->first();
- abort_if(!$location, 404, '位置信息不存在');
-
- return $location;
- }
-
- private function formatLocationResponse(CoachLocation $location): array
- {
- return [
- 'province' => $location->province,
- 'city' => $location->city,
- 'district' => $location->district,
- 'address' => $location->address,
- 'adcode' => $location->adcode,
- 'longitude' => $location->longitude,
- 'latitude' => $location->latitude,
- 'updated_at' => $location->updated_at->toDateTimeString(),
- ];
- }
-
- 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,
- ]
- );
-
- $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;
- }
-
- 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(),
- ]);
- }
- }
-
- public function updateWorkStatus(CoachUser $coach, int $status): array
- {
- DB::beginTransaction();
- try {
-
- $this->validateCoachStatus($coach);
-
- $status = (int)$status;
-
- $coach->work_status = $status;
- $coach->save();
-
- $this->updateWorkStatusCache($coach->id, $status);
- DB::commit();
-
- return [
- 'status' => true,
- 'message' => '状态更新成功',
- 'data' => [
- 'work_status' => $status,
- 'work_status_text' => TechnicianWorkStatus::fromValue($status)->label()
- ],
- ];
- } catch (\Exception $e) {
- DB::rollBack();
- throw $e;
- }
- }
-
- private function validateCoachStatus($coach): void
- {
-
- $baseInfo = $coach->info;
- abort_if(
- ! $baseInfo || (int)$baseInfo->state !== TechnicianAuthStatus::PASSED->value,
- 422,
- '基本信息未认证通过'
- );
-
- $qualification = $coach->qual;
- abort_if(
- ! $qualification || (int)$qualification->state !== TechnicianAuthStatus::PASSED->value,
- 422,
- '资质信息未认证通过'
- );
-
- $realName = $coach->real;
- abort_if(
- ! $realName || (int)$realName->state !== TechnicianAuthStatus::PASSED->value,
- 422,
- '实名信息未认证通过'
- );
- }
-
- 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(),
- ]);
-
- }
- }
-
- public function getWorkStatus(int $coachId): array
- {
- try {
-
- $coach = CoachUser::find($coachId);
- abort_if(! $coach, 404, '技师不存在');
-
- $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;
- }
- }
-
- 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;
- }
- }
-
- 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;
- }
-
- 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();
- }
-
- private function formatLocationInfo(array $locationInfo): array
- {
-
- $allowedFields = [
- 'province',
- 'city',
- 'district',
- 'address',
- 'adcode'
- ];
-
-
-
- $formatted = array_filter(
- array_intersect_key($locationInfo, array_flip($allowedFields)),
- function ($value) {
- return !is_null($value) && $value !== '';
- }
- );
-
- if (isset($formatted['adcode'])) {
- abort_if(!preg_match('/^\d{6}$/', $formatted['adcode']), 422, '无效的行政区划代码');
- }
- return $formatted;
- }
-
- private function updateLocationCache(int $coachId, float $longitude, float $latitude, int $type): bool
- {
-
- $key = $coachId . '_' . $type;
-
-
- return Redis::geoadd('coach_locations', $longitude, $latitude, $key);
- }
-
- private function getLatestBaseInfo(CoachUser $coach): CoachInfoRecord
- {
-
- $latestInfo = $coach->infoRecords()
- ->where('state', '<>', TechnicianAuthStatus::REJECTED->value)
- ->latest()
- ->first();
- abort_if(!$latestInfo, 404, '技师基本信息不存在');
- return $latestInfo;
- }
-
- private function generateInviteCode(int $coachId): string
- {
- return sprintf('C%d', $coachId);
- }
-
- private function getWalletInfo(int $coachId): array
- {
-
- $coach = CoachUser::with('wallet')->find($coachId);
-
- if (!$coach || !$coach->wallet) {
- return [
- 'total_balance' => 0,
- 'available_balance' => 0,
- 'frozen_amount' => 0,
- 'total_income' => 0,
- 'total_expense' => 0,
- ];
- }
-
- return [
- 'total_balance' => $coach->wallet->total_balance ?? 0,
- 'available_balance' => $coach->wallet->available_balance ?? 0,
- 'frozen_amount' => $coach->wallet->frozen_amount ?? 0,
- 'total_income' => $coach->wallet->total_income ?? 0,
- 'total_expense' => $coach->wallet->total_expense ?? 0,
- ];
- }
-
- public function updateBasicInfo(CoachUser $coach, array $data): array
- {
- return DB::transaction(function () use ($coach, $data) {
-
- $latestRecord = $coach->infoRecords()
- ->where('state', '<>', TechnicianAuthStatus::REJECTED->value)
- ->latest()
- ->first();
- abort_if(!$latestRecord, 404, '未找到有效的基础信息记录');
-
- if (isset($data['mobile'])) {
- $this->verifyMobileCode($data['mobile'], $data['code']);
- }
-
- $updateFields = array_intersect_key($data, [
- 'nickname' => '',
- 'gender' => '',
- 'mobile' => '',
- ]);
-
- abort_if(empty($updateFields), 422, '没有需要更新的字段');
-
- if ($latestRecord->state === TechnicianAuthStatus::AUDITING->value) {
- $latestRecord->update($updateFields);
- return [
- 'message' => '基础信息修改申请已更新',
- 'record_id' => $latestRecord->id,
- 'updated_fields' => array_keys($updateFields)
- ];
- }
-
- $newRecord = $coach->infoRecords()->create(array_merge([
- 'avatar' => $latestRecord->avatar,
- 'life_photos' => $latestRecord->life_photos,
- 'gender' => $latestRecord->gender,
- 'mobile' => $latestRecord->mobile,
- 'birthday' => $latestRecord->birthday,
- 'work_years' => $latestRecord->work_years,
- 'intention_city' => $latestRecord->intention_city,
- 'introduction' => $latestRecord->introduction,
- 'state' => TechnicianAuthStatus::AUDITING->value,
- ], $updateFields));
- return [
- 'message' => '基础信息修改申请已提交',
- 'record_id' => $newRecord->id,
- 'updated_fields' => array_keys($updateFields)
- ];
- });
- }
-
- private function verifyMobileCode(string $mobile, string $code): void
- {
-
- $cacheKey = "sms_code:update:{$mobile}";
-
- $cacheCode = Redis::get($cacheKey);
-
- abort_if(!$cacheCode || $cacheCode !== $code, 422, '验证码错误或已过期');
-
- Redis::del($cacheKey);
- }
-
- public function sendVerifyCode(array $data): array
- {
-
- $exists = MemberUser::where('mobile', $data['mobile'])
- ->whereHas('coach')
- ->exists();
- abort_if($exists, 422, '该手机号已被使用');
-
- $code = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
-
- $expireTime = 300;
-
- $cacheKey = "sms_code:{$data['type']}:{$data['mobile']}";
-
- Redis::setex($cacheKey, $expireTime, $code);
- return [
- 'code' => $code,
- 'mobile' => substr_replace($data['mobile'], '****', 3, 4),
- 'expire_time' => $expireTime
- ];
- }
-
- private function getLevelText(int $level): string
- {
-
- return match ($level) {
- 1 => '初级技师',
- 2 => '中级技师',
- 3 => '高级技师',
- default => '未知等级',
- };
- }
-
- public function getEnabledProjects(int $coachId): array
- {
-
- $projects = CoachProject::with(['project', 'project.category'])
- ->where('coach_id', $coachId)
- ->where('state', ProjectStatus::OPEN->value)
- ->get();
-
- $list = $projects->map(function ($item) {
- return [
- 'id' => $item->id,
- 'project_id' => $item->project_id,
- 'project_name' => $item->project?->name,
- 'category_id' => $item->project?->category_id,
- 'category_name' => $item->project?->category?->name,
- 'duration' => $item->project?->duration,
- 'price' => $item->project?->price,
- 'discount_amount' => $item->discount_amount,
- 'final_price' => $item->project?->price - $item->discount_amount,
- 'service_gender' => $item->service_gender,
- 'service_distance' => $item->service_distance,
- 'traffic_fee_type' => $item->traffic_fee_type,
- 'traffic_fee' => $item->traffic_fee,
- 'created_at' => $item->created_at?->format('Y-m-d H:i:s'),
- 'updated_at' => $item->updated_at?->format('Y-m-d H:i:s'),
- ];
- })->values()->all();
- return [
- 'total' => count($list),
- 'list' => $list
- ];
- }
-
- private function getOrderStatistics(int $coachId): array
- {
-
- $orderStats = Order::where('coach_id', $coachId)
- ->selectRaw('
- COUNT(*) as total_count,
- SUM(CASE WHEN state = ? THEN 1 ELSE 0 END) as completed_count,
- SUM(CASE WHEN state IN (?,?,?,?,?,?,?,?) THEN 1 ELSE 0 END) as pending_count,
- SUM(CASE WHEN state = ? THEN 1 ELSE 0 END) as carrying_count
- ', [
- OrderStatus::COMPLETED->value,
- OrderStatus::PAID->value,
- OrderStatus::ACCEPTED->value,
- OrderStatus::DEPARTED->value,
- OrderStatus::ARRIVED->value,
- OrderStatus::SERVICE_START->value,
- OrderStatus::SERVICING->value,
- OrderStatus::SERVICE_END->value,
- OrderStatus::LEAVING->value,
- OrderStatus::PAID->value
- ])
- ->first();
-
- $grabOrderCount = OrderGrabRecord::where('coach_id', $coachId)->count();
- return [
- 'order_count' => $orderStats->total_count ?? 0,
- 'completed_order_count' => $orderStats->completed_count ?? 0,
- 'pending_order_count' => $orderStats->pending_count ?? 0,
- 'carrying_order_count' => $orderStats->carrying_count ?? 0,
- 'grab_order_count' => $grabOrderCount,
- ];
- }
- }
|