AccountService.php 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571
  1. <?php
  2. namespace App\Services\Coach;
  3. use App\Models\ShopInfo;
  4. use App\Models\CoachUser;
  5. use App\Enums\OrderStatus;
  6. use App\Models\MemberUser;
  7. use App\Enums\ProjectStatus;
  8. use App\Models\CoachProject;
  9. use App\Models\CoachLocation;
  10. use App\Models\CoachSchedule;
  11. use App\Models\CoachStatistic;
  12. use App\Enums\TechnicianStatus;
  13. use App\Models\CoachInfoRecord;
  14. use Illuminate\Support\Facades\DB;
  15. use App\Enums\TechnicianAuthStatus;
  16. use App\Enums\TechnicianWorkStatus;
  17. use Illuminate\Support\Facades\Log;
  18. use Illuminate\Support\Facades\Auth;
  19. use App\Enums\TechnicianLocationType;
  20. use Illuminate\Support\Facades\Cache;
  21. use Illuminate\Support\Facades\Redis;
  22. use App\Traits\LocationValidationTrait;
  23. class AccountService
  24. {
  25. use LocationValidationTrait;
  26. private const CACHE_KEY_PREFIX = 'coach_info_';
  27. private const CACHE_TTL = 300; // 5分钟
  28. /**
  29. * 提交技师基本信息
  30. * 包括个人基础资料的提交和审核
  31. *
  32. * 业务流程:
  33. * 1. 验证技师信息存在性
  34. * 2. 检查是否有待审核的记录
  35. * 3. 处理生活照片数据
  36. * 4. 创建新的基本信息记录
  37. * 5. 清除相关缓存
  38. *
  39. * 注意事项:
  40. * - 同一时间只能有一条待审核记录
  41. * - 审核不通过可以重新提交
  42. * - 头像和生活照片不限制格式
  43. * - 除性别和手机号外,其他字段均为可选
  44. * - 手机号会进行脱敏处理
  45. *
  46. * @param User $user 当前认证用户
  47. * @param array $data 基本信息数据,包含:
  48. * - nickname: string|null 昵称(可选)
  49. * - avatar: string|null 头像图片(可选)
  50. * - life_photos: array|null 生活照片数组(可选)
  51. * - gender: string 性别(1:男 2:女)
  52. * - mobile: string 手机号
  53. * - birthday: string|null 出生日期(可选)
  54. * - work_years: int|null 工作年限(可选)
  55. * - intention_city: string|null 意向城市(可选)
  56. * - introduction: string|null 个人简介(可选)
  57. * @return array 返回结果,包含:
  58. * - message: string 提示信息
  59. * @throws \Exception 当验证失败或保存失败时抛出异常
  60. */
  61. public function submitBaseInfo($user, array $data)
  62. {
  63. return DB::transaction(function () use ($user, $data) {
  64. // 验证技师信息是否存在,不存在则抛出404异常
  65. abort_if(!$user->coach, 404, '技师信息不存在');
  66. // 检查是否有待审核的记录,避免重复提交
  67. // 如果存在待审核记录,则抛出422异常
  68. $pendingRecord = $this->hasPendingRecord($user->coach, 'info');
  69. abort_if($pendingRecord, 422, '已有待审核的基本信息记录');
  70. // 处理生活照片数据:将数组转换为JSON格式存储
  71. // 如果没有生活照片数据,则保持原样
  72. if (isset($data['life_photos'])) {
  73. // 使用array_values确保数组索引连续
  74. $data['life_photos'] = json_encode(array_values($data['life_photos']));
  75. }
  76. // 创建新的基本信息记录,设置为待审核状态
  77. // 合并用户提交的数据和审核状态
  78. $user->coach->infoRecords()->create(array_merge($data, [
  79. 'state' => TechnicianAuthStatus::AUDITING->value, // 设置为待审核状态
  80. ]));
  81. // 清除技师信息缓存,确保数据一致性
  82. // 避免用户获取到旧的缓存数据
  83. $this->clearCoachCache($user->coach->id);
  84. return ['message' => '基本信息提交成功'];
  85. });
  86. }
  87. /**
  88. * 提交技师资质信息
  89. * 包括资质证书照片、营业执照和健康证照片的提交和审核
  90. *
  91. * 业务流程:
  92. * 1. 验证技师信息存在性
  93. * 2. 检查是否有待审核的记录
  94. * 3. 创建新的资质审核记录
  95. * 4. 清除相关缓存
  96. *
  97. * 注意事项:
  98. * - 同一时间只能有一条待审核记录
  99. * - 审核不通过可以重新提交
  100. * - 所有图片数据不限制格式
  101. *
  102. * @param User $user 当前认证用户
  103. * @param array $data 资质信息数据,包含:
  104. * - qual_type: int 资质类型(1:初级 2:中级 3:高级)
  105. * - qual_photo: string 资质证书照片
  106. * - business_license: string 营业执照照片
  107. * - health_cert: string 健康证照片
  108. * @return array 返回结果,包含:
  109. * - message: string 提示信息
  110. * - data: array 详细数据
  111. * - record_id: int 记录ID
  112. * - state: int 状态值
  113. * - state_text: string 状态文本
  114. * @throws \Exception 当验证失败或保存失败时抛出异常
  115. */
  116. public function submitQualification($user, array $data)
  117. {
  118. // 开启数据库事务
  119. DB::beginTransaction();
  120. try {
  121. // 验证技师信息是否存在
  122. abort_if(!$user->coach, 404, '技师信息不存在');
  123. // 检查是否有待审核的记录,避免重复提交
  124. $pendingRecord = $this->hasPendingRecord($user->coach, 'qual');
  125. abort_if($pendingRecord, 422, '已有待审核的资质信息记录');
  126. // 创建新的资质审核记录,设置为待审核状态
  127. $record = $user->coach->qualRecords()->create(array_merge($data, [
  128. 'state' => TechnicianAuthStatus::AUDITING->value,
  129. ]));
  130. // 清除技师信息缓存,确保数据一致性
  131. $this->clearCoachCache($user->coach->id);
  132. // 提交事务
  133. DB::commit();
  134. // 返回成功结果
  135. return [
  136. 'message' => '资质信息提交成功',
  137. 'data' => [
  138. 'record_id' => $record->id,
  139. 'state' => TechnicianAuthStatus::AUDITING->value,
  140. 'state_text' => TechnicianAuthStatus::fromValue(TechnicianAuthStatus::AUDITING->value)->label(),
  141. ]
  142. ];
  143. } catch (\Exception $e) {
  144. // 发生异常时回滚事务
  145. DB::rollBack();
  146. throw $e;
  147. }
  148. }
  149. /**
  150. * 提交实名认证信息
  151. * 包括姓名(可选)、身份证号(可选)和三张身份证照片的提交和审核
  152. *
  153. * 业务流程:
  154. * 1. 验证技师信息存在性
  155. * 2. 检查是否有待审核的记录
  156. * 3. 创建新的实名认证记录
  157. * 4. 清除相关缓存
  158. *
  159. * 注意事项:
  160. * - 同一时间只能有一条待审核记录
  161. * - 审核不通过可以重新提交
  162. * - 所有图片数据不限制格式
  163. * - 姓名和身份证号为可选字段
  164. * - 敏感信息会进行脱敏处理
  165. *
  166. * @param User $user 当前认证用户
  167. * @param array $data 实名认证数据,包含:
  168. * - real_name: string|null 真实姓名(可选)
  169. * - id_card: string|null 身份证号(可选)
  170. * - id_card_front_photo: string 身份证正面照片
  171. * - id_card_back_photo: string 身份证反面照片
  172. * - id_card_hand_photo: string 手持身份证照片
  173. * @return array 返回结果
  174. * @throws \Exception 当验证失败或保存失败时抛出异常
  175. */
  176. public function submitRealName($user, array $data)
  177. {
  178. // 开启数据库事务
  179. DB::beginTransaction();
  180. try {
  181. // 验证技师信息是否存在
  182. abort_if(!$user->coach, 404, '技师信息不存在');
  183. // TODO: 临时清除技师信息,便于对接调试
  184. $this->clearCoachCache($user->coach->id);
  185. // 检查是否有待审核的记录,避免重复提交
  186. $pendingRecord = $this->hasPendingRecord($user->coach, 'real');
  187. abort_if($pendingRecord, 422, '已有待审核的实名认证信息');
  188. // 创建新的实名认证记录,设置为待审核状态
  189. $user->coach->realRecords()->create(array_merge($data, [
  190. 'state' => TechnicianAuthStatus::AUDITING->value,
  191. ]));
  192. // 清除技师信息缓存,确保数据一致性
  193. $this->clearCoachCache($user->coach->id);
  194. // 提交事务
  195. DB::commit();
  196. // 返回成功结果
  197. return ['message' => '实名认证信息提交成功'];
  198. } catch (\Exception $e) {
  199. // 发生异常时回滚事务
  200. DB::rollBack();
  201. throw $e;
  202. }
  203. }
  204. /**
  205. * 获取技师信息
  206. * 包括基本信息、资质信息和实名认证信息
  207. *
  208. * 业务流程:
  209. * 1. 验证用户和技师信息存在性
  210. * 2. 尝试从缓存获取数据
  211. * 3. 如果缓存不存在,从数据库获取并缓存
  212. *
  213. * 注意事项:
  214. * - 所有图片数据不限制格式
  215. * - 敏感信息会进行脱敏处理
  216. * - 使用缓存提高性能
  217. *
  218. * @param User $user 当前认证用户
  219. * @return array 返回技师所有信息,包含:
  220. * - base_info: array|null 基本信息
  221. * - qualification: array|null 资质信息
  222. * - real_name: array|null 实名认证信息
  223. * @throws \Exception 当验证失败时抛出异常
  224. */
  225. public function getCoachInfo($user)
  226. {
  227. // 验证用户和技师信息
  228. abort_if(!$user, 404, '用户不存在');
  229. abort_if(!$user->coach, 404, '技师信息不存在');
  230. // 尝试从缓存获取数据
  231. return Cache::remember(
  232. self::CACHE_KEY_PREFIX . $user->coach->id,
  233. self::CACHE_TTL,
  234. function () use ($user) {
  235. // 缓存不存在时,从数据库获取
  236. return $this->fetchCoachInfo($user->coach);
  237. }
  238. );
  239. }
  240. /**
  241. * 获取技师详细信息
  242. *
  243. * 业务逻辑:
  244. * 1. 获取技师最新基本信息(不包括审核拒绝的记录)
  245. * 2. 获取技师邀请码信息
  246. * 3. 获取钱包信息
  247. * 4. 获取审核状态信息
  248. * 5. 获取位置和店铺信息
  249. * 6. 获取统计数据
  250. * 7. 组装返回数据
  251. *
  252. * @return array 技师详细信息
  253. * @throws \Exception 获取信息失败时抛出异常
  254. */
  255. public function getCoachDetail(): array
  256. {
  257. // 获取技师信息并预加载关联,避免 N+1 问题
  258. $coach = Auth::user()->coach->load([
  259. 'latestInfoRecord',
  260. 'latestRealRecord',
  261. 'latestQualRecord',
  262. 'commonLocation',
  263. 'shop',
  264. 'statistics',
  265. ]);
  266. // 获取基本信息
  267. $baseInfo = $this->formatBaseInfo($coach->latestInfoRecord);
  268. // 生成技师工号
  269. $coachNo = str_pad($coach->id, 8, '0', STR_PAD_LEFT);
  270. // 获取技师邀请码
  271. $inviteCode = $this->generateInviteCode($coach->id);
  272. // 获取钱包信息
  273. $wallet = $this->getWalletInfo($coach->id);
  274. // 获取审核状态信息
  275. $authStatus = $this->formatAuthStatus($coach);
  276. // 获取位置信息
  277. $location = $this->formatLocation($coach->commonLocation);
  278. // 获取店铺信息
  279. $shop = $this->formatShop($coach->shop);
  280. // 获取统计信息
  281. $statistics = $this->formatStatistics($coach->statistics);
  282. // 组装返回数据
  283. return array_merge(
  284. [
  285. 'coach_no' => $coachNo,
  286. 'invite_code' => $inviteCode,
  287. 'wallet' => $wallet,
  288. ],
  289. $baseInfo,
  290. [
  291. 'state' => $coach->state,
  292. 'state_text' => TechnicianStatus::fromValue($coach->state)?->label(),
  293. ],
  294. [
  295. 'auth_status' => $authStatus,
  296. 'location' => $location,
  297. 'shop' => $shop,
  298. 'statistics' => $statistics,
  299. ]
  300. );
  301. }
  302. /**
  303. * 格式化审核状态信息
  304. * 包含基本信息、实名认证和资质认证的审核状态
  305. *
  306. * 业务逻辑:
  307. * 1. 获取最新的基本信息审核状态
  308. * 2. 获取最新的实名认证审核状态
  309. * 3. 获取最新的资质认证审核状态
  310. * 4. 格式化状态文本和时间
  311. *
  312. * @param CoachUser $coach 技师对象
  313. * @return array 审核状态信息
  314. */
  315. private function formatAuthStatus(CoachUser $coach): array
  316. {
  317. return [
  318. 'base_info' => [
  319. 'state' => $coach->latestInfoRecord?->state, // 审核状态值
  320. 'state_text' => TechnicianAuthStatus::fromValue($coach->latestInfoRecord?->state)?->label(), // 状态文本
  321. 'audit_remark' => $coach->latestInfoRecord?->audit_remark, // 审核备注
  322. 'updated_at' => $coach->latestInfoRecord?->updated_at?->format('Y-m-d H:i:s'), // 更新时间
  323. ],
  324. 'real_name' => [
  325. 'state' => $coach->latestRealRecord?->state,
  326. 'state_text' => TechnicianAuthStatus::fromValue($coach->latestRealRecord?->state)?->label(),
  327. 'audit_remark' => $coach->latestRealRecord?->audit_remark,
  328. 'updated_at' => $coach->latestRealRecord?->updated_at?->format('Y-m-d H:i:s'),
  329. ],
  330. 'qualification' => [
  331. 'state' => $coach->latestQualRecord?->state,
  332. 'state_text' => TechnicianAuthStatus::fromValue($coach->latestQualRecord?->state)?->label(),
  333. 'audit_remark' => $coach->latestQualRecord?->audit_remark,
  334. 'updated_at' => $coach->latestQualRecord?->updated_at?->format('Y-m-d H:i:s'),
  335. ],
  336. ];
  337. }
  338. /**
  339. * 格式化位置信息
  340. * 处理技师的常用位置信息
  341. *
  342. * 业务逻辑:
  343. * 1. 检查位置信息是否存在
  344. * 2. 格式化地理位置信息
  345. * 3. 格式化行政区划信息
  346. *
  347. * @param CoachLocation|null $location 位置对象
  348. * @return array|null 格式化后的位置信息
  349. */
  350. private function formatLocation(?CoachLocation $location): ?array
  351. {
  352. // 如果没有位置信息,返回null
  353. if (!$location) {
  354. return null;
  355. }
  356. // 返回格式化的位置信息
  357. return [
  358. 'province' => $location->province, // 省份
  359. 'city' => $location->city, // 城市
  360. 'district' => $location->district, // 区县
  361. 'address' => $location->address, // 详细地址
  362. 'adcode' => $location->adcode, // 行政区划代码
  363. 'longitude' => $location->longitude, // 经度
  364. 'latitude' => $location->latitude, // 纬度
  365. ];
  366. }
  367. /**
  368. * 格式化店铺信息
  369. * 处理技师所属店铺的基本信息
  370. *
  371. * 业务逻辑:
  372. * 1. 检查店铺信息是否存在
  373. * 2. 格式化店铺基本信息
  374. * 3. 格式化联系信息
  375. *
  376. * @param ShopInfo|null $shop 店铺对象
  377. * @return array|null 格式化后的店铺信息
  378. */
  379. private function formatShop(?ShopInfo $shop): ?array
  380. {
  381. // 如果没有店铺信息,返回null
  382. if (!$shop) {
  383. return null;
  384. }
  385. // 返回格式化的店铺信息
  386. return [
  387. 'id' => $shop->id, // 店铺ID
  388. 'name' => $shop->name, // 店铺名称
  389. 'address' => $shop->address, // 店铺地址
  390. 'phone' => $shop->phone, // 联系电话
  391. ];
  392. }
  393. /**
  394. * 格式化统计信息
  395. * 处理技师的订单统计和等级信息
  396. *
  397. * 业务逻辑:
  398. * 1. 获取订单相关统计数据
  399. * 2. 获取技师等级信息
  400. * 3. 获取评分信息
  401. * 4. 处理默认值
  402. *
  403. * @param CoachStatistic|null $statistics 统计对象
  404. * @return array 格式化后的统计信息
  405. */
  406. private function formatStatistics(?CoachStatistic $statistics): array
  407. {
  408. return [
  409. 'order_count' => $statistics?->order_count ?? 0, // 总订单数
  410. 'completed_order_count' => $statistics?->completed_order_count ?? 0, // 已完成订单数
  411. 'level' => $statistics?->level ?? 1, // 技师等级
  412. 'level_text' => $this->getLevelText($statistics?->level ?? 1), // 等级文本
  413. 'rating' => $statistics?->rating ?? 5.0, // 评分
  414. ];
  415. }
  416. /**
  417. * 获取技师详细信息
  418. * 从数据库获取最新的认证记录信息
  419. *
  420. * @param CoachUser $coach 技师对象
  421. * @return array 格式化后的技师信息
  422. */
  423. private function fetchCoachInfo($coach)
  424. {
  425. // 获取最新的各类认证记录
  426. $baseInfo = $coach->infoRecords()->latest()->first();
  427. $qualification = $coach->qualRecords()->latest()->first();
  428. $realName = $coach->realRecords()->latest()->first();
  429. // 格式化并返回数据
  430. return [
  431. 'base_info' => $baseInfo ? $this->formatBaseInfo($baseInfo) : null,
  432. 'qualification' => $qualification ? $this->formatQualification($qualification) : null,
  433. 'real_name' => $realName ? $this->formatRealName($realName) : null,
  434. ];
  435. }
  436. /**
  437. * 格式化基本信息
  438. * 处理技师基本信息的展示格式
  439. *
  440. * @param object $info 基本信息记录对象
  441. * @return array 格式化后的基本信息
  442. */
  443. private function formatBaseInfo($info)
  444. {
  445. // 返回格式化后的基本信息,包含状态文本
  446. return [
  447. 'nickname' => $info->nickname,
  448. 'avatar' => $info->avatar, // 支持任意格式的图片数据
  449. 'life_photos' => $info->life_photos ?? [], // 生活照片数组
  450. 'gender' => $info->gender,
  451. 'mobile' => $this->maskMobile($info->mobile), // 手机号脱敏处理
  452. 'birthday' => $info->birthday,
  453. 'work_years' => $info->work_years,
  454. 'intention_city' => $info->intention_city,
  455. 'introduction' => $info->introduction,
  456. 'state' => $info->state,
  457. 'state_text' => TechnicianAuthStatus::fromValue($info->state)->label(),
  458. 'audit_remark' => $info->audit_remark,
  459. ];
  460. }
  461. /**
  462. * 格式化资质信息
  463. * 处理技师资质信息的展示格式
  464. *
  465. * @param object $qual 资质记录对象
  466. * @return array 格式化后的资质信息
  467. */
  468. private function formatQualification($qual)
  469. {
  470. // 资质类型文本映射
  471. $qualTypeMap = [
  472. 1 => '初级按摩师',
  473. 2 => '中级按摩师',
  474. 3 => '高级按摩师',
  475. ];
  476. // 返回格式化后的资质信息,包含状态文本
  477. return [
  478. 'qual_type' => $qual->qual_type,
  479. 'qual_type_text' => $qualTypeMap[$qual->qual_type] ?? '未知类型', // 添加类型文本
  480. 'qual_photo' => $qual->qual_photo, // 支持任意格式的图片数据
  481. 'business_license' => $qual->business_license, // 支持任意格式的图片数据
  482. 'health_cert' => $qual->health_cert, // 支持任意格式的图片数据
  483. 'state' => $qual->state,
  484. 'state_text' => TechnicianAuthStatus::fromValue($qual->state)->label(),
  485. 'audit_remark' => $qual->audit_remark,
  486. ];
  487. }
  488. /**
  489. * 格式化实名信息
  490. * 处理技师实名认证信息的展示格式
  491. *
  492. * @param object $real 实名认证记录对象
  493. * @return array 格式化后的实名信息
  494. */
  495. private function formatRealName($real)
  496. {
  497. // 返回格式化后的实名信息,包含状态文本和脱敏处理
  498. return [
  499. 'real_name' => $real->real_name,
  500. 'id_card' => $this->maskIdCard($real->id_card), // 身份证号脱敏处理
  501. 'id_card_front_photo' => $real->id_card_front_photo, // 支持任意格式的图片数据
  502. 'id_card_back_photo' => $real->id_card_back_photo, // 支持任意格式的图片数据
  503. 'id_card_hand_photo' => $real->id_card_hand_photo, // 支持任意格式的图片数据
  504. 'state' => $real->state,
  505. 'state_text' => TechnicianAuthStatus::fromValue($real->state)->label(),
  506. 'audit_remark' => $real->audit_remark,
  507. ];
  508. }
  509. /**
  510. * 手机号脱敏
  511. * 将手机号中间4位替换为****
  512. *
  513. * @param string $mobile 原始手机号
  514. * @return string 脱敏后的手机号
  515. */
  516. private function maskMobile($mobile)
  517. {
  518. return substr_replace($mobile, '****', 3, 4);
  519. }
  520. /**
  521. * 身份证号脱敏
  522. * 将身份证号中间8位替换为****
  523. *
  524. * @param string|null $idCard 原始身份证号
  525. * @return string|null 脱敏后的身份证号
  526. */
  527. private function maskIdCard($idCard)
  528. {
  529. if (!$idCard) {
  530. return null;
  531. }
  532. return substr_replace($idCard, '****', 6, 8);
  533. }
  534. /**
  535. * 清除技师信息缓存
  536. */
  537. private function clearCoachCache($coachId)
  538. {
  539. Cache::forget(self::CACHE_KEY_PREFIX . $coachId);
  540. }
  541. /**
  542. * 设置定位信息
  543. * 支持设置当前位置和常用位置,包含地理位置和行政区划信息
  544. *
  545. * 业务流程:
  546. * 1. 验证经纬度参数
  547. * 2. 验证位置类型
  548. * 3. 保存到Redis的地理位置数据结构
  549. * 4. 同步保存到据库
  550. *
  551. * @param int $coachId 技师ID
  552. * @param float $latitude 纬度
  553. * @param float $longitude 经度
  554. * @param int $type 位置类型 (current:1|common:2)
  555. * @param array $locationInfo 位置信息,包含:
  556. * - province: string|null 省份
  557. * - city: string|null 城市
  558. * - district: string|null 区县
  559. * - address: string|null 详细地址
  560. * - adcode: string|null 行政区划代码
  561. * @return bool 返回缓存更新结果
  562. * @throws \Exception 当验证失败或保存失败时抛出异常
  563. */
  564. public function setLocation($coachId, $latitude, $longitude, $type = TechnicianLocationType::COMMON->value, array $locationInfo = [])
  565. {
  566. // 使用事务确保一致性
  567. return DB::transaction(function () use ($coachId, $latitude, $longitude, $type, $locationInfo) {
  568. // 验证经纬度的有效性(-90≤纬度≤90,-180≤经度≤180)
  569. $this->validateCoordinates($latitude, $longitude);
  570. // 验证位置类型是否为有效值(1:当前位置 2:常用位置)
  571. $this->validateLocationType($type);
  572. // 格式化并验证位置信息(省市区、地址、行政区划代码)
  573. $formattedLocation = $this->formatLocationInfo($locationInfo);
  574. // 更新Redis地理位置缓存,用于实时位置查询
  575. $result = $this->updateLocationCache($coachId, $longitude, $latitude, $type);
  576. // 同步更新数据库,保存历史位置记录
  577. CoachLocation::updateOrCreate(
  578. // 查询条件:根据技师ID和位置类型确定唯一记录
  579. ['coach_id' => $coachId, 'type' => $type],
  580. // 更新数据:合并基础位置信息和格式化后的地址信息
  581. array_merge([
  582. 'latitude' => $latitude,
  583. 'longitude' => $longitude,
  584. ], $formattedLocation)
  585. );
  586. return $result;
  587. });
  588. }
  589. /**
  590. * 获取技师位置信息
  591. *
  592. * 业务流程:
  593. * 1. 获取指定类型的位置记录
  594. * 2. 返回格式化的位置数据
  595. *
  596. * @param User $user 认证用户
  597. * @param int $type 位置类型 (1:当前位置 2:常用位置)
  598. * @return array 位置信息,包含:
  599. * - province: string 省份
  600. * - city: string 城市
  601. * - district: string 区县
  602. * - address: string 详细地址
  603. * - adcode: string 行政区划代码
  604. * - longitude: float 经度
  605. * - latitude: float 纬度
  606. * - updated_at: string 更新时间
  607. */
  608. public function getLocation($user, int $type): array
  609. {
  610. // 获取指定类型的位置记录
  611. $location = $this->getLocationByType($user->coach, $type);
  612. // 返回格式化的位置数据
  613. return $this->formatLocationResponse($location);
  614. }
  615. /**
  616. * 根据类型获取技师位置记录
  617. *
  618. * @param CoachUser $coach 技师对象
  619. * @param int $type 位置类型 (1:当前位置 2:常用位置)
  620. * @return CoachLocation 位置信息
  621. * @throws \Illuminate\Http\Exceptions\HttpResponseException 当位置信息不存在时抛出404异常
  622. */
  623. private function getLocationByType(CoachUser $coach, int $type): CoachLocation
  624. {
  625. // 获取指定类型的位置记录
  626. $location = $coach->locations()
  627. ->where('type', $type)
  628. ->first();
  629. abort_if(!$location, 404, '位置信息不存在');
  630. // 返回位置数据
  631. return $location;
  632. }
  633. /**
  634. * 格式化位置响应数据
  635. *
  636. * @param CoachLocation $location 位置记录
  637. * @return array 格式化后的位置信息,包含:
  638. * - province: string 省份
  639. * - city: string 城市
  640. * - district: string 区县
  641. * - address: string 详细地址
  642. * - adcode: string 行政区划代码
  643. * - longitude: float 经度
  644. * - latitude: float 纬度
  645. * - updated_at: string 更新时间
  646. */
  647. private function formatLocationResponse(CoachLocation $location): array
  648. {
  649. return [
  650. 'province' => $location->province, // 省份
  651. 'city' => $location->city, // 城市
  652. 'district' => $location->district, // 区县
  653. 'address' => $location->address, // 详细地址
  654. 'adcode' => $location->adcode, // 行政区划代码
  655. 'longitude' => $location->longitude, // 经度
  656. 'latitude' => $location->latitude, // 纬度
  657. 'updated_at' => $location->updated_at->toDateTimeString(), // 更新时间
  658. ];
  659. }
  660. /**
  661. * 设置技师排班时间(每天通用)
  662. *
  663. * @param int $userId 技师用户ID
  664. * @param array $timeRanges 时间段数组 格式: [
  665. * ['start_time' => '09:00', 'end_time' => '12:00'],
  666. * ['start_time' => '14:00', 'end_time' => '18:00']
  667. * ]
  668. *
  669. * @throws \Exception
  670. */
  671. public function setSchedule(int $userId, array $timeRanges): array
  672. {
  673. return DB::transaction(function () use ($userId, $timeRanges) {
  674. try {
  675. // 获取技师信息
  676. $user = MemberUser::with(['coach'])->findOrFail($userId);
  677. $coach = $user->coach;
  678. abort_if(! $coach, 404, '技师信息不存在');
  679. // 验证并排序时间段
  680. $sortedRanges = $this->validateAndSortTimeRanges($timeRanges);
  681. // 创建或更新排班记录
  682. $schedule = CoachSchedule::updateOrCreate(
  683. [
  684. 'coach_id' => $coach->id,
  685. ],
  686. [
  687. 'time_ranges' => json_encode($sortedRanges),
  688. 'state' => 1,
  689. ]
  690. );
  691. // 更新Redis缓存
  692. $this->updateScheduleCache($coach->id, $sortedRanges);
  693. // 记录日志
  694. Log::info('技师排班设置成功', [
  695. 'coach_id' => $coach->id,
  696. 'time_ranges' => $sortedRanges,
  697. ]);
  698. return [
  699. 'status' => true,
  700. 'message' => '排班设置成功',
  701. 'data' => [
  702. 'coach_id' => $coach->id,
  703. 'time_ranges' => $sortedRanges,
  704. 'updated_at' => $schedule->updated_at->toDateTimeString(),
  705. ],
  706. ];
  707. } catch (\Exception $e) {
  708. Log::error('技师排班设置败', [
  709. 'user_id' => $userId,
  710. 'time_ranges' => $timeRanges,
  711. 'error' => $e->getMessage(),
  712. 'trace' => $e->getTraceAsString(),
  713. ]);
  714. throw $e;
  715. }
  716. });
  717. }
  718. /**
  719. * 验证并排序时间段
  720. */
  721. private function validateAndSortTimeRanges(array $timeRanges): array
  722. {
  723. // 验证时间段数组
  724. abort_if(empty($timeRanges), 400, '必须至少设置一个时间段');
  725. // 验证每个时间段格式并转换为分钟数进行比较
  726. $ranges = collect($timeRanges)->map(function ($range) {
  727. abort_if(
  728. ! isset($range['start_time'], $range['end_time']),
  729. 400,
  730. '时间段格式错误'
  731. );
  732. // 验证时间格式
  733. foreach (['start_time', 'end_time'] as $field) {
  734. abort_if(
  735. ! preg_match('/^([01][0-9]|2[0-3]):[0-5][0-9]$/', $range[$field]),
  736. 400,
  737. '时间格式错,应为HH:mm格式'
  738. );
  739. }
  740. // 转换为分钟数便于比较
  741. $startMinutes = $this->timeToMinutes($range['start_time']);
  742. $endMinutes = $this->timeToMinutes($range['end_time']);
  743. // 验证时间先后
  744. abort_if(
  745. $startMinutes >= $endMinutes,
  746. 400,
  747. "时间段 {$range['start_time']}-{$range['end_time']} 结束时间必须大于开始时间"
  748. );
  749. return [
  750. 'start_time' => $range['start_time'],
  751. 'end_time' => $range['end_time'],
  752. 'start_minutes' => $startMinutes,
  753. 'end_minutes' => $endMinutes,
  754. ];
  755. })
  756. ->sortBy('start_minutes')
  757. ->values();
  758. // 验证时间段是否重叠
  759. $ranges->each(function ($range, $index) use ($ranges) {
  760. if ($index > 0) {
  761. $prevRange = $ranges[$index - 1];
  762. abort_if(
  763. $range['start_minutes'] <= $prevRange['end_minutes'],
  764. 400,
  765. "时间段 {$prevRange['start_time']}-{$prevRange['end_time']} 和 " .
  766. "{$range['start_time']}-{$range['end_time']} 之间存在重叠"
  767. );
  768. }
  769. });
  770. // 返回排序后的时间,只保留需要的字段
  771. return $ranges->map(function ($range) {
  772. return [
  773. 'start_time' => $range['start_time'],
  774. 'end_time' => $range['end_time'],
  775. ];
  776. })->toArray();
  777. }
  778. /**
  779. * 将时间转换为分钟数
  780. */
  781. private function timeToMinutes(string $time): int
  782. {
  783. [$hours, $minutes] = explode(':', $time);
  784. return (int) $hours * 60 + (int) $minutes;
  785. }
  786. /**
  787. * 更新Redis缓存
  788. */
  789. private function updateScheduleCache(int $coachId, array $timeRanges): void
  790. {
  791. try {
  792. $cacheKey = "coach:schedule:{$coachId}";
  793. $cacheData = [
  794. 'updated_at' => now()->toDateTimeString(),
  795. 'time_ranges' => $timeRanges,
  796. ];
  797. Redis::setex($cacheKey, 86400, json_encode($cacheData));
  798. // 清除相关的可预约时间段缓存
  799. $this->clearTimeSlotCache($coachId);
  800. } catch (\Exception $e) {
  801. Log::error('更新排班缓存失败', [
  802. 'coach_id' => $coachId,
  803. 'error' => $e->getMessage(),
  804. ]);
  805. // 缓存更新失败不影响主流程
  806. }
  807. }
  808. /**
  809. * 清除可预约时间段缓存
  810. */
  811. public function clearTimeSlotCache(int $coachId): void
  812. {
  813. try {
  814. $pattern = "coach:timeslots:{$coachId}:*";
  815. $keys = Redis::keys($pattern);
  816. if (! empty($keys)) {
  817. Redis::del($keys);
  818. }
  819. } catch (\Exception $e) {
  820. Log::error('清除可预约时间段缓存失败', [
  821. 'coach_id' => $coachId,
  822. 'error' => $e->getMessage(),
  823. ]);
  824. }
  825. }
  826. /**
  827. * 更改技师工作状态
  828. *
  829. * @param int $userId 用户ID
  830. * @param int $status 状态(1:休息中 2:工作中)
  831. */
  832. public function updateWorkStatus(int $userId, int $status): array
  833. {
  834. DB::beginTransaction();
  835. try {
  836. // 获取技师信息
  837. $user = MemberUser::with(['coach', 'coach.infoRecords', 'coach.qualRecords', 'coach.realRecords'])
  838. ->findOrFail($userId);
  839. $coach = $user->coach;
  840. abort_if(! $coach, 404, '技师信息不存在');
  841. // 验证状态值
  842. abort_if(! in_array($status, [1, 2]), 400, '无效的状态值');
  843. // 验证技师认证状态
  844. $this->validateCoachStatus($coach);
  845. // 获取当前时间是否在排班时间内
  846. $isInSchedule = $this->checkScheduleTime($coach->id);
  847. $currentStatus = $coach->work_status;
  848. $newStatus = $status;
  849. // 如果要切换到休息状态
  850. if ($status === 1) {
  851. // 验证当前状态是否允许切换到休息
  852. $this->validateRestStatus($currentStatus);
  853. $newStatus = TechnicianWorkStatus::REST->value;
  854. }
  855. // 如果要切换到工作状态
  856. elseif ($status === 2) {
  857. // 验证是否在排班时间内
  858. abort_if(! $isInSchedule, 422, '当前时间不在排班时间内,无法切换到工作状态');
  859. // 检查是否有进行中的订单
  860. $hasActiveOrder = $coach->orders()
  861. ->whereIn('state', [
  862. OrderStatus::ACCEPTED->value, // 已接单
  863. OrderStatus::DEPARTED->value, // 已出发
  864. OrderStatus::ARRIVED->value, // 已到达
  865. OrderStatus::SERVING->value, // 服务中
  866. ])
  867. ->exists();
  868. // 根据是否有进行中订单决定状态
  869. $newStatus = $hasActiveOrder ?
  870. TechnicianWorkStatus::BUSY->value :
  871. TechnicianWorkStatus::FREE->value;
  872. }
  873. // 如果状态没有变,则不需要更新
  874. if ($currentStatus === $newStatus) {
  875. DB::rollBack();
  876. return [
  877. 'status' => true,
  878. 'message' => '状态未发生变化',
  879. 'data' => [
  880. 'work_status' => $newStatus,
  881. 'work_status_text' => TechnicianWorkStatus::fromValue($newStatus)->label(),
  882. 'updated_at' => now()->toDateTimeString(),
  883. ],
  884. ];
  885. }
  886. // 更新状态
  887. $coach->work_status = $newStatus;
  888. $coach->save();
  889. // 更新Redis缓存
  890. $this->updateWorkStatusCache($coach->id, $newStatus);
  891. DB::commit();
  892. // 记录日志
  893. Log::info('技师工作状态更新成功', [
  894. 'coach_id' => $coach->id,
  895. 'old_status' => $currentStatus,
  896. 'new_status' => $newStatus,
  897. 'updated_at' => now()->toDateTimeString(),
  898. 'in_schedule' => $isInSchedule,
  899. ]);
  900. return [
  901. 'status' => true,
  902. 'message' => '状态更新成功',
  903. 'data' => [
  904. 'work_status' => $newStatus,
  905. 'work_status_text' => TechnicianWorkStatus::fromValue($newStatus)->label(),
  906. 'updated_at' => now()->toDateTimeString(),
  907. ],
  908. ];
  909. } catch (\Exception $e) {
  910. DB::rollBack();
  911. Log::error('技师工作状态更新失败', [
  912. 'user_id' => $userId,
  913. 'status' => $status,
  914. 'error' => $e->getMessage(),
  915. 'trace' => $e->getTraceAsString(),
  916. ]);
  917. throw $e;
  918. }
  919. }
  920. /**
  921. * 验证技师认证状态
  922. */
  923. private function validateCoachStatus($coach): void
  924. {
  925. // 验证基本信息认证
  926. $baseInfo = $coach->info;
  927. abort_if(
  928. ! $baseInfo || $baseInfo->state !== TechnicianAuthStatus::PASSED->value,
  929. 422,
  930. '基本信息未认证通过'
  931. );
  932. // 验证资质认证
  933. $qualification = $coach->qual;
  934. abort_if(
  935. ! $qualification || $qualification->state !== TechnicianAuthStatus::PASSED->value,
  936. 422,
  937. '资质信息未认证通过'
  938. );
  939. // 验证实名认证
  940. $realName = $coach->real;
  941. abort_if(
  942. ! $realName || $realName->state !== TechnicianAuthStatus::PASSED->value,
  943. 422,
  944. '实名信息未认证通过'
  945. );
  946. }
  947. /**
  948. * 验证是否可以切换到休息状态
  949. */
  950. private function validateRestStatus(int $currentStatus): void
  951. {
  952. // 只有在空闲或忙碌状态下才能改为休息状态
  953. abort_if(! in_array($currentStatus, [
  954. TechnicianWorkStatus::FREE->value,
  955. TechnicianWorkStatus::BUSY->value,
  956. ]), 422, '当前状态不能更改为休息状态');
  957. }
  958. /**
  959. * 检查当前时间是否在排班时间内
  960. */
  961. private function checkScheduleTime(int $coachId): bool
  962. {
  963. try {
  964. $schedule = CoachSchedule::where('coach_id', $coachId)
  965. ->where('state', 1)
  966. ->first();
  967. if (! $schedule) {
  968. return false;
  969. }
  970. $timeRanges = json_decode($schedule->time_ranges, true);
  971. if (empty($timeRanges)) {
  972. return false;
  973. }
  974. $currentTime = now()->format('H:i');
  975. foreach ($timeRanges as $range) {
  976. if ($currentTime >= $range['start_time'] && $currentTime <= $range['end_time']) {
  977. return true;
  978. }
  979. }
  980. return false;
  981. } catch (\Exception $e) {
  982. Log::error('检查排班时间异常', [
  983. 'coach_id' => $coachId,
  984. 'error' => $e->getMessage(),
  985. ]);
  986. return false;
  987. }
  988. }
  989. /**
  990. * 更新工作状态缓存
  991. */
  992. private function updateWorkStatusCache(int $coachId, int $status): void
  993. {
  994. try {
  995. $cacheKey = "coach:work_status:{$coachId}";
  996. $cacheData = [
  997. 'status' => $status,
  998. 'updated_at' => now()->toDateTimeString(),
  999. ];
  1000. Redis::setex($cacheKey, 86400, json_encode($cacheData));
  1001. } catch (\Exception $e) {
  1002. Log::error('更新工作状态缓存失败', [
  1003. 'coach_id' => $coachId,
  1004. 'error' => $e->getMessage(),
  1005. ]);
  1006. // 缓存更新失败不影响主流程
  1007. }
  1008. }
  1009. /**
  1010. * 获取技师工作状态
  1011. *
  1012. * @param int $coachId 技师ID
  1013. */
  1014. public function getWorkStatus(int $coachId): array
  1015. {
  1016. try {
  1017. // 验证技师信息
  1018. $coach = CoachUser::find($coachId);
  1019. abort_if(! $coach, 404, '技师不存在');
  1020. // 直接获取技师信息里的work_status
  1021. $workStatus = $coach->work_status;
  1022. return [
  1023. 'work_status' => $workStatus,
  1024. 'work_status_text' => TechnicianWorkStatus::fromValue($workStatus)->label(),
  1025. 'updated_at' => now()->toDateTimeString(),
  1026. ];
  1027. } catch (\Exception $e) {
  1028. Log::error('获取技师工作状态失败', [
  1029. 'coach_id' => $coachId,
  1030. 'error' => $e->getMessage(),
  1031. 'trace' => $e->getTraceAsString(),
  1032. ]);
  1033. throw $e;
  1034. }
  1035. }
  1036. /**
  1037. * 获取技师排班信息
  1038. *
  1039. * @param int $userId 用户ID
  1040. */
  1041. public function getSchedule(int $userId): array
  1042. {
  1043. try {
  1044. // 获取技师信息
  1045. $user = MemberUser::with(['coach'])->findOrFail($userId);
  1046. $coach = $user->coach;
  1047. abort_if(! $coach, 404, '技师信息不存在');
  1048. // 先尝试缓存获取
  1049. $cacheKey = "coach:schedule:{$coach->id}";
  1050. $cached = Redis::get($cacheKey);
  1051. if ($cached) {
  1052. return json_decode($cached, true);
  1053. }
  1054. // 缓存不存在,从数据库获取
  1055. $schedule = CoachSchedule::where('coach_id', $coach->id)
  1056. ->where('state', 1)
  1057. ->first();
  1058. $result = [
  1059. 'time_ranges' => $schedule ? json_decode($schedule->time_ranges, true) : [],
  1060. 'updated_at' => $schedule ? $schedule->updated_at->toDateTimeString() : now()->toDateTimeString(),
  1061. ];
  1062. // 写入缓存
  1063. Redis::setex($cacheKey, 86400, json_encode($result));
  1064. // 记录日志
  1065. Log::info('获取技师排班信息成功', [
  1066. 'coach_id' => $coach->id,
  1067. 'schedule' => $result,
  1068. ]);
  1069. return $result;
  1070. } catch (\Exception $e) {
  1071. Log::error('获取技师排班信息失败', [
  1072. 'user_id' => $userId,
  1073. 'error' => $e->getMessage(),
  1074. 'trace' => $e->getTraceAsString(),
  1075. ]);
  1076. throw $e;
  1077. }
  1078. }
  1079. /**
  1080. * 验证技师基础信息
  1081. *
  1082. * @param User $user 用户对象
  1083. * @param bool $throwError 是否抛出异常
  1084. * @return bool
  1085. */
  1086. private function validateBasicCoach($user, bool $throwError = true): bool
  1087. {
  1088. if (!$user || !$user->coach) {
  1089. if ($throwError) {
  1090. abort_if(!$user, 404, '用户不存在');
  1091. abort_if(!$user->coach, 404, '技师信息不存在');
  1092. }
  1093. return false;
  1094. }
  1095. return true;
  1096. }
  1097. /**
  1098. * 检查是否存在审核记录
  1099. *
  1100. * @param CoachUser $coach 技师对象
  1101. * @param string $type 记录类型(info|qual|real)
  1102. * @return bool
  1103. */
  1104. private function hasPendingRecord($coach, string $type): bool
  1105. {
  1106. $method = match ($type) {
  1107. 'info' => 'infoRecords',
  1108. 'qual' => 'qualRecords',
  1109. 'real' => 'realRecords',
  1110. default => throw new \InvalidArgumentException('Invalid record type')
  1111. };
  1112. return $coach->{$method}()
  1113. ->where('state', TechnicianAuthStatus::AUDITING->value)
  1114. ->exists();
  1115. }
  1116. /**
  1117. * 格式化位置信息
  1118. * 过滤和验证位置相关字段
  1119. *
  1120. * @param array $locationInfo 原始位置信息
  1121. * @return array 格式化后的位置信息
  1122. * @throws \Exception 当行政区划代码格式无效时抛出异常
  1123. */
  1124. private function formatLocationInfo(array $locationInfo): array
  1125. {
  1126. // 定义允许的字段列表,确保数据安全性
  1127. $allowedFields = [
  1128. 'province', // 省份
  1129. 'city', // 城市
  1130. 'district', // 区县
  1131. 'address', // 详细地址
  1132. 'adcode' // 行政区划代码
  1133. ];
  1134. // 过滤并验证字段:
  1135. // 1. 只保留允许的字段
  1136. // 2. 移除空值
  1137. $formatted = array_filter(
  1138. array_intersect_key($locationInfo, array_flip($allowedFields)),
  1139. function ($value) {
  1140. return !is_null($value) && $value !== '';
  1141. }
  1142. );
  1143. // 验证行政区划代码格式(6位数字)
  1144. if (isset($formatted['adcode'])) {
  1145. abort_if(!preg_match('/^\d{6}$/', $formatted['adcode']), 422, '无效的行政区划代码');
  1146. }
  1147. return $formatted;
  1148. }
  1149. /**
  1150. * 更新位置缓存
  1151. * 处理Redis地理位置数据结构的更新
  1152. * 使用Redis的GEOADD命令存储地理位置信息
  1153. *
  1154. * @param int $coachId 技师ID
  1155. * @param float $longitude 经度
  1156. * @param float $latitude 纬度
  1157. * @param int $type 位置类型
  1158. * @return bool 操作是否成功
  1159. */
  1160. private function updateLocationCache(int $coachId, float $longitude, float $latitude, int $type): bool
  1161. {
  1162. // 生成缓存键:技师ID_位置类型
  1163. $key = $coachId . '_' . $type;
  1164. // 使用Redis的GEOADD命令添加地理位置信息
  1165. // 参数顺序:key longitude latitude member
  1166. return Redis::geoadd('coach_locations', $longitude, $latitude, $key);
  1167. }
  1168. /**
  1169. * 获取技师最新基本信息
  1170. *
  1171. * @param CoachUser $coach 技师对象
  1172. * @return CoachInfoRecord 最新的基本信息记录
  1173. * @throws \Illuminate\Http\Exceptions\HttpResponseException 当信息不存在时抛出404异常
  1174. */
  1175. private function getLatestBaseInfo(CoachUser $coach): CoachInfoRecord
  1176. {
  1177. // 获取最新的技师信息记录(排除审核拒绝的记录)
  1178. $latestInfo = $coach->infoRecords()
  1179. ->where('state', '<>', TechnicianAuthStatus::REJECTED->value)
  1180. ->latest()
  1181. ->first();
  1182. abort_if(!$latestInfo, 404, '技师基本信息不存在');
  1183. return $latestInfo;
  1184. }
  1185. /**
  1186. * 生成技师邀请码
  1187. *
  1188. * @param int $coachId 技师ID
  1189. * @return string 邀请码
  1190. */
  1191. private function generateInviteCode(int $coachId): string
  1192. {
  1193. return sprintf('C%d', $coachId);
  1194. }
  1195. /**
  1196. * 获取技师钱包信息
  1197. *
  1198. * 业务逻辑:
  1199. * 1. 获取技师钱包关联数据
  1200. * 2. 如果钱包不存在,返回默认值
  1201. * 3. 返回钱包概况数据
  1202. *
  1203. * @param int $coachId 技师ID
  1204. * @return array 钱包概况信息
  1205. */
  1206. private function getWalletInfo(int $coachId): array
  1207. {
  1208. // 获取技师对象及其钱包关联
  1209. $coach = CoachUser::with('wallet')->find($coachId);
  1210. // 如果钱包不存在,返回默认值
  1211. if (!$coach || !$coach->wallet) {
  1212. return [
  1213. 'total_balance' => 0, // 总余额
  1214. 'available_balance' => 0, // 可用余额
  1215. 'frozen_amount' => 0, // 冻结金额
  1216. 'total_income' => 0, // 累计收入
  1217. 'total_expense' => 0, // 累计支出
  1218. ];
  1219. }
  1220. // 返回钱包概况数据
  1221. return [
  1222. 'total_balance' => $coach->wallet->total_balance ?? 0, // 总余额
  1223. 'available_balance' => $coach->wallet->available_balance ?? 0, // 可用余额
  1224. 'frozen_amount' => $coach->wallet->frozen_amount ?? 0, // 冻结金额
  1225. 'total_income' => $coach->wallet->total_income ?? 0, // 累计收入
  1226. 'total_expense' => $coach->wallet->total_expense ?? 0, // 累计支出
  1227. ];
  1228. }
  1229. /**
  1230. * 更新技师基础信息
  1231. *
  1232. * 业务流程:
  1233. * 1. 获取最新的非拒绝记录
  1234. * 2. 验证手机验证码(如果修改手机号)
  1235. * 3. 如果是待审核状态,直接更新字段
  1236. * 4. 如果是已通过状态,创建新记录并复制字段
  1237. *
  1238. * @param CoachUser $coach 技师对象
  1239. * @param array $data 待更新的数据,可包含:
  1240. * - nickname: ?string 昵称
  1241. * - gender: ?int 性别(1:男 2:女)
  1242. * - mobile: ?string 手机号
  1243. * - code: ?string 验证码(修改手机号时必填)
  1244. * @return array 返回结果
  1245. */
  1246. public function updateBasicInfo(CoachUser $coach, array $data): array
  1247. {
  1248. return DB::transaction(function () use ($coach, $data) {
  1249. // 获取最新的非拒绝记录
  1250. $latestRecord = $coach->infoRecords()
  1251. ->where('state', '<>', TechnicianAuthStatus::REJECTED->value)
  1252. ->latest()
  1253. ->first();
  1254. abort_if(!$latestRecord, 404, '未找到有效的基础信息记录');
  1255. // 如果要修改手机号,验证验证码
  1256. if (isset($data['mobile'])) {
  1257. $this->verifyMobileCode($data['mobile'], $data['code']);
  1258. }
  1259. // 提取要更新的字段
  1260. $updateFields = array_intersect_key($data, [
  1261. 'nickname' => '',
  1262. 'gender' => '',
  1263. 'mobile' => '',
  1264. ]);
  1265. // 如果没有要更新的字段,直接返回
  1266. abort_if(empty($updateFields), 422, '没有需要更新的字段');
  1267. // 如果最新记录是待审核状态,直接更新
  1268. if ($latestRecord->state === TechnicianAuthStatus::AUDITING->value) {
  1269. $latestRecord->update($updateFields);
  1270. return [
  1271. 'message' => '基础信息修改申请已更新',
  1272. 'record_id' => $latestRecord->id,
  1273. 'updated_fields' => array_keys($updateFields)
  1274. ];
  1275. }
  1276. // 创建新的审核记录,复制其他字段
  1277. $newRecord = $coach->infoRecords()->create(array_merge([
  1278. 'avatar' => $latestRecord->avatar,
  1279. 'life_photos' => $latestRecord->life_photos,
  1280. 'gender' => $latestRecord->gender,
  1281. 'mobile' => $latestRecord->mobile,
  1282. 'birthday' => $latestRecord->birthday,
  1283. 'work_years' => $latestRecord->work_years,
  1284. 'intention_city' => $latestRecord->intention_city,
  1285. 'introduction' => $latestRecord->introduction,
  1286. 'state' => TechnicianAuthStatus::AUDITING->value,
  1287. ], $updateFields)); // 使用新的字段值覆盖
  1288. return [
  1289. 'message' => '基础信息修改申请已提交',
  1290. 'record_id' => $newRecord->id,
  1291. 'updated_fields' => array_keys($updateFields)
  1292. ];
  1293. });
  1294. }
  1295. /**
  1296. * 验证手机验证码
  1297. *
  1298. * @param string $mobile 手机号
  1299. * @param string $code 验证码
  1300. * @throws \Illuminate\Http\Exceptions\HttpResponseException
  1301. */
  1302. private function verifyMobileCode(string $mobile, string $code): void
  1303. {
  1304. // 缓存键
  1305. $cacheKey = "sms_code:update:{$mobile}";
  1306. // 获取缓存中的验证码
  1307. $cacheCode = Redis::get($cacheKey);
  1308. // 验证码不存在或不匹配
  1309. abort_if(!$cacheCode || $cacheCode !== $code, 422, '验证码错误或已过期');
  1310. // 验证成功后删除验证码
  1311. Redis::del($cacheKey);
  1312. }
  1313. /**
  1314. * 发送验证码
  1315. *
  1316. * 业务流程:
  1317. * 1. 检查手机号是否已被使用
  1318. * 2. 生成验证码
  1319. * 3. 保存到 Redis
  1320. * 4. 发送验证码
  1321. *
  1322. * @param array $data 包含:
  1323. * - mobile: string 手机号
  1324. * - type: string 验证码类型
  1325. * @return array 返回结果
  1326. */
  1327. public function sendVerifyCode(array $data): array
  1328. {
  1329. // 检查手机号是否已被使用
  1330. $exists = MemberUser::where('mobile', $data['mobile'])
  1331. ->whereHas('coach')
  1332. ->exists();
  1333. abort_if($exists, 422, '该手机号已被使用');
  1334. // 生成6位随机验证码
  1335. $code = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
  1336. // 验证码有效期(5分钟)
  1337. $expireTime = 300;
  1338. // 缓存键
  1339. $cacheKey = "sms_code:{$data['type']}:{$data['mobile']}";
  1340. // 保存到Redis,设置5分钟过期
  1341. Redis::setex($cacheKey, $expireTime, $code);
  1342. return [
  1343. 'code' => $code,
  1344. 'mobile' => substr_replace($data['mobile'], '****', 3, 4),
  1345. 'expire_time' => $expireTime
  1346. ];
  1347. }
  1348. /**
  1349. * 获取等级文本
  1350. * 将等级数值转换为对应的文本描述
  1351. *
  1352. * @param int $level 等级值
  1353. * @return string 等级文本描述
  1354. */
  1355. private function getLevelText(int $level): string
  1356. {
  1357. // 使用 match 表达式转换等级文本
  1358. return match ($level) {
  1359. 1 => '初级技师',
  1360. 2 => '中级技师',
  1361. 3 => '高级技师',
  1362. default => '未知等级',
  1363. };
  1364. }
  1365. /**
  1366. * 获取技师已开通的项目列表
  1367. *
  1368. * 业务逻辑:
  1369. * 1. 获取技师开通的所有项目
  1370. * 2. 预加载项目基础信息
  1371. * 3. 格式化返回数据
  1372. *
  1373. * @param int $coachId 技师ID
  1374. * @return array 项目列表数据,包含:
  1375. * - total: int 总数
  1376. * - list: array 项目列表
  1377. */
  1378. public function getEnabledProjects(int $coachId): array
  1379. {
  1380. // 获取技师开通且启用的项目
  1381. $projects = CoachProject::with(['project', 'project.category'])
  1382. ->where('coach_id', $coachId)
  1383. ->where('state', ProjectStatus::OPEN->value)
  1384. ->get();
  1385. // 格式化项目数据
  1386. $list = $projects->map(function ($item) {
  1387. return [
  1388. 'id' => $item->id,
  1389. 'project_id' => $item->project_id,
  1390. 'project_name' => $item->project?->name,
  1391. 'category_id' => $item->project?->category_id,
  1392. 'category_name' => $item->project?->category?->name,
  1393. 'duration' => $item->project?->duration, // 服务时长(分钟)
  1394. 'price' => $item->project?->price, // 项目价格
  1395. 'discount_amount' => $item->discount_amount, // 优惠金额
  1396. 'final_price' => $item->project?->price - $item->discount_amount, // 最终价格
  1397. 'service_gender' => $item->service_gender, // 服务性别
  1398. 'service_distance' => $item->service_distance, // 服务距离(米)
  1399. 'traffic_fee_type' => $item->traffic_fee_type, // 路费类型
  1400. 'traffic_fee' => $item->traffic_fee, // 路费金额
  1401. 'created_at' => $item->created_at?->format('Y-m-d H:i:s'),
  1402. 'updated_at' => $item->updated_at?->format('Y-m-d H:i:s'),
  1403. ];
  1404. })->values()->all();
  1405. return [
  1406. 'total' => count($list),
  1407. 'list' => $list
  1408. ];
  1409. }
  1410. }