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