AccountService.php 25 KB

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