AccountService.php 51 KB

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