AccountService.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  1. <?php
  2. namespace App\Services\Coach;
  3. use App\Models\CoachUser;
  4. use App\Enums\OrderStatus;
  5. use App\Models\MemberUser;
  6. use App\Models\CoachSchedule;
  7. use Illuminate\Support\Facades\DB;
  8. use App\Enums\TechnicianAuthStatus;
  9. use App\Enums\TechnicianWorkStatus;
  10. use Illuminate\Support\Facades\Log;
  11. use App\Enums\TechnicianLocationType;
  12. use Illuminate\Support\Facades\Cache;
  13. use Illuminate\Support\Facades\Redis;
  14. class AccountService
  15. {
  16. private const CACHE_KEY_PREFIX = 'coach_info_';
  17. private const CACHE_TTL = 300; // 5分钟
  18. /**
  19. * 提交技师基本信息
  20. * 包括个人基础资料的提交和审核
  21. *
  22. * 业务流程:
  23. * 1. 验证技师信息存在性
  24. * 2. 检查是否有待审核的记录
  25. * 3. 创建新的基本信息记录
  26. * 4. 清除相关缓存
  27. *
  28. * 注意事项:
  29. * - 同一时间只能有一条待审核记录
  30. * - 审核不通过可以重新提交
  31. * - 头像图片数据不限制格式
  32. * - 除性别和手机号外,其他字段均为可选
  33. * - 手机号会进行脱敏处理
  34. *
  35. * @param User $user 当前认证用户
  36. * @param array $data 基本信息数据,包含:
  37. * - nickname: string|null 昵称(可选)
  38. * - avatar: string|null 头像图片(可选)
  39. * - gender: string 性别(1:男 2:女)
  40. * - mobile: string 手机号
  41. * - birthday: string|null 出生日期(可选)
  42. * - work_years: int|null 工作年限(可选)
  43. * - intention_city: string|null 意向城市(可选)
  44. * - introduction: string|null 个人简介(可选)
  45. * @return array 返回结果
  46. * @throws \Exception 当验证失败或保存失败时抛出异常
  47. */
  48. public function submitBaseInfo($user, array $data)
  49. {
  50. DB::beginTransaction();
  51. try {
  52. // 验证技师信息是否存在
  53. abort_if(!$user->coach, 404, '技师信息不存在');
  54. // 检查是否有待审核的记录,避免重复提交
  55. $pendingRecord = $this->hasPendingRecord($user->coach, 'info');
  56. abort_if($pendingRecord, 422, '已有待审核的基本信息记录');
  57. // 创建技师信息
  58. $user->coach->infoRecords()->create(array_merge($data, [
  59. 'state' => TechnicianAuthStatus::AUDITING->value,
  60. ]));
  61. // 清除技师信息缓存,确保数据一致性
  62. $this->clearCoachCache($user->coach->id);
  63. // 提交事务
  64. DB::commit();
  65. // 返回成功结果
  66. return ['message' => '基本信息提交成功'];
  67. } catch (\Exception $e) {
  68. // 发生异常时回滚事务
  69. DB::rollBack();
  70. throw $e;
  71. }
  72. }
  73. /**
  74. * 提交技师资质信息
  75. * 包括资质证书照片、营业执照和健康证照片的提交和审核
  76. *
  77. * 业务流程:
  78. * 1. 验证技师信息存在性
  79. * 2. 检查是否有待审核的记录
  80. * 3. 创建新的资质审核记录
  81. * 4. 清除相关缓存
  82. *
  83. * 注意事项:
  84. * - 同一时间只能有一条待审核记录
  85. * - 审核不通过可以重新提交
  86. * - 所有图片数据不限制格式
  87. *
  88. * @param User $user 当前认证用户
  89. * @param array $data 资质信息数据,包含:
  90. * - qual_type: string 资质类型(如:高级按摩师)
  91. * - qual_photo: string 资质证书照片
  92. * - business_license: string 营业执照照片
  93. * - health_cert: string 健康证照片
  94. * @return array 返回结果,包含:
  95. * - message: string 提示信息
  96. * - data: array 详细数据
  97. * - record_id: int 记录ID
  98. * - state: int 状态值
  99. * - state_text: string 状态文本
  100. * @throws \Exception 当验证失败或保存失败时抛出异常
  101. */
  102. public function submitQualification($user, array $data)
  103. {
  104. // 开启数据库事务
  105. DB::beginTransaction();
  106. try {
  107. // 验证技师信息是否存在
  108. abort_if(!$user->coach, 404, '技师信息不存在');
  109. // 检查是否有待审核的记录,避免重复提交
  110. $pendingRecord = $this->hasPendingRecord($user->coach, 'qual');
  111. abort_if($pendingRecord, 422, '已有待审核的资质信息记录');
  112. // 创建新的资质审核记录,设置为待审核状态
  113. $record = $user->coach->qualRecords()->create(array_merge($data, [
  114. 'state' => TechnicianAuthStatus::AUDITING->value,
  115. ]));
  116. // 清除技师信息缓存,确保数据一致性
  117. $this->clearCoachCache($user->coach->id);
  118. // 提交事务
  119. DB::commit();
  120. // 返回成功结果
  121. return [
  122. 'message' => '资质信息提交成功',
  123. 'data' => [
  124. 'record_id' => $record->id,
  125. 'state' => TechnicianAuthStatus::AUDITING->value,
  126. 'state_text' => TechnicianAuthStatus::fromValue(TechnicianAuthStatus::AUDITING->value)->label(),
  127. ]
  128. ];
  129. } catch (\Exception $e) {
  130. // 发生异常时回滚事务
  131. DB::rollBack();
  132. throw $e;
  133. }
  134. }
  135. /**
  136. * 提交实名认证信息
  137. * 包括姓名(可选)、身份证号(可选)和三张身份证照片的提交和审核
  138. *
  139. * 业务流程:
  140. * 1. 验证技师信息存在性
  141. * 2. 检查是否有待审核的记录
  142. * 3. 创建新的实名认证记录
  143. * 4. 清除相关缓存
  144. *
  145. * 注意事项:
  146. * - 同一时间只能有一条待审核记录
  147. * - 审核不通过可以重新提交
  148. * - 所有图片数据不限制格式
  149. * - 姓名和身份证号为可选字段
  150. * - 敏感信息会进行脱敏处理
  151. *
  152. * @param User $user 当前认证用户
  153. * @param array $data 实名认证数据,包含:
  154. * - real_name: string|null 真实姓名(可选)
  155. * - id_card: string|null 身份证号(可选)
  156. * - id_card_front_photo: string 身份证正面照片
  157. * - id_card_back_photo: string 身份证反面照片
  158. * - id_card_hand_photo: string 手持身份证照片
  159. * @return array 返回结果
  160. * @throws \Exception 当验证失败或保存失败时抛出异常
  161. */
  162. public function submitRealName($user, array $data)
  163. {
  164. // 开启数据库事务
  165. DB::beginTransaction();
  166. try {
  167. // 验证技师信息是否存在
  168. abort_if(!$user->coach, 404, '技师信息不存在');
  169. // 检查是否有待审核的记录,避免重复提交
  170. $pendingRecord = $this->hasPendingRecord($user->coach, 'real');
  171. abort_if($pendingRecord, 422, '已有待审核的实名认证信息');
  172. // 创建新的实名认证记录,设置为待审核状态
  173. $user->coach->realRecords()->create(array_merge($data, [
  174. 'state' => TechnicianAuthStatus::AUDITING->value,
  175. ]));
  176. // 清除技师信息缓存,确保数据一致性
  177. $this->clearCoachCache($user->coach->id);
  178. // 提交事务
  179. DB::commit();
  180. // 返回成功结果
  181. return ['message' => '实名认证信息提交成功'];
  182. } catch (\Exception $e) {
  183. // 发生异常时回滚事务
  184. DB::rollBack();
  185. throw $e;
  186. }
  187. }
  188. /**
  189. * 获取技师信息
  190. */
  191. public function getCoachInfo($user)
  192. {
  193. abort_if(! $user, 404, '用户不存在');
  194. abort_if(! $user->coach, 404, '技师信息不存在');
  195. return Cache::remember(
  196. self::CACHE_KEY_PREFIX . $user->coach->id,
  197. self::CACHE_TTL,
  198. function () use ($user) {
  199. return $this->fetchCoachInfo($user->coach);
  200. }
  201. );
  202. }
  203. /**
  204. * 获取技师详细信息
  205. */
  206. private function fetchCoachInfo($coach)
  207. {
  208. $baseInfo = $coach->infoRecords()->latest()->first();
  209. $qualification = $coach->qualRecords()->latest()->first();
  210. $realName = $coach->realRecords()->latest()->first();
  211. return [
  212. 'base_info' => $baseInfo ? $this->formatBaseInfo($baseInfo) : null,
  213. 'qualification' => $qualification ? $this->formatQualification($qualification) : null,
  214. 'real_name' => $realName ? $this->formatRealName($realName) : null,
  215. ];
  216. }
  217. /**
  218. * 格式化基本信息
  219. */
  220. private function formatBaseInfo($info)
  221. {
  222. return [
  223. 'nickname' => $info->nickname,
  224. 'avatar' => $info->avatar,
  225. 'gender' => $info->gender,
  226. 'mobile' => $this->maskMobile($info->mobile),
  227. 'birthday' => $info->birthday,
  228. 'work_years' => $info->work_years,
  229. 'intention_city' => $info->intention_city,
  230. 'introduction' => $info->introduction,
  231. 'state' => $info->state,
  232. 'state_text' => TechnicianAuthStatus::fromValue($info->state)->label(),
  233. 'audit_remark' => $info->audit_remark,
  234. ];
  235. }
  236. /**
  237. * 格式化资质信息
  238. *
  239. * @param object $qual 资质记录对象
  240. * @return array 格式化后的资质信息
  241. */
  242. private function formatQualification($qual)
  243. {
  244. return [
  245. 'qual_type' => $qual->qual_type,
  246. 'qual_photo' => $qual->qual_photo,
  247. 'business_license' => $qual->business_license,
  248. 'health_cert' => $qual->health_cert,
  249. 'state' => $qual->state,
  250. 'state_text' => TechnicianAuthStatus::fromValue($qual->state)->label(),
  251. 'audit_remark' => $qual->audit_remark,
  252. ];
  253. }
  254. /**
  255. * 格式化实名信息
  256. */
  257. private function formatRealName($real)
  258. {
  259. return [
  260. 'real_name' => $real->real_name,
  261. 'id_card' => $this->maskIdCard($real->id_card),
  262. 'id_card_front_photo' => $real->id_card_front_photo,
  263. 'id_card_back_photo' => $real->id_card_back_photo,
  264. 'id_card_hand_photo' => $real->id_card_hand_photo,
  265. 'state' => $real->state,
  266. 'state_text' => TechnicianAuthStatus::fromValue($real->state)->label(),
  267. 'audit_remark' => $real->audit_remark,
  268. ];
  269. }
  270. /**
  271. * 手机号脱敏
  272. */
  273. private function maskMobile($mobile)
  274. {
  275. return substr_replace($mobile, '****', 3, 4);
  276. }
  277. /**
  278. * 身份证脱敏
  279. */
  280. private function maskIdCard($idCard)
  281. {
  282. return substr_replace($idCard, '****', 6, 8);
  283. }
  284. /**
  285. * 清除技师信息缓存
  286. */
  287. private function clearCoachCache($coachId)
  288. {
  289. Cache::forget(self::CACHE_KEY_PREFIX . $coachId);
  290. }
  291. /**
  292. * 设置定位信息
  293. *
  294. * @param int $coachId 技师ID
  295. * @param float $latitude 纬度
  296. * @param float $longitude 经度
  297. * @param int $type 位置类型 (current:1|common:2)
  298. * @return bool
  299. *
  300. * @throws \Exception
  301. */
  302. public function setLocation($coachId, $latitude, $longitude, $type = TechnicianLocationType::COMMON->value)
  303. {
  304. DB::beginTransaction();
  305. try {
  306. // 验证经纬度参数
  307. if (! is_numeric($latitude) || ! is_numeric($longitude)) {
  308. throw new \Exception('无效的经纬度坐标');
  309. }
  310. // 验证位置类型
  311. if (! in_array($type, [TechnicianLocationType::CURRENT->value, TechnicianLocationType::COMMON->value])) {
  312. throw new \Exception('无效的位置类型');
  313. }
  314. // 生成Redis键
  315. $key = $coachId . '_' . $type;
  316. // 将置信息写入Redis
  317. $result = Redis::geoadd('coach_locations', $longitude, $latitude, $key);
  318. // 同时写入数据库保存历史记录
  319. DB::table('coach_locations')->updateOrInsert(
  320. ['coach_id' => $coachId, 'type' => $type],
  321. [
  322. 'latitude' => $latitude,
  323. 'longitude' => $longitude,
  324. 'updated_at' => now(),
  325. ]
  326. );
  327. DB::commit();
  328. Log::info('技师位置信息设置成功', [
  329. 'coach_id' => $coachId,
  330. 'type' => $type,
  331. 'latitude' => $latitude,
  332. 'longitude' => $longitude,
  333. ]);
  334. return $result;
  335. } catch (\Exception $e) {
  336. DB::rollBack();
  337. Log::error('技师位置信息设置异常', [
  338. 'coach_id' => $coachId,
  339. 'latitude' => $latitude,
  340. 'longitude' => $longitude,
  341. 'type' => $type,
  342. 'error' => $e->getMessage(),
  343. 'file' => $e->getFile(),
  344. 'line' => $e->getLine(),
  345. ]);
  346. throw $e;
  347. }
  348. }
  349. /**
  350. * 获取技师位置信息
  351. *
  352. * @param int $userId 用户ID
  353. * @return array 位置信息
  354. */
  355. public function getLocation($userId)
  356. {
  357. try {
  358. // 改进:直接使用 coach 模型
  359. $user = MemberUser::find($userId);
  360. abort_if(! $user, 404, '用户不存在');
  361. abort_if(! $user->coach, 404, '技师信息不存在');
  362. // 获取常用位置信息
  363. $location = $user->coach->locations()
  364. ->where('type', TechnicianLocationType::COMMON->value)
  365. ->first();
  366. $result = [
  367. 'address' => $location ? $location->location : null,
  368. ];
  369. // 记录日志
  370. Log::info('获取技师常用位置信息成功', [
  371. 'coach_id' => $user->coach->id,
  372. 'location' => $result,
  373. ]);
  374. return $result;
  375. } catch (\Exception $e) {
  376. Log::error('获取技师常用位置信息异常', [
  377. 'coach_id' => $user->coach->id ?? null,
  378. 'error' => $e->getMessage(),
  379. 'file' => $e->getFile(),
  380. 'line' => $e->getLine(),
  381. ]);
  382. throw $e;
  383. }
  384. }
  385. /**
  386. * 设置技师排班时间(每天通用)
  387. *
  388. * @param int $userId 技师用户ID
  389. * @param array $timeRanges 时间段数组 格式: [
  390. * ['start_time' => '09:00', 'end_time' => '12:00'],
  391. * ['start_time' => '14:00', 'end_time' => '18:00']
  392. * ]
  393. *
  394. * @throws \Exception
  395. */
  396. public function setSchedule(int $userId, array $timeRanges): array
  397. {
  398. return DB::transaction(function () use ($userId, $timeRanges) {
  399. try {
  400. // 获取技师信息
  401. $user = MemberUser::with(['coach'])->findOrFail($userId);
  402. $coach = $user->coach;
  403. abort_if(! $coach, 404, '技师信息不存在');
  404. // 验证并排序时间段
  405. $sortedRanges = $this->validateAndSortTimeRanges($timeRanges);
  406. // 创建或更新排班记录
  407. $schedule = CoachSchedule::updateOrCreate(
  408. [
  409. 'coach_id' => $coach->id,
  410. ],
  411. [
  412. 'time_ranges' => json_encode($sortedRanges),
  413. 'state' => 1,
  414. ]
  415. );
  416. // 更新Redis缓存
  417. $this->updateScheduleCache($coach->id, $sortedRanges);
  418. // 记录日志
  419. Log::info('技师排班设置成功', [
  420. 'coach_id' => $coach->id,
  421. 'time_ranges' => $sortedRanges,
  422. ]);
  423. return [
  424. 'status' => true,
  425. 'message' => '排班设置成功',
  426. 'data' => [
  427. 'coach_id' => $coach->id,
  428. 'time_ranges' => $sortedRanges,
  429. 'updated_at' => $schedule->updated_at->toDateTimeString(),
  430. ],
  431. ];
  432. } catch (\Exception $e) {
  433. Log::error('技师排班设置败', [
  434. 'user_id' => $userId,
  435. 'time_ranges' => $timeRanges,
  436. 'error' => $e->getMessage(),
  437. 'trace' => $e->getTraceAsString(),
  438. ]);
  439. throw $e;
  440. }
  441. });
  442. }
  443. /**
  444. * 验证并排序时间段
  445. */
  446. private function validateAndSortTimeRanges(array $timeRanges): array
  447. {
  448. // 验证时间段数组
  449. abort_if(empty($timeRanges), 400, '必须至少设置一个时间段');
  450. // 验证每个时间段格式并转换为分钟数进行比较
  451. $ranges = collect($timeRanges)->map(function ($range) {
  452. abort_if(
  453. ! isset($range['start_time'], $range['end_time']),
  454. 400,
  455. '时间段格式错误'
  456. );
  457. // 验证时间格式
  458. foreach (['start_time', 'end_time'] as $field) {
  459. abort_if(
  460. ! preg_match('/^([01][0-9]|2[0-3]):[0-5][0-9]$/', $range[$field]),
  461. 400,
  462. '时间格式错,应为HH:mm格式'
  463. );
  464. }
  465. // 转换为分钟数便于比较
  466. $startMinutes = $this->timeToMinutes($range['start_time']);
  467. $endMinutes = $this->timeToMinutes($range['end_time']);
  468. // 验证时间先后
  469. abort_if(
  470. $startMinutes >= $endMinutes,
  471. 400,
  472. "时间段 {$range['start_time']}-{$range['end_time']} 结束时间必须大于开始时间"
  473. );
  474. return [
  475. 'start_time' => $range['start_time'],
  476. 'end_time' => $range['end_time'],
  477. 'start_minutes' => $startMinutes,
  478. 'end_minutes' => $endMinutes,
  479. ];
  480. })
  481. ->sortBy('start_minutes')
  482. ->values();
  483. // 验证时间段是否重叠
  484. $ranges->each(function ($range, $index) use ($ranges) {
  485. if ($index > 0) {
  486. $prevRange = $ranges[$index - 1];
  487. abort_if(
  488. $range['start_minutes'] <= $prevRange['end_minutes'],
  489. 400,
  490. "时间段 {$prevRange['start_time']}-{$prevRange['end_time']} 和 " .
  491. "{$range['start_time']}-{$range['end_time']} 之间存在重叠"
  492. );
  493. }
  494. });
  495. // 返回排序后的时间,只保留需要的字段
  496. return $ranges->map(function ($range) {
  497. return [
  498. 'start_time' => $range['start_time'],
  499. 'end_time' => $range['end_time'],
  500. ];
  501. })->toArray();
  502. }
  503. /**
  504. * 将时间转换为分钟数
  505. */
  506. private function timeToMinutes(string $time): int
  507. {
  508. [$hours, $minutes] = explode(':', $time);
  509. return (int) $hours * 60 + (int) $minutes;
  510. }
  511. /**
  512. * 更新Redis缓存
  513. */
  514. private function updateScheduleCache(int $coachId, array $timeRanges): void
  515. {
  516. try {
  517. $cacheKey = "coach:schedule:{$coachId}";
  518. $cacheData = [
  519. 'updated_at' => now()->toDateTimeString(),
  520. 'time_ranges' => $timeRanges,
  521. ];
  522. Redis::setex($cacheKey, 86400, json_encode($cacheData));
  523. // 清除相关的可预约时间段缓存
  524. $this->clearTimeSlotCache($coachId);
  525. } catch (\Exception $e) {
  526. Log::error('更新排班缓存失败', [
  527. 'coach_id' => $coachId,
  528. 'error' => $e->getMessage(),
  529. ]);
  530. // 缓存更新失败不影响主流程
  531. }
  532. }
  533. /**
  534. * 清除可预约时间段缓存
  535. */
  536. public function clearTimeSlotCache(int $coachId): void
  537. {
  538. try {
  539. $pattern = "coach:timeslots:{$coachId}:*";
  540. $keys = Redis::keys($pattern);
  541. if (! empty($keys)) {
  542. Redis::del($keys);
  543. }
  544. } catch (\Exception $e) {
  545. Log::error('清除时间段缓存失败', [
  546. 'coach_id' => $coachId,
  547. 'error' => $e->getMessage(),
  548. ]);
  549. }
  550. }
  551. /**
  552. * 更改技师工作状态
  553. *
  554. * @param int $userId 用户ID
  555. * @param int $status 状态(1:休息中 2:工作中)
  556. */
  557. public function updateWorkStatus(int $userId, int $status): array
  558. {
  559. DB::beginTransaction();
  560. try {
  561. // 获取技师信息
  562. $user = MemberUser::with(['coach', 'coach.infoRecords', 'coach.qualRecords', 'coach.realRecords'])
  563. ->findOrFail($userId);
  564. $coach = $user->coach;
  565. abort_if(! $coach, 404, '技师信息不存在');
  566. // 验证状态值
  567. abort_if(! in_array($status, [1, 2]), 400, '无效的状态值');
  568. // 验证技师认证状态
  569. $this->validateCoachStatus($coach);
  570. // 获取当前时间是否在排班时间内
  571. $isInSchedule = $this->checkScheduleTime($coach->id);
  572. $currentStatus = $coach->work_status;
  573. $newStatus = $status;
  574. // 如果要切换到休息状态
  575. if ($status === 1) {
  576. // 验证当前状态是否允许切换到休息
  577. $this->validateRestStatus($currentStatus);
  578. $newStatus = TechnicianWorkStatus::REST->value;
  579. }
  580. // 如果要切换到工作状态
  581. elseif ($status === 2) {
  582. // 验证是否在排班时间内
  583. abort_if(! $isInSchedule, 422, '当前时间不在排班时间内,无法切换到工作状态');
  584. // 检查是否有进行中的订单
  585. $hasActiveOrder = $coach->orders()
  586. ->whereIn('state', [
  587. OrderStatus::ACCEPTED->value, // 已接单
  588. OrderStatus::DEPARTED->value, // 已出发
  589. OrderStatus::ARRIVED->value, // 已到达
  590. OrderStatus::SERVING->value, // 服务中
  591. ])
  592. ->exists();
  593. // 根据是否有进行中订单决定状态
  594. $newStatus = $hasActiveOrder ?
  595. TechnicianWorkStatus::BUSY->value :
  596. TechnicianWorkStatus::FREE->value;
  597. }
  598. // 如果状态没有变,则不需要更新
  599. if ($currentStatus === $newStatus) {
  600. DB::rollBack();
  601. return [
  602. 'status' => true,
  603. 'message' => '状态未发生变化',
  604. 'data' => [
  605. 'work_status' => $newStatus,
  606. 'work_status_text' => TechnicianWorkStatus::fromValue($newStatus)->label(),
  607. 'updated_at' => now()->toDateTimeString(),
  608. ],
  609. ];
  610. }
  611. // 更新状态
  612. $coach->work_status = $newStatus;
  613. $coach->save();
  614. // 更新Redis缓存
  615. $this->updateWorkStatusCache($coach->id, $newStatus);
  616. DB::commit();
  617. // 记录日志
  618. Log::info('技师工作状态更新成功', [
  619. 'coach_id' => $coach->id,
  620. 'old_status' => $currentStatus,
  621. 'new_status' => $newStatus,
  622. 'updated_at' => now()->toDateTimeString(),
  623. 'in_schedule' => $isInSchedule,
  624. ]);
  625. return [
  626. 'status' => true,
  627. 'message' => '状态更新成功',
  628. 'data' => [
  629. 'work_status' => $newStatus,
  630. 'work_status_text' => TechnicianWorkStatus::fromValue($newStatus)->label(),
  631. 'updated_at' => now()->toDateTimeString(),
  632. ],
  633. ];
  634. } catch (\Exception $e) {
  635. DB::rollBack();
  636. Log::error('技师工作状态更新失败', [
  637. 'user_id' => $userId,
  638. 'status' => $status,
  639. 'error' => $e->getMessage(),
  640. 'trace' => $e->getTraceAsString(),
  641. ]);
  642. throw $e;
  643. }
  644. }
  645. /**
  646. * 验证技师认证状态
  647. */
  648. private function validateCoachStatus($coach): void
  649. {
  650. // 验证基本信息认证
  651. $baseInfo = $coach->info;
  652. abort_if(
  653. ! $baseInfo || $baseInfo->state !== TechnicianAuthStatus::PASSED->value,
  654. 422,
  655. '基本信息未认证通过'
  656. );
  657. // 验证资质认证
  658. $qualification = $coach->qual;
  659. abort_if(
  660. ! $qualification || $qualification->state !== TechnicianAuthStatus::PASSED->value,
  661. 422,
  662. '资质信息未认证通过'
  663. );
  664. // 验证实名认证
  665. $realName = $coach->real;
  666. abort_if(
  667. ! $realName || $realName->state !== TechnicianAuthStatus::PASSED->value,
  668. 422,
  669. '实名信息未认证通过'
  670. );
  671. }
  672. /**
  673. * 验证是否可以切换到休息状态
  674. */
  675. private function validateRestStatus(int $currentStatus): void
  676. {
  677. // 只有在空闲或忙碌状态下才能更改为休息状态
  678. abort_if(! in_array($currentStatus, [
  679. TechnicianWorkStatus::FREE->value,
  680. TechnicianWorkStatus::BUSY->value,
  681. ]), 422, '当前状态不能更改为休息状态');
  682. }
  683. /**
  684. * 检查当前时间是否在排班时间内
  685. */
  686. private function checkScheduleTime(int $coachId): bool
  687. {
  688. try {
  689. $schedule = CoachSchedule::where('coach_id', $coachId)
  690. ->where('state', 1)
  691. ->first();
  692. if (! $schedule) {
  693. return false;
  694. }
  695. $timeRanges = json_decode($schedule->time_ranges, true);
  696. if (empty($timeRanges)) {
  697. return false;
  698. }
  699. $currentTime = now()->format('H:i');
  700. foreach ($timeRanges as $range) {
  701. if ($currentTime >= $range['start_time'] && $currentTime <= $range['end_time']) {
  702. return true;
  703. }
  704. }
  705. return false;
  706. } catch (\Exception $e) {
  707. Log::error('检查排班时间异常', [
  708. 'coach_id' => $coachId,
  709. 'error' => $e->getMessage(),
  710. ]);
  711. return false;
  712. }
  713. }
  714. /**
  715. * 更新工作状态缓存
  716. */
  717. private function updateWorkStatusCache(int $coachId, int $status): void
  718. {
  719. try {
  720. $cacheKey = "coach:work_status:{$coachId}";
  721. $cacheData = [
  722. 'status' => $status,
  723. 'updated_at' => now()->toDateTimeString(),
  724. ];
  725. Redis::setex($cacheKey, 86400, json_encode($cacheData));
  726. } catch (\Exception $e) {
  727. Log::error('更新工作状态缓存失败', [
  728. 'coach_id' => $coachId,
  729. 'error' => $e->getMessage(),
  730. ]);
  731. // 缓存更新失败不影响主流程
  732. }
  733. }
  734. /**
  735. * 获取技师工作状态
  736. *
  737. * @param int $coachId 技师ID
  738. */
  739. public function getWorkStatus(int $coachId): array
  740. {
  741. try {
  742. // 验证技师信息
  743. $coach = CoachUser::find($coachId);
  744. abort_if(! $coach, 404, '技师不存在');
  745. // 直接获取技师信息里的work_status
  746. $workStatus = $coach->work_status;
  747. return [
  748. 'work_status' => $workStatus,
  749. 'work_status_text' => TechnicianWorkStatus::fromValue($workStatus)->label(),
  750. 'updated_at' => now()->toDateTimeString(),
  751. ];
  752. } catch (\Exception $e) {
  753. Log::error('获取技师工作状态失败', [
  754. 'coach_id' => $coachId,
  755. 'error' => $e->getMessage(),
  756. 'trace' => $e->getTraceAsString(),
  757. ]);
  758. throw $e;
  759. }
  760. }
  761. /**
  762. * 获取技师排班信息
  763. *
  764. * @param int $userId 用户ID
  765. */
  766. public function getSchedule(int $userId): array
  767. {
  768. try {
  769. // 获取技师信息
  770. $user = MemberUser::with(['coach'])->findOrFail($userId);
  771. $coach = $user->coach;
  772. abort_if(! $coach, 404, '技师信息不存在');
  773. // 先尝试从缓存获取
  774. $cacheKey = "coach:schedule:{$coach->id}";
  775. $cached = Redis::get($cacheKey);
  776. if ($cached) {
  777. return json_decode($cached, true);
  778. }
  779. // 缓存不存在,从数据库获取
  780. $schedule = CoachSchedule::where('coach_id', $coach->id)
  781. ->where('state', 1)
  782. ->first();
  783. $result = [
  784. 'time_ranges' => $schedule ? json_decode($schedule->time_ranges, true) : [],
  785. 'updated_at' => $schedule ? $schedule->updated_at->toDateTimeString() : now()->toDateTimeString(),
  786. ];
  787. // 写入缓存
  788. Redis::setex($cacheKey, 86400, json_encode($result));
  789. // 记录日志
  790. Log::info('获取技师排班信息成功', [
  791. 'coach_id' => $coach->id,
  792. 'schedule' => $result,
  793. ]);
  794. return $result;
  795. } catch (\Exception $e) {
  796. Log::error('获取技师排班信息失败', [
  797. 'user_id' => $userId,
  798. 'error' => $e->getMessage(),
  799. 'trace' => $e->getTraceAsString(),
  800. ]);
  801. throw $e;
  802. }
  803. }
  804. /**
  805. * 验证技师基础信息
  806. *
  807. * @param User $user 用户对象
  808. * @param bool $throwError 是否抛出异常
  809. * @return bool
  810. */
  811. private function validateBasicCoach($user, bool $throwError = true): bool
  812. {
  813. if (!$user || !$user->coach) {
  814. if ($throwError) {
  815. abort_if(!$user, 404, '用户不存在');
  816. abort_if(!$user->coach, 404, '技师信息不存在');
  817. }
  818. return false;
  819. }
  820. return true;
  821. }
  822. /**
  823. * 检查是否存在审核记录
  824. *
  825. * @param CoachUser $coach 技师象
  826. * @param string $type 记录类型(info|qual|real)
  827. * @return bool
  828. */
  829. private function hasPendingRecord($coach, string $type): bool
  830. {
  831. $method = match ($type) {
  832. 'info' => 'infoRecords',
  833. 'qual' => 'qualRecords',
  834. 'real' => 'realRecords',
  835. default => throw new \InvalidArgumentException('Invalid record type')
  836. };
  837. return $coach->{$method}()
  838. ->where('state', TechnicianAuthStatus::AUDITING->value)
  839. ->exists();
  840. }
  841. }