AccountService.php 31 KB

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