AccountService.php 28 KB

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