AccountService.php 32 KB

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