12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571 |
- <?php
- namespace App\Services\Coach;
- 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 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; // 5分钟
- /**
- * 提交技师基本信息
- * 包括个人基础资料的提交和审核
- *
- * 业务流程:
- * 1. 验证技师信息存在性
- * 2. 检查是否有待审核的记录
- * 3. 处理生活照片数据
- * 4. 创建新的基本信息记录
- * 5. 清除相关缓存
- *
- * 注意事项:
- * - 同一时间只能有一条待审核记录
- * - 审核不通过可以重新提交
- * - 头像和生活照片不限制格式
- * - 除性别和手机号外,其他字段均为可选
- * - 手机号会进行脱敏处理
- *
- * @param User $user 当前认证用户
- * @param array $data 基本信息数据,包含:
- * - nickname: string|null 昵称(可选)
- * - avatar: string|null 头像图片(可选)
- * - life_photos: array|null 生活照片数组(可选)
- * - gender: string 性别(1:男 2:女)
- * - mobile: string 手机号
- * - birthday: string|null 出生日期(可选)
- * - work_years: int|null 工作年限(可选)
- * - intention_city: string|null 意向城市(可选)
- * - introduction: string|null 个人简介(可选)
- * @return array 返回结果,包含:
- * - message: string 提示信息
- * @throws \Exception 当验证失败或保存失败时抛出异常
- */
- public function submitBaseInfo($user, array $data)
- {
- return DB::transaction(function () use ($user, $data) {
- // 验证技师信息是否存在,不存在则抛出404异常
- abort_if(!$user->coach, 404, '技师信息不存在');
- // 检查是否有待审核的记录,避免重复提交
- // 如果存在待审核记录,则抛出422异常
- $pendingRecord = $this->hasPendingRecord($user->coach, 'info');
- abort_if($pendingRecord, 422, '已有待审核的基本信息记录');
- // 处理生活照片数据:将数组转换为JSON格式存储
- // 如果没有生活照片数据,则保持原样
- if (isset($data['life_photos'])) {
- // 使用array_values确保数组索引连续
- $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' => '基本信息提交成功'];
- });
- }
- /**
- * 提交技师资质信息
- * 包括资质证书照片、营业执照和健康证照片的提交和审核
- *
- * 业务流程:
- * 1. 验证技师信息存在性
- * 2. 检查是否有待审核的记录
- * 3. 创建新的资质审核记录
- * 4. 清除相关缓存
- *
- * 注意事项:
- * - 同一时间只能有一条待审核记录
- * - 审核不通过可以重新提交
- * - 所有图片数据不限制格式
- *
- * @param User $user 当前认证用户
- * @param array $data 资质信息数据,包含:
- * - qual_type: int 资质类型(1:初级 2:中级 3:高级)
- * - 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, '技师信息不存在');
- // TODO: 临时清除技师信息,便于对接调试
- $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;
- }
- }
- /**
- * 获取技师信息
- * 包括基本信息、资质信息和实名认证信息
- *
- * 业务流程:
- * 1. 验证用户和技师信息存在性
- * 2. 尝试从缓存获取数据
- * 3. 如果缓存不存在,从数据库获取并缓存
- *
- * 注意事项:
- * - 所有图片数据不限制格式
- * - 敏感信息会进行脱敏处理
- * - 使用缓存提高性能
- *
- * @param User $user 当前认证用户
- * @return array 返回技师所有信息,包含:
- * - base_info: array|null 基本信息
- * - qualification: array|null 资质信息
- * - real_name: array|null 实名认证信息
- * @throws \Exception 当验证失败时抛出异常
- */
- 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);
- }
- );
- }
- /**
- * 获取技师详细信息
- *
- * 业务逻辑:
- * 1. 获取技师最新基本信息(不包括审核拒绝的记录)
- * 2. 获取技师邀请码信息
- * 3. 获取钱包信息
- * 4. 获取审核状态信息
- * 5. 获取位置和店铺信息
- * 6. 获取统计数据
- * 7. 组装返回数据
- *
- * @return array 技师详细信息
- * @throws \Exception 获取信息失败时抛出异常
- */
- public function getCoachDetail(): array
- {
- // 获取技师信息并预加载关联,避免 N+1 问题
- $coach = Auth::user()->coach->load([
- 'latestInfoRecord',
- 'latestRealRecord',
- 'latestQualRecord',
- 'commonLocation',
- 'shop',
- 'statistics',
- ]);
- // 获取基本信息
- $baseInfo = $this->formatBaseInfo($coach->latestInfoRecord);
- // 生成技师工号
- $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);
- // 获取统计信息
- $statistics = $this->formatStatistics($coach->statistics);
- // 组装返回数据
- return array_merge(
- [
- 'coach_no' => $coachNo,
- 'invite_code' => $inviteCode,
- 'wallet' => $wallet,
- ],
- $baseInfo,
- [
- 'state' => $coach->state,
- 'state_text' => TechnicianStatus::fromValue($coach->state)?->label(),
- ],
- [
- 'auth_status' => $authStatus,
- 'location' => $location,
- 'shop' => $shop,
- 'statistics' => $statistics,
- ]
- );
- }
- /**
- * 格式化审核状态信息
- * 包含基本信息、实名认证和资质认证的审核状态
- *
- * 业务逻辑:
- * 1. 获取最新的基本信息审核状态
- * 2. 获取最新的实名认证审核状态
- * 3. 获取最新的资质认证审核状态
- * 4. 格式化状态文本和时间
- *
- * @param CoachUser $coach 技师对象
- * @return array 审核状态信息
- */
- 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'),
- ],
- ];
- }
- /**
- * 格式化位置信息
- * 处理技师的常用位置信息
- *
- * 业务逻辑:
- * 1. 检查位置信息是否存在
- * 2. 格式化地理位置信息
- * 3. 格式化行政区划信息
- *
- * @param CoachLocation|null $location 位置对象
- * @return array|null 格式化后的位置信息
- */
- private function formatLocation(?CoachLocation $location): ?array
- {
- // 如果没有位置信息,返回null
- 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, // 纬度
- ];
- }
- /**
- * 格式化店铺信息
- * 处理技师所属店铺的基本信息
- *
- * 业务逻辑:
- * 1. 检查店铺信息是否存在
- * 2. 格式化店铺基本信息
- * 3. 格式化联系信息
- *
- * @param ShopInfo|null $shop 店铺对象
- * @return array|null 格式化后的店铺信息
- */
- private function formatShop(?ShopInfo $shop): ?array
- {
- // 如果没有店铺信息,返回null
- if (!$shop) {
- return null;
- }
- // 返回格式化的店铺信息
- return [
- 'id' => $shop->id, // 店铺ID
- 'name' => $shop->name, // 店铺名称
- 'address' => $shop->address, // 店铺地址
- 'phone' => $shop->phone, // 联系电话
- ];
- }
- /**
- * 格式化统计信息
- * 处理技师的订单统计和等级信息
- *
- * 业务逻辑:
- * 1. 获取订单相关统计数据
- * 2. 获取技师等级信息
- * 3. 获取评分信息
- * 4. 处理默认值
- *
- * @param CoachStatistic|null $statistics 统计对象
- * @return array 格式化后的统计信息
- */
- private function formatStatistics(?CoachStatistic $statistics): array
- {
- return [
- 'order_count' => $statistics?->order_count ?? 0, // 总订单数
- 'completed_order_count' => $statistics?->completed_order_count ?? 0, // 已完成订单数
- 'level' => $statistics?->level ?? 1, // 技师等级
- 'level_text' => $this->getLevelText($statistics?->level ?? 1), // 等级文本
- 'rating' => $statistics?->rating ?? 5.0, // 评分
- ];
- }
- /**
- * 获取技师详细信息
- * 从数据库获取最新的认证记录信息
- *
- * @param CoachUser $coach 技师对象
- * @return array 格式化后的技师信息
- */
- 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,
- ];
- }
- /**
- * 格式化基本信息
- * 处理技师基本信息的展示格式
- *
- * @param object $info 基本信息记录对象
- * @return array 格式化后的基本信息
- */
- 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,
- ];
- }
- /**
- * 格式化资质信息
- * 处理技师资质信息的展示格式
- *
- * @param object $qual 资质记录对象
- * @return array 格式化后的资质信息
- */
- 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,
- ];
- }
- /**
- * 格式化实名信息
- * 处理技师实名认证信息的展示格式
- *
- * @param object $real 实名认证记录对象
- * @return array 格式化后的实名信息
- */
- 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,
- ];
- }
- /**
- * 手机号脱敏
- * 将手机号中间4位替换为****
- *
- * @param string $mobile 原始手机号
- * @return string 脱敏后的手机号
- */
- private function maskMobile($mobile)
- {
- return substr_replace($mobile, '****', 3, 4);
- }
- /**
- * 身份证号脱敏
- * 将身份证号中间8位替换为****
- *
- * @param string|null $idCard 原始身份证号
- * @return string|null 脱敏后的身份证号
- */
- 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);
- }
- /**
- * 设置定位信息
- * 支持设置当前位置和常用位置,包含地理位置和行政区划信息
- *
- * 业务流程:
- * 1. 验证经纬度参数
- * 2. 验证位置类型
- * 3. 保存到Redis的地理位置数据结构
- * 4. 同步保存到据库
- *
- * @param int $coachId 技师ID
- * @param float $latitude 纬度
- * @param float $longitude 经度
- * @param int $type 位置类型 (current:1|common:2)
- * @param array $locationInfo 位置信息,包含:
- * - province: string|null 省份
- * - city: string|null 城市
- * - district: string|null 区县
- * - address: string|null 详细地址
- * - adcode: string|null 行政区划代码
- * @return bool 返回缓存更新结果
- * @throws \Exception 当验证失败或保存失败时抛出异常
- */
- public function setLocation($coachId, $latitude, $longitude, $type = TechnicianLocationType::COMMON->value, array $locationInfo = [])
- {
- // 使用事务确保一致性
- return DB::transaction(function () use ($coachId, $latitude, $longitude, $type, $locationInfo) {
- // 验证经纬度的有效性(-90≤纬度≤90,-180≤经度≤180)
- $this->validateCoordinates($latitude, $longitude);
- // 验证位置类型是否为有效值(1:当前位置 2:常用位置)
- $this->validateLocationType($type);
- // 格式化并验证位置信息(省市区、地址、行政区划代码)
- $formattedLocation = $this->formatLocationInfo($locationInfo);
- // 更新Redis地理位置缓存,用于实时位置查询
- $result = $this->updateLocationCache($coachId, $longitude, $latitude, $type);
- // 同步更新数据库,保存历史位置记录
- CoachLocation::updateOrCreate(
- // 查询条件:根据技师ID和位置类型确定唯一记录
- ['coach_id' => $coachId, 'type' => $type],
- // 更新数据:合并基础位置信息和格式化后的地址信息
- array_merge([
- 'latitude' => $latitude,
- 'longitude' => $longitude,
- ], $formattedLocation)
- );
- return $result;
- });
- }
- /**
- * 获取技师位置信息
- *
- * 业务流程:
- * 1. 获取指定类型的位置记录
- * 2. 返回格式化的位置数据
- *
- * @param User $user 认证用户
- * @param int $type 位置类型 (1:当前位置 2:常用位置)
- * @return array 位置信息,包含:
- * - province: string 省份
- * - city: string 城市
- * - district: string 区县
- * - address: string 详细地址
- * - adcode: string 行政区划代码
- * - longitude: float 经度
- * - latitude: float 纬度
- * - updated_at: string 更新时间
- */
- public function getLocation($user, int $type): array
- {
- // 获取指定类型的位置记录
- $location = $this->getLocationByType($user->coach, $type);
- // 返回格式化的位置数据
- return $this->formatLocationResponse($location);
- }
- /**
- * 根据类型获取技师位置记录
- *
- * @param CoachUser $coach 技师对象
- * @param int $type 位置类型 (1:当前位置 2:常用位置)
- * @return CoachLocation 位置信息
- * @throws \Illuminate\Http\Exceptions\HttpResponseException 当位置信息不存在时抛出404异常
- */
- private function getLocationByType(CoachUser $coach, int $type): CoachLocation
- {
- // 获取指定类型的位置记录
- $location = $coach->locations()
- ->where('type', $type)
- ->first();
- abort_if(!$location, 404, '位置信息不存在');
- // 返回位置数据
- return $location;
- }
- /**
- * 格式化位置响应数据
- *
- * @param CoachLocation $location 位置记录
- * @return array 格式化后的位置信息,包含:
- * - province: string 省份
- * - city: string 城市
- * - district: string 区县
- * - address: string 详细地址
- * - adcode: string 行政区划代码
- * - longitude: float 经度
- * - latitude: float 纬度
- * - updated_at: string 更新时间
- */
- 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(), // 更新时间
- ];
- }
- /**
- * 设置技师排班时间(每天通用)
- *
- * @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();
- }
- /**
- * 格式化位置信息
- * 过滤和验证位置相关字段
- *
- * @param array $locationInfo 原始位置信息
- * @return array 格式化后的位置信息
- * @throws \Exception 当行政区划代码格式无效时抛出异常
- */
- private function formatLocationInfo(array $locationInfo): array
- {
- // 定义允许的字段列表,确保数据安全性
- $allowedFields = [
- 'province', // 省份
- 'city', // 城市
- 'district', // 区县
- 'address', // 详细地址
- 'adcode' // 行政区划代码
- ];
- // 过滤并验证字段:
- // 1. 只保留允许的字段
- // 2. 移除空值
- $formatted = array_filter(
- array_intersect_key($locationInfo, array_flip($allowedFields)),
- function ($value) {
- return !is_null($value) && $value !== '';
- }
- );
- // 验证行政区划代码格式(6位数字)
- if (isset($formatted['adcode'])) {
- abort_if(!preg_match('/^\d{6}$/', $formatted['adcode']), 422, '无效的行政区划代码');
- }
- return $formatted;
- }
- /**
- * 更新位置缓存
- * 处理Redis地理位置数据结构的更新
- * 使用Redis的GEOADD命令存储地理位置信息
- *
- * @param int $coachId 技师ID
- * @param float $longitude 经度
- * @param float $latitude 纬度
- * @param int $type 位置类型
- * @return bool 操作是否成功
- */
- private function updateLocationCache(int $coachId, float $longitude, float $latitude, int $type): bool
- {
- // 生成缓存键:技师ID_位置类型
- $key = $coachId . '_' . $type;
- // 使用Redis的GEOADD命令添加地理位置信息
- // 参数顺序:key longitude latitude member
- return Redis::geoadd('coach_locations', $longitude, $latitude, $key);
- }
- /**
- * 获取技师最新基本信息
- *
- * @param CoachUser $coach 技师对象
- * @return CoachInfoRecord 最新的基本信息记录
- * @throws \Illuminate\Http\Exceptions\HttpResponseException 当信息不存在时抛出404异常
- */
- private function getLatestBaseInfo(CoachUser $coach): CoachInfoRecord
- {
- // 获取最新的技师信息记录(排除审核拒绝的记录)
- $latestInfo = $coach->infoRecords()
- ->where('state', '<>', TechnicianAuthStatus::REJECTED->value)
- ->latest()
- ->first();
- abort_if(!$latestInfo, 404, '技师基本信息不存在');
- return $latestInfo;
- }
- /**
- * 生成技师邀请码
- *
- * @param int $coachId 技师ID
- * @return string 邀请码
- */
- private function generateInviteCode(int $coachId): string
- {
- return sprintf('C%d', $coachId);
- }
- /**
- * 获取技师钱包信息
- *
- * 业务逻辑:
- * 1. 获取技师钱包关联数据
- * 2. 如果钱包不存在,返回默认值
- * 3. 返回钱包概况数据
- *
- * @param int $coachId 技师ID
- * @return array 钱包概况信息
- */
- 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, // 累计支出
- ];
- }
- /**
- * 更新技师基础信息
- *
- * 业务流程:
- * 1. 获取最新的非拒绝记录
- * 2. 验证手机验证码(如果修改手机号)
- * 3. 如果是待审核状态,直接更新字段
- * 4. 如果是已通过状态,创建新记录并复制字段
- *
- * @param CoachUser $coach 技师对象
- * @param array $data 待更新的数据,可包含:
- * - nickname: ?string 昵称
- * - gender: ?int 性别(1:男 2:女)
- * - mobile: ?string 手机号
- * - code: ?string 验证码(修改手机号时必填)
- * @return array 返回结果
- */
- 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)
- ];
- });
- }
- /**
- * 验证手机验证码
- *
- * @param string $mobile 手机号
- * @param string $code 验证码
- * @throws \Illuminate\Http\Exceptions\HttpResponseException
- */
- 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);
- }
- /**
- * 发送验证码
- *
- * 业务流程:
- * 1. 检查手机号是否已被使用
- * 2. 生成验证码
- * 3. 保存到 Redis
- * 4. 发送验证码
- *
- * @param array $data 包含:
- * - mobile: string 手机号
- * - type: string 验证码类型
- * @return array 返回结果
- */
- public function sendVerifyCode(array $data): array
- {
- // 检查手机号是否已被使用
- $exists = MemberUser::where('mobile', $data['mobile'])
- ->whereHas('coach')
- ->exists();
- abort_if($exists, 422, '该手机号已被使用');
- // 生成6位随机验证码
- $code = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
- // 验证码有效期(5分钟)
- $expireTime = 300;
- // 缓存键
- $cacheKey = "sms_code:{$data['type']}:{$data['mobile']}";
- // 保存到Redis,设置5分钟过期
- Redis::setex($cacheKey, $expireTime, $code);
- return [
- 'code' => $code,
- 'mobile' => substr_replace($data['mobile'], '****', 3, 4),
- 'expire_time' => $expireTime
- ];
- }
- /**
- * 获取等级文本
- * 将等级数值转换为对应的文本描述
- *
- * @param int $level 等级值
- * @return string 等级文本描述
- */
- private function getLevelText(int $level): string
- {
- // 使用 match 表达式转换等级文本
- return match ($level) {
- 1 => '初级技师',
- 2 => '中级技师',
- 3 => '高级技师',
- default => '未知等级',
- };
- }
- /**
- * 获取技师已开通的项目列表
- *
- * 业务逻辑:
- * 1. 获取技师开通的所有项目
- * 2. 预加载项目基础信息
- * 3. 格式化返回数据
- *
- * @param int $coachId 技师ID
- * @return array 项目列表数据,包含:
- * - total: int 总数
- * - list: array 项目列表
- */
- 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
- ];
- }
- }
|