AccountService.php 52 KB

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