AccountService.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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. * @param object $qual 资质记录对象
  222. * @return array 格式化后的资质信息
  223. */
  224. private function formatQualification($qual)
  225. {
  226. return [
  227. 'qual_type' => $qual->qual_type,
  228. 'qual_photo' => $qual->qual_photo,
  229. 'business_license' => $qual->business_license,
  230. 'health_cert' => $qual->health_cert,
  231. 'state' => $qual->state,
  232. 'state_text' => TechnicianAuthStatus::fromValue($qual->state)->label(),
  233. 'audit_remark' => $qual->audit_remark,
  234. ];
  235. }
  236. /**
  237. * 格式化实名信息
  238. */
  239. private function formatRealName($real)
  240. {
  241. return [
  242. 'real_name' => $real->real_name,
  243. 'id_card' => $this->maskIdCard($real->id_card),
  244. 'id_card_front_photo' => $real->id_card_front_photo,
  245. 'id_card_back_photo' => $real->id_card_back_photo,
  246. 'id_card_hand_photo' => $real->id_card_hand_photo,
  247. 'state' => $real->state,
  248. 'state_text' => TechnicianAuthStatus::fromValue($real->state)->label(),
  249. 'audit_remark' => $real->audit_remark,
  250. ];
  251. }
  252. /**
  253. * 手机号脱敏
  254. */
  255. private function maskMobile($mobile)
  256. {
  257. return substr_replace($mobile, '****', 3, 4);
  258. }
  259. /**
  260. * 身份证脱敏
  261. */
  262. private function maskIdCard($idCard)
  263. {
  264. return substr_replace($idCard, '****', 6, 8);
  265. }
  266. /**
  267. * 敏感数据脱敏
  268. */
  269. private function maskSensitiveData(array $data)
  270. {
  271. if (isset($data['id_card'])) {
  272. $data['id_card'] = $this->maskIdCard($data['id_card']);
  273. }
  274. if (isset($data['mobile'])) {
  275. $data['mobile'] = $this->maskMobile($data['mobile']);
  276. }
  277. return $data;
  278. }
  279. /**
  280. * 清除技师信息缓存
  281. */
  282. private function clearCoachCache($coachId)
  283. {
  284. Cache::forget(self::CACHE_KEY_PREFIX . $coachId);
  285. }
  286. /**
  287. * 设置定位信息
  288. *
  289. * @param int $coachId 技师ID
  290. * @param float $latitude 纬度
  291. * @param float $longitude 经度
  292. * @param int $type 位置类型 (current:1|common:2)
  293. * @return bool
  294. *
  295. * @throws \Exception
  296. */
  297. public function setLocation($coachId, $latitude, $longitude, $type = TechnicianLocationType::COMMON->value)
  298. {
  299. DB::beginTransaction();
  300. try {
  301. // 验证经纬度参数
  302. if (! is_numeric($latitude) || ! is_numeric($longitude)) {
  303. throw new \Exception('无���的经纬度坐标');
  304. }
  305. // 验证位置类型
  306. if (! in_array($type, [TechnicianLocationType::CURRENT->value, TechnicianLocationType::COMMON->value])) {
  307. throw new \Exception('无效的位置类型');
  308. }
  309. // 生成Redis键
  310. $key = $coachId . '_' . $type;
  311. // 将置信息写入Redis
  312. $result = Redis::geoadd('coach_locations', $longitude, $latitude, $key);
  313. // 同时写入数据库保存历史记录
  314. DB::table('coach_locations')->updateOrInsert(
  315. ['coach_id' => $coachId, 'type' => $type],
  316. [
  317. 'latitude' => $latitude,
  318. 'longitude' => $longitude,
  319. 'updated_at' => now(),
  320. ]
  321. );
  322. DB::commit();
  323. Log::info('技师位置信息设置成功', [
  324. 'coach_id' => $coachId,
  325. 'type' => $type,
  326. 'latitude' => $latitude,
  327. 'longitude' => $longitude,
  328. ]);
  329. return $result;
  330. } catch (\Exception $e) {
  331. DB::rollBack();
  332. Log::error('技师位置信息设置异常', [
  333. 'coach_id' => $coachId,
  334. 'latitude' => $latitude,
  335. 'longitude' => $longitude,
  336. 'type' => $type,
  337. 'error' => $e->getMessage(),
  338. 'file' => $e->getFile(),
  339. 'line' => $e->getLine(),
  340. ]);
  341. throw $e;
  342. }
  343. }
  344. /**
  345. * 获取技师位置信息
  346. *
  347. * @param int $userId 用户ID
  348. * @return array 位置信息
  349. */
  350. public function getLocation($userId)
  351. {
  352. try {
  353. // 改进:直接使用 coach 模型
  354. $user = MemberUser::find($userId);
  355. abort_if(! $user, 404, '用户不存在');
  356. abort_if(! $user->coach, 404, '技师信息不存在');
  357. // 获取常用位置信息
  358. $location = $user->coach->locations()
  359. ->where('type', TechnicianLocationType::COMMON->value)
  360. ->first();
  361. $result = [
  362. 'address' => $location ? $location->location : null,
  363. ];
  364. // 记录日志
  365. Log::info('获取技师常用位置信息成功', [
  366. 'coach_id' => $user->coach->id,
  367. 'location' => $result,
  368. ]);
  369. return $result;
  370. } catch (\Exception $e) {
  371. Log::error('获取技师常用位置信息异常', [
  372. 'coach_id' => $user->coach->id ?? null,
  373. 'error' => $e->getMessage(),
  374. 'file' => $e->getFile(),
  375. 'line' => $e->getLine(),
  376. ]);
  377. throw $e;
  378. }
  379. }
  380. /**
  381. * 设置技师排班时间(每天通用)
  382. *
  383. * @param int $userId 技师用户ID
  384. * @param array $timeRanges 时间段数组 格式: [
  385. * ['start_time' => '09:00', 'end_time' => '12:00'],
  386. * ['start_time' => '14:00', 'end_time' => '18:00']
  387. * ]
  388. *
  389. * @throws \Exception
  390. */
  391. public function setSchedule(int $userId, array $timeRanges): array
  392. {
  393. return DB::transaction(function () use ($userId, $timeRanges) {
  394. try {
  395. // 获取技师信息
  396. $user = MemberUser::with(['coach'])->findOrFail($userId);
  397. $coach = $user->coach;
  398. abort_if(! $coach, 404, '技师信息不存在');
  399. // 验证并排序时间段
  400. $sortedRanges = $this->validateAndSortTimeRanges($timeRanges);
  401. // 创建或更新排班记录
  402. $schedule = CoachSchedule::updateOrCreate(
  403. [
  404. 'coach_id' => $coach->id,
  405. ],
  406. [
  407. 'time_ranges' => json_encode($sortedRanges),
  408. 'state' => 1,
  409. ]
  410. );
  411. // 更新Redis缓存
  412. $this->updateScheduleCache($coach->id, $sortedRanges);
  413. // 记录日志
  414. Log::info('技师排班设置成功', [
  415. 'coach_id' => $coach->id,
  416. 'time_ranges' => $sortedRanges,
  417. ]);
  418. return [
  419. 'status' => true,
  420. 'message' => '排班设置成功',
  421. 'data' => [
  422. 'coach_id' => $coach->id,
  423. 'time_ranges' => $sortedRanges,
  424. 'updated_at' => $schedule->updated_at->toDateTimeString(),
  425. ],
  426. ];
  427. } catch (\Exception $e) {
  428. Log::error('技师排班设置败', [
  429. 'user_id' => $userId,
  430. 'time_ranges' => $timeRanges,
  431. 'error' => $e->getMessage(),
  432. 'trace' => $e->getTraceAsString(),
  433. ]);
  434. throw $e;
  435. }
  436. });
  437. }
  438. /**
  439. * 验证并排序时间段
  440. */
  441. private function validateAndSortTimeRanges(array $timeRanges): array
  442. {
  443. // 验证时���段数组
  444. abort_if(empty($timeRanges), 400, '必须至少设置一个时间段');
  445. // 验证每个时间段格式并转换为分钟数进行比较
  446. $ranges = collect($timeRanges)->map(function ($range) {
  447. abort_if(
  448. ! isset($range['start_time'], $range['end_time']),
  449. 400,
  450. '时间段格式错误'
  451. );
  452. // 验证时间格式
  453. foreach (['start_time', 'end_time'] as $field) {
  454. abort_if(
  455. ! preg_match('/^([01][0-9]|2[0-3]):[0-5][0-9]$/', $range[$field]),
  456. 400,
  457. '时间格式错,应为HH:mm格式'
  458. );
  459. }
  460. // 转换为分钟数便于比较
  461. $startMinutes = $this->timeToMinutes($range['start_time']);
  462. $endMinutes = $this->timeToMinutes($range['end_time']);
  463. // 验证时间先后
  464. abort_if(
  465. $startMinutes >= $endMinutes,
  466. 400,
  467. "时间段 {$range['start_time']}-{$range['end_time']} 结束时间必须大于开始时间"
  468. );
  469. return [
  470. 'start_time' => $range['start_time'],
  471. 'end_time' => $range['end_time'],
  472. 'start_minutes' => $startMinutes,
  473. 'end_minutes' => $endMinutes,
  474. ];
  475. })
  476. ->sortBy('start_minutes')
  477. ->values();
  478. // 验证时间段是否重叠
  479. $ranges->each(function ($range, $index) use ($ranges) {
  480. if ($index > 0) {
  481. $prevRange = $ranges[$index - 1];
  482. abort_if(
  483. $range['start_minutes'] <= $prevRange['end_minutes'],
  484. 400,
  485. "时间段 {$prevRange['start_time']}-{$prevRange['end_time']} 和 " .
  486. "{$range['start_time']}-{$range['end_time']} 之间存在重叠"
  487. );
  488. }
  489. });
  490. // 返回排序后的时间,只保留需要的字段
  491. return $ranges->map(function ($range) {
  492. return [
  493. 'start_time' => $range['start_time'],
  494. 'end_time' => $range['end_time'],
  495. ];
  496. })->toArray();
  497. }
  498. /**
  499. * 将时间转换为分钟数
  500. */
  501. private function timeToMinutes(string $time): int
  502. {
  503. [$hours, $minutes] = explode(':', $time);
  504. return (int) $hours * 60 + (int) $minutes;
  505. }
  506. /**
  507. * 更新Redis缓存
  508. */
  509. private function updateScheduleCache(int $coachId, array $timeRanges): void
  510. {
  511. try {
  512. $cacheKey = "coach:schedule:{$coachId}";
  513. $cacheData = [
  514. 'updated_at' => now()->toDateTimeString(),
  515. 'time_ranges' => $timeRanges,
  516. ];
  517. Redis::setex($cacheKey, 86400, json_encode($cacheData));
  518. // 清除相关的可预约时间段缓存
  519. $this->clearTimeSlotCache($coachId);
  520. } catch (\Exception $e) {
  521. Log::error('更新排班缓存失败', [
  522. 'coach_id' => $coachId,
  523. 'error' => $e->getMessage(),
  524. ]);
  525. // 缓存更新失败不影响主流程
  526. }
  527. }
  528. /**
  529. * 清除可预约时间段缓存
  530. */
  531. public function clearTimeSlotCache(int $coachId): void
  532. {
  533. try {
  534. $pattern = "coach:timeslots:{$coachId}:*";
  535. $keys = Redis::keys($pattern);
  536. if (! empty($keys)) {
  537. Redis::del($keys);
  538. }
  539. } catch (\Exception $e) {
  540. Log::error('清除时间段缓存失败', [
  541. 'coach_id' => $coachId,
  542. 'error' => $e->getMessage(),
  543. ]);
  544. }
  545. }
  546. /**
  547. * 更改技师工作状态
  548. *
  549. * @param int $userId 用户ID
  550. * @param int $status 状态(1:休息中 2:工作中)
  551. */
  552. public function updateWorkStatus(int $userId, int $status): array
  553. {
  554. DB::beginTransaction();
  555. try {
  556. // 获取技师信息
  557. $user = MemberUser::with(['coach', 'coach.infoRecords', 'coach.qualRecords', 'coach.realRecords'])
  558. ->findOrFail($userId);
  559. $coach = $user->coach;
  560. abort_if(! $coach, 404, '技师信息不存在');
  561. // 验证状态值
  562. abort_if(! in_array($status, [1, 2]), 400, '无效的状态值');
  563. // 验证技师认证状态
  564. $this->validateCoachStatus($coach);
  565. // 获取当前时间是否在排班时间内
  566. $isInSchedule = $this->checkScheduleTime($coach->id);
  567. $currentStatus = $coach->work_status;
  568. $newStatus = $status;
  569. // 如果要切换到休息状态
  570. if ($status === 1) {
  571. // 验证当前状态是否允许切换到休息
  572. $this->validateRestStatus($currentStatus);
  573. $newStatus = TechnicianWorkStatus::REST->value;
  574. }
  575. // 如果要切换到工作状态
  576. elseif ($status === 2) {
  577. // 验证是否在排班时间内
  578. abort_if(! $isInSchedule, 422, '当前时间不在排班时间内,无法切换到工作状态');
  579. // 检查是否有进行中的订单
  580. $hasActiveOrder = $coach->orders()
  581. ->whereIn('state', [
  582. OrderStatus::ACCEPTED->value, // 已接单
  583. OrderStatus::DEPARTED->value, // 已出发
  584. OrderStatus::ARRIVED->value, // 已到达
  585. OrderStatus::SERVING->value, // 服务中
  586. ])
  587. ->exists();
  588. // 根据是否有进行中订单决定状态
  589. $newStatus = $hasActiveOrder ?
  590. TechnicianWorkStatus::BUSY->value :
  591. TechnicianWorkStatus::FREE->value;
  592. }
  593. // 如果状态没有变,则不需要更新
  594. if ($currentStatus === $newStatus) {
  595. DB::rollBack();
  596. return [
  597. 'status' => true,
  598. 'message' => '状态未发生变化',
  599. 'data' => [
  600. 'work_status' => $newStatus,
  601. 'work_status_text' => TechnicianWorkStatus::fromValue($newStatus)->label(),
  602. 'updated_at' => now()->toDateTimeString(),
  603. ],
  604. ];
  605. }
  606. // 更新状态
  607. $coach->work_status = $newStatus;
  608. $coach->save();
  609. // 更新Redis缓存
  610. $this->updateWorkStatusCache($coach->id, $newStatus);
  611. DB::commit();
  612. // 记录日志
  613. Log::info('技师工作状态更新成功', [
  614. 'coach_id' => $coach->id,
  615. 'old_status' => $currentStatus,
  616. 'new_status' => $newStatus,
  617. 'updated_at' => now()->toDateTimeString(),
  618. 'in_schedule' => $isInSchedule,
  619. ]);
  620. return [
  621. 'status' => true,
  622. 'message' => '状态更新成功',
  623. 'data' => [
  624. 'work_status' => $newStatus,
  625. 'work_status_text' => TechnicianWorkStatus::fromValue($newStatus)->label(),
  626. 'updated_at' => now()->toDateTimeString(),
  627. ],
  628. ];
  629. } catch (\Exception $e) {
  630. DB::rollBack();
  631. Log::error('技师工作状态更新失败', [
  632. 'user_id' => $userId,
  633. 'status' => $status,
  634. 'error' => $e->getMessage(),
  635. 'trace' => $e->getTraceAsString(),
  636. ]);
  637. throw $e;
  638. }
  639. }
  640. /**
  641. * 验证技师认证状态
  642. */
  643. private function validateCoachStatus($coach): void
  644. {
  645. // 验证基本信息认证
  646. $baseInfo = $coach->info;
  647. abort_if(
  648. ! $baseInfo || $baseInfo->state !== TechnicianAuthStatus::PASSED->value,
  649. 422,
  650. '基本信息未认证通过'
  651. );
  652. // 验证资质认证
  653. $qualification = $coach->qual;
  654. abort_if(
  655. ! $qualification || $qualification->state !== TechnicianAuthStatus::PASSED->value,
  656. 422,
  657. '资质信息未认证通过'
  658. );
  659. // 验证实名认证
  660. $realName = $coach->real;
  661. abort_if(
  662. ! $realName || $realName->state !== TechnicianAuthStatus::PASSED->value,
  663. 422,
  664. '实名信息未认证通过'
  665. );
  666. }
  667. /**
  668. * 验证是否可以切换到休息状态
  669. */
  670. private function validateRestStatus(int $currentStatus): void
  671. {
  672. // 只有在空闲或忙碌状态下才能更改为休息状态
  673. abort_if(! in_array($currentStatus, [
  674. TechnicianWorkStatus::FREE->value,
  675. TechnicianWorkStatus::BUSY->value,
  676. ]), 422, '当前状态不能更改为休息状态');
  677. }
  678. /**
  679. * 检查当前时间是否在排班时间内
  680. */
  681. private function checkScheduleTime(int $coachId): bool
  682. {
  683. try {
  684. $schedule = CoachSchedule::where('coach_id', $coachId)
  685. ->where('state', 1)
  686. ->first();
  687. if (! $schedule) {
  688. return false;
  689. }
  690. $timeRanges = json_decode($schedule->time_ranges, true);
  691. if (empty($timeRanges)) {
  692. return false;
  693. }
  694. $currentTime = now()->format('H:i');
  695. foreach ($timeRanges as $range) {
  696. if ($currentTime >= $range['start_time'] && $currentTime <= $range['end_time']) {
  697. return true;
  698. }
  699. }
  700. return false;
  701. } catch (\Exception $e) {
  702. Log::error('检查排班时间异���', [
  703. 'coach_id' => $coachId,
  704. 'error' => $e->getMessage(),
  705. ]);
  706. return false;
  707. }
  708. }
  709. /**
  710. * 更新工作状态缓存
  711. */
  712. private function updateWorkStatusCache(int $coachId, int $status): void
  713. {
  714. try {
  715. $cacheKey = "coach:work_status:{$coachId}";
  716. $cacheData = [
  717. 'status' => $status,
  718. 'updated_at' => now()->toDateTimeString(),
  719. ];
  720. Redis::setex($cacheKey, 86400, json_encode($cacheData));
  721. } catch (\Exception $e) {
  722. Log::error('更新工作状态缓存失败', [
  723. 'coach_id' => $coachId,
  724. 'error' => $e->getMessage(),
  725. ]);
  726. // 缓存更新失败不影响主流程
  727. }
  728. }
  729. /**
  730. * 获取技师工作状态
  731. *
  732. * @param int $coachId 技师ID
  733. */
  734. public function getWorkStatus(int $coachId): array
  735. {
  736. try {
  737. // 验证技师信息
  738. $coach = CoachUser::find($coachId);
  739. abort_if(! $coach, 404, '技师不存在');
  740. // 直接获取技师信息里的work_status
  741. $workStatus = $coach->work_status;
  742. return [
  743. 'work_status' => $workStatus,
  744. 'work_status_text' => TechnicianWorkStatus::fromValue($workStatus)->label(),
  745. 'updated_at' => now()->toDateTimeString(),
  746. ];
  747. } catch (\Exception $e) {
  748. Log::error('获取技师工作状态失败', [
  749. 'coach_id' => $coachId,
  750. 'error' => $e->getMessage(),
  751. 'trace' => $e->getTraceAsString(),
  752. ]);
  753. throw $e;
  754. }
  755. }
  756. /**
  757. * 获取技师排班信息
  758. *
  759. * @param int $userId 用户ID
  760. */
  761. public function getSchedule(int $userId): array
  762. {
  763. try {
  764. // 获取技师信息
  765. $user = MemberUser::with(['coach'])->findOrFail($userId);
  766. $coach = $user->coach;
  767. abort_if(! $coach, 404, '技师信息不存在');
  768. // 先尝试从缓存获取
  769. $cacheKey = "coach:schedule:{$coach->id}";
  770. $cached = Redis::get($cacheKey);
  771. if ($cached) {
  772. return json_decode($cached, true);
  773. }
  774. // 缓存不存在,从数据库获取
  775. $schedule = CoachSchedule::where('coach_id', $coach->id)
  776. ->where('state', 1)
  777. ->first();
  778. $result = [
  779. 'time_ranges' => $schedule ? json_decode($schedule->time_ranges, true) : [],
  780. 'updated_at' => $schedule ? $schedule->updated_at->toDateTimeString() : now()->toDateTimeString(),
  781. ];
  782. // 写入缓存
  783. Redis::setex($cacheKey, 86400, json_encode($result));
  784. // 记录日志
  785. Log::info('获取技师排班信息成功', [
  786. 'coach_id' => $coach->id,
  787. 'schedule' => $result,
  788. ]);
  789. return $result;
  790. } catch (\Exception $e) {
  791. Log::error('获取技师排班信息失败', [
  792. 'user_id' => $userId,
  793. 'error' => $e->getMessage(),
  794. 'trace' => $e->getTraceAsString(),
  795. ]);
  796. throw $e;
  797. }
  798. }
  799. /**
  800. * 验证技师基础信息
  801. *
  802. * @param User $user 用户对象
  803. * @param bool $throwError 是否抛出异常
  804. * @return bool
  805. */
  806. private function validateBasicCoach($user, bool $throwError = true): bool
  807. {
  808. if (!$user || !$user->coach) {
  809. if ($throwError) {
  810. abort_if(!$user, 404, '用户不存在');
  811. abort_if(!$user->coach, 404, '技师信息不存在');
  812. }
  813. return false;
  814. }
  815. return true;
  816. }
  817. /**
  818. * 检查是否存在待审核记录
  819. *
  820. * @param CoachUser $coach 技师���象
  821. * @param string $type 记录类型(info|qual|real)
  822. * @return bool
  823. */
  824. private function hasPendingRecord($coach, string $type): bool
  825. {
  826. $method = match ($type) {
  827. 'info' => 'infoRecords',
  828. 'qual' => 'qualRecords',
  829. 'real' => 'realRecords',
  830. default => throw new \InvalidArgumentException('Invalid record type')
  831. };
  832. return $coach->{$method}()
  833. ->where('state', TechnicianAuthStatus::AUDITING->value)
  834. ->exists();
  835. }
  836. }