AccountService.php 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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\CoachLocation;
  7. use App\Models\CoachSchedule;
  8. use App\Enums\TechnicianStatus;
  9. use App\Models\CoachInfoRecord;
  10. use Illuminate\Support\Facades\DB;
  11. use App\Enums\TechnicianAuthStatus;
  12. use App\Enums\TechnicianWorkStatus;
  13. use Illuminate\Support\Facades\Log;
  14. use Illuminate\Support\Facades\Auth;
  15. use App\Enums\TechnicianLocationType;
  16. use Illuminate\Support\Facades\Cache;
  17. use Illuminate\Support\Facades\Redis;
  18. use App\Traits\LocationValidationTrait;
  19. class AccountService
  20. {
  21. use LocationValidationTrait;
  22. private const CACHE_KEY_PREFIX = 'coach_info_';
  23. private const CACHE_TTL = 300; // 5分钟
  24. /**
  25. * 提交技师基本信息
  26. * 包括个人基础资料的提交和审核
  27. *
  28. * 业务流程:
  29. * 1. 验证技师信息存在性
  30. * 2. 检查是否有待审核的记录
  31. * 3. 处理生活照片数据
  32. * 4. 创建新的基本信息记录
  33. * 5. 清除相关缓存
  34. *
  35. * 注意事项:
  36. * - 同一时间只能有一条待审核记录
  37. * - 审核不通过可以重新提交
  38. * - 头像和生活照片不限制格式
  39. * - 除性别和手机号外,其他字段均为可选
  40. * - 手机号会进行脱敏处理
  41. *
  42. * @param User $user 当前认证用户
  43. * @param array $data 基本信息数据,包含:
  44. * - nickname: string|null 昵称(可选)
  45. * - avatar: string|null 头像图片(可选)
  46. * - life_photos: array|null 生活照片数组(可选)
  47. * - gender: string 性别(1:男 2:女)
  48. * - mobile: string 手机号
  49. * - birthday: string|null 出生日期(可选)
  50. * - work_years: int|null 工作年限(可选)
  51. * - intention_city: string|null 意向城市(可选)
  52. * - introduction: string|null 个人简介(可选)
  53. * @return array 返回结果,包含:
  54. * - message: string 提示信息
  55. * @throws \Exception 当验证失败或保存失败时抛出异常
  56. */
  57. public function submitBaseInfo($user, array $data)
  58. {
  59. // 开启数据库事务,确保数据一致性
  60. DB::beginTransaction();
  61. try {
  62. // 验证技师信息是否存在,不存在则抛出404异常
  63. abort_if(!$user->coach, 404, '技师信息不存在');
  64. // 检查是否有待审核的记录,避免重复提交
  65. // 如果存在待审核记录,则抛出422异常
  66. $pendingRecord = $this->hasPendingRecord($user->coach, 'info');
  67. abort_if($pendingRecord, 422, '已有待审核的基本信息记录');
  68. // 处理生活照片数据:将数组转换为JSON格式存储
  69. // 如果没有生活照片数据,则保持原样
  70. if (isset($data['life_photos'])) {
  71. // 使用array_values确保数组索引连续
  72. $data['life_photos'] = json_encode(array_values($data['life_photos']));
  73. }
  74. // 创建新的基本信息记录,设置为待审核状态
  75. // 合并用户提交的数据和审核状态
  76. $user->coach->infoRecords()->create(array_merge($data, [
  77. 'state' => TechnicianAuthStatus::AUDITING->value, // 设置为待审核状态
  78. ]));
  79. // 清除技师信息缓存,确保数据一致性
  80. // 避免用户获取到旧的缓存数据
  81. $this->clearCoachCache($user->coach->id);
  82. // 提交事务,确保所有操作成功
  83. DB::commit();
  84. // 返回成功结果
  85. return ['message' => '基本信息提交成功'];
  86. } catch (\Exception $e) {
  87. // 发生异常时回滚事务,确保数据一致性
  88. DB::rollBack();
  89. // 向上抛出异常,由调用方处理
  90. throw $e;
  91. }
  92. }
  93. /**
  94. * 提交技师资质信息
  95. * 包括资质证书照片、营业执照和健康证照片的提交和审核
  96. *
  97. * 业务流程:
  98. * 1. 验证技师信息存在性
  99. * 2. 检查是否有待审核的记录
  100. * 3. 创建新的资质审核记录
  101. * 4. 清除相关缓存
  102. *
  103. * 注意事项:
  104. * - 同一时间只能有一条待审核记录
  105. * - 审核不通过可以重新提交
  106. * - 所有图片数据不限制格式
  107. *
  108. * @param User $user 当前认证用户
  109. * @param array $data 资质信息数据,包含:
  110. * - qual_type: int 资质类型(1:初级 2:中级 3:高级)
  111. * - qual_photo: string 资质证书照片
  112. * - business_license: string 营业执照照片
  113. * - health_cert: string 健康证照片
  114. * @return array 返回结果,包含:
  115. * - message: string 提示信息
  116. * - data: array 详细数据
  117. * - record_id: int 记录ID
  118. * - state: int 状态值
  119. * - state_text: string 状态文本
  120. * @throws \Exception 当验证失败或保存失败时抛出异常
  121. */
  122. public function submitQualification($user, array $data)
  123. {
  124. // 开启数据库事务
  125. DB::beginTransaction();
  126. try {
  127. // 验证技师信息是否存在
  128. abort_if(!$user->coach, 404, '技师信息不存在');
  129. // 检查是否有待审核的记录,避免重复提交
  130. $pendingRecord = $this->hasPendingRecord($user->coach, 'qual');
  131. abort_if($pendingRecord, 422, '已有待审核的资质信息记录');
  132. // 创建新的资质审核记录,设置为待审核状态
  133. $record = $user->coach->qualRecords()->create(array_merge($data, [
  134. 'state' => TechnicianAuthStatus::AUDITING->value,
  135. ]));
  136. // 清除技师信息缓存,确保数据一致性
  137. $this->clearCoachCache($user->coach->id);
  138. // 提交事务
  139. DB::commit();
  140. // 返回成功结果
  141. return [
  142. 'message' => '资质信息提交成功',
  143. 'data' => [
  144. 'record_id' => $record->id,
  145. 'state' => TechnicianAuthStatus::AUDITING->value,
  146. 'state_text' => TechnicianAuthStatus::fromValue(TechnicianAuthStatus::AUDITING->value)->label(),
  147. ]
  148. ];
  149. } catch (\Exception $e) {
  150. // 发生异常时回滚事务
  151. DB::rollBack();
  152. throw $e;
  153. }
  154. }
  155. /**
  156. * 提交实名认证信息
  157. * 包括姓名(可选)、身份证号(可选)和三张身份证照片的提交和审核
  158. *
  159. * 业务流程:
  160. * 1. 验证技师信息存在性
  161. * 2. 检查是否有待审核的记录
  162. * 3. 创建新的实名认证记录
  163. * 4. 清除相关缓存
  164. *
  165. * 注意事项:
  166. * - 同一时间只能有一条待审核记录
  167. * - 审核不通过可以重新提交
  168. * - 所有图片数据不限制格式
  169. * - 姓名和身份证号为可选字段
  170. * - 敏感信息会进行脱敏处理
  171. *
  172. * @param User $user 当前认证用户
  173. * @param array $data 实名认证数据,包含:
  174. * - real_name: string|null 真实姓名(可选)
  175. * - id_card: string|null 身份证号(可选)
  176. * - id_card_front_photo: string 身份证正面照片
  177. * - id_card_back_photo: string 身份证反面照片
  178. * - id_card_hand_photo: string 手持身份证照片
  179. * @return array 返回结果
  180. * @throws \Exception 当验证失败或保存失败时抛出异常
  181. */
  182. public function submitRealName($user, array $data)
  183. {
  184. // 开启数据库事务
  185. DB::beginTransaction();
  186. try {
  187. // 验证技师信息是否存在
  188. abort_if(!$user->coach, 404, '技师信息不存在');
  189. // TODO: 临时清除技师信息,便于对接调试
  190. $this->clearCoachCache($user->coach->id);
  191. // 检查是否有待审核的记录,避免重复提交
  192. $pendingRecord = $this->hasPendingRecord($user->coach, 'real');
  193. abort_if($pendingRecord, 422, '已有待审核的实名认证信息');
  194. // 创建新的实名认证记录,设置为待审核状态
  195. $user->coach->realRecords()->create(array_merge($data, [
  196. 'state' => TechnicianAuthStatus::AUDITING->value,
  197. ]));
  198. // 清除技师信息缓存,确保数据一致性
  199. $this->clearCoachCache($user->coach->id);
  200. // 提交事务
  201. DB::commit();
  202. // 返回成功结果
  203. return ['message' => '实名认证信息提交成功'];
  204. } catch (\Exception $e) {
  205. // 发生异常时回滚事务
  206. DB::rollBack();
  207. throw $e;
  208. }
  209. }
  210. /**
  211. * 获取技师信息
  212. * 包括基本信息、资质信息和实名认证信息
  213. *
  214. * 业务流程:
  215. * 1. 验证用户和技师信息存在性
  216. * 2. 尝试从缓存获取数据
  217. * 3. 如果缓存不存在,从数据库获取并缓存
  218. *
  219. * 注意事项:
  220. * - 所有图片数据不限制格式
  221. * - 敏感信息会进行脱敏处理
  222. * - 使用缓存提高性能
  223. *
  224. * @param User $user 当前认证用户
  225. * @return array 返回技师所有信息,包含:
  226. * - base_info: array|null 基本信息
  227. * - qualification: array|null 资质信息
  228. * - real_name: array|null 实名认证信息
  229. * @throws \Exception 当验证失败时抛出异常
  230. */
  231. public function getCoachInfo($user)
  232. {
  233. // 验证用户和技师信息
  234. abort_if(!$user, 404, '用户不存在');
  235. abort_if(!$user->coach, 404, '技师信息不存在');
  236. // 尝试从缓存获取数据
  237. return Cache::remember(
  238. self::CACHE_KEY_PREFIX . $user->coach->id,
  239. self::CACHE_TTL,
  240. function () use ($user) {
  241. // 缓存不存在时,从数据库获取
  242. return $this->fetchCoachInfo($user->coach);
  243. }
  244. );
  245. }
  246. /**
  247. * 获取技师详细信息
  248. * 从数据库获取最新的认证记录信息
  249. *
  250. * @param CoachUser $coach 技师对象
  251. * @return array 格式化后的技师信息
  252. */
  253. private function fetchCoachInfo($coach)
  254. {
  255. // 获取最新的各类认证记录
  256. $baseInfo = $coach->infoRecords()->latest()->first();
  257. $qualification = $coach->qualRecords()->latest()->first();
  258. $realName = $coach->realRecords()->latest()->first();
  259. // 格式化并返回数据
  260. return [
  261. 'base_info' => $baseInfo ? $this->formatBaseInfo($baseInfo) : null,
  262. 'qualification' => $qualification ? $this->formatQualification($qualification) : null,
  263. 'real_name' => $realName ? $this->formatRealName($realName) : null,
  264. ];
  265. }
  266. /**
  267. * 格式化基本信息
  268. * 处理技师基本信息的展示格式
  269. *
  270. * @param object $info 基本信息记录对象
  271. * @return array 格式化后的基本信息
  272. */
  273. private function formatBaseInfo($info)
  274. {
  275. // 返回格式化后的基本信息,包含状态文本
  276. return [
  277. 'nickname' => $info->nickname,
  278. 'avatar' => $info->avatar, // 支持任意格式的图片数据
  279. 'life_photos' => $info->life_photos ?? [], // 生活照片数组
  280. 'gender' => $info->gender,
  281. 'mobile' => $this->maskMobile($info->mobile), // 手机号脱敏处理
  282. 'birthday' => $info->birthday,
  283. 'work_years' => $info->work_years,
  284. 'intention_city' => $info->intention_city,
  285. 'introduction' => $info->introduction,
  286. 'state' => $info->state,
  287. 'state_text' => TechnicianAuthStatus::fromValue($info->state)->label(),
  288. 'audit_remark' => $info->audit_remark,
  289. ];
  290. }
  291. /**
  292. * 格式化资质信息
  293. * 处理技师资质信息的展示格式
  294. *
  295. * @param object $qual 资质记录对象
  296. * @return array 格式化后的资质信息
  297. */
  298. private function formatQualification($qual)
  299. {
  300. // 资质类型文本映射
  301. $qualTypeMap = [
  302. 1 => '初级按摩师',
  303. 2 => '中级按摩师',
  304. 3 => '高级按摩师',
  305. ];
  306. // 返回格式化后的资质信息,包含状态文本
  307. return [
  308. 'qual_type' => $qual->qual_type,
  309. 'qual_type_text' => $qualTypeMap[$qual->qual_type] ?? '未知类型', // 添加类型文本
  310. 'qual_photo' => $qual->qual_photo, // 支持任意格式的图片数据
  311. 'business_license' => $qual->business_license, // 支持任意格式的图片数据
  312. 'health_cert' => $qual->health_cert, // 支持任意格式的图片数据
  313. 'state' => $qual->state,
  314. 'state_text' => TechnicianAuthStatus::fromValue($qual->state)->label(),
  315. 'audit_remark' => $qual->audit_remark,
  316. ];
  317. }
  318. /**
  319. * 格式化实名信息
  320. * 处理技师实名认证信息的展示格式
  321. *
  322. * @param object $real 实名认证记录对象
  323. * @return array 格式化后的实名信息
  324. */
  325. private function formatRealName($real)
  326. {
  327. // 返回格式化后的实名信息,包含状态文本和脱敏处理
  328. return [
  329. 'real_name' => $real->real_name,
  330. 'id_card' => $this->maskIdCard($real->id_card), // 身份证号脱敏处理
  331. 'id_card_front_photo' => $real->id_card_front_photo, // 支持任意格式的图片数据
  332. 'id_card_back_photo' => $real->id_card_back_photo, // 支持任意格式的图片数据
  333. 'id_card_hand_photo' => $real->id_card_hand_photo, // 支持任意格式的图片数据
  334. 'state' => $real->state,
  335. 'state_text' => TechnicianAuthStatus::fromValue($real->state)->label(),
  336. 'audit_remark' => $real->audit_remark,
  337. ];
  338. }
  339. /**
  340. * 手机号脱敏
  341. * 将手机号中间4位替换为****
  342. *
  343. * @param string $mobile 原始手机号
  344. * @return string 脱敏后的手机号
  345. */
  346. private function maskMobile($mobile)
  347. {
  348. return substr_replace($mobile, '****', 3, 4);
  349. }
  350. /**
  351. * 身份证号脱敏
  352. * 将身份证号中间8位替换为****
  353. *
  354. * @param string|null $idCard 原始身份证号
  355. * @return string|null 脱敏后的身份证号
  356. */
  357. private function maskIdCard($idCard)
  358. {
  359. if (!$idCard) {
  360. return null;
  361. }
  362. return substr_replace($idCard, '****', 6, 8);
  363. }
  364. /**
  365. * 清除技师信息缓存
  366. */
  367. private function clearCoachCache($coachId)
  368. {
  369. Cache::forget(self::CACHE_KEY_PREFIX . $coachId);
  370. }
  371. /**
  372. * 设置定位信息
  373. * 支持设置当前位置和常用位置,包含地理位置和行政区划信息
  374. *
  375. * 业务流程:
  376. * 1. 验证经纬度参数
  377. * 2. 验证位置类型
  378. * 3. 保存到Redis的地理位置数据结构
  379. * 4. 同步保存到据库
  380. *
  381. * @param int $coachId 技师ID
  382. * @param float $latitude 纬度
  383. * @param float $longitude 经度
  384. * @param int $type 位置类型 (current:1|common:2)
  385. * @param array $locationInfo 位置信息,包含:
  386. * - province: string|null 省份
  387. * - city: string|null 城市
  388. * - district: string|null 区县
  389. * - address: string|null 详细地址
  390. * - adcode: string|null 行政区划代码
  391. * @return bool 返回缓存更新结果
  392. * @throws \Exception 当验证失败或保存失败时抛出异常
  393. */
  394. public function setLocation($coachId, $latitude, $longitude, $type = TechnicianLocationType::COMMON->value, array $locationInfo = [])
  395. {
  396. // 使用事务确保数据一致性
  397. return DB::transaction(function () use ($coachId, $latitude, $longitude, $type, $locationInfo) {
  398. // 验证经纬度的有效性(-90≤纬度≤90,-180≤经度≤180)
  399. $this->validateCoordinates($latitude, $longitude);
  400. // 验证位置类型是否为有效值(1:当前位置 2:常用位置)
  401. $this->validateLocationType($type);
  402. // 格式化并验证位置信息(省市区、地址、行政区划代码)
  403. $formattedLocation = $this->formatLocationInfo($locationInfo);
  404. // 更新Redis地理位置缓存,用于实时位置查询
  405. $result = $this->updateLocationCache($coachId, $longitude, $latitude, $type);
  406. // 同步更新数据库,保存历史位置记录
  407. CoachLocation::updateOrCreate(
  408. // 查询条件:根据技师ID和位置类型确定唯一记录
  409. ['coach_id' => $coachId, 'type' => $type],
  410. // 更新数据:合并基础位置信息和格式化后的地址信息
  411. array_merge([
  412. 'latitude' => $latitude,
  413. 'longitude' => $longitude,
  414. ], $formattedLocation)
  415. );
  416. return $result;
  417. });
  418. }
  419. /**
  420. * 获取技师位置信息
  421. *
  422. * @param int $userId 用户ID
  423. * @return array 位置信息
  424. */
  425. public function getLocation($userId)
  426. {
  427. try {
  428. // 改进:直接使用 coach 模型
  429. $user = MemberUser::find($userId);
  430. abort_if(! $user, 404, '用户不存在');
  431. abort_if(! $user->coach, 404, '技师信息不存在');
  432. // 获取常用位置信息
  433. $location = $user->coach->locations()
  434. ->where('type', TechnicianLocationType::COMMON->value)
  435. ->first();
  436. $result = [
  437. 'address' => $location ? $location->location : null,
  438. ];
  439. // 记录日志
  440. Log::info('获取技师常用位置信息成功', [
  441. 'coach_id' => $user->coach->id,
  442. 'location' => $result,
  443. ]);
  444. return $result;
  445. } catch (\Exception $e) {
  446. Log::error('获取技师常用位置信息异常', [
  447. 'coach_id' => $user->coach->id ?? null,
  448. 'error' => $e->getMessage(),
  449. 'file' => $e->getFile(),
  450. 'line' => $e->getLine(),
  451. ]);
  452. throw $e;
  453. }
  454. }
  455. /**
  456. * 设置技师排班时间(每天通用)
  457. *
  458. * @param int $userId 技师用户ID
  459. * @param array $timeRanges 时间段数组 格式: [
  460. * ['start_time' => '09:00', 'end_time' => '12:00'],
  461. * ['start_time' => '14:00', 'end_time' => '18:00']
  462. * ]
  463. *
  464. * @throws \Exception
  465. */
  466. public function setSchedule(int $userId, array $timeRanges): array
  467. {
  468. return DB::transaction(function () use ($userId, $timeRanges) {
  469. try {
  470. // 获取技师信息
  471. $user = MemberUser::with(['coach'])->findOrFail($userId);
  472. $coach = $user->coach;
  473. abort_if(! $coach, 404, '技师信息不存在');
  474. // 验证并排序时间段
  475. $sortedRanges = $this->validateAndSortTimeRanges($timeRanges);
  476. // 创建或更新排班记录
  477. $schedule = CoachSchedule::updateOrCreate(
  478. [
  479. 'coach_id' => $coach->id,
  480. ],
  481. [
  482. 'time_ranges' => json_encode($sortedRanges),
  483. 'state' => 1,
  484. ]
  485. );
  486. // 更新Redis缓存
  487. $this->updateScheduleCache($coach->id, $sortedRanges);
  488. // 记录日志
  489. Log::info('技师排班设置成功', [
  490. 'coach_id' => $coach->id,
  491. 'time_ranges' => $sortedRanges,
  492. ]);
  493. return [
  494. 'status' => true,
  495. 'message' => '排班设置成功',
  496. 'data' => [
  497. 'coach_id' => $coach->id,
  498. 'time_ranges' => $sortedRanges,
  499. 'updated_at' => $schedule->updated_at->toDateTimeString(),
  500. ],
  501. ];
  502. } catch (\Exception $e) {
  503. Log::error('技师排班设置败', [
  504. 'user_id' => $userId,
  505. 'time_ranges' => $timeRanges,
  506. 'error' => $e->getMessage(),
  507. 'trace' => $e->getTraceAsString(),
  508. ]);
  509. throw $e;
  510. }
  511. });
  512. }
  513. /**
  514. * 验证并排序时间段
  515. */
  516. private function validateAndSortTimeRanges(array $timeRanges): array
  517. {
  518. // 验证时间段数组
  519. abort_if(empty($timeRanges), 400, '必须至少设置一个时间段');
  520. // 验证每个时间段格式并转换为分钟数进行比较
  521. $ranges = collect($timeRanges)->map(function ($range) {
  522. abort_if(
  523. ! isset($range['start_time'], $range['end_time']),
  524. 400,
  525. '时间段格式错误'
  526. );
  527. // 验证时间格式
  528. foreach (['start_time', 'end_time'] as $field) {
  529. abort_if(
  530. ! preg_match('/^([01][0-9]|2[0-3]):[0-5][0-9]$/', $range[$field]),
  531. 400,
  532. '时间格式错,应为HH:mm格式'
  533. );
  534. }
  535. // 转换为分钟数便于比较
  536. $startMinutes = $this->timeToMinutes($range['start_time']);
  537. $endMinutes = $this->timeToMinutes($range['end_time']);
  538. // 验证时间先后
  539. abort_if(
  540. $startMinutes >= $endMinutes,
  541. 400,
  542. "时间段 {$range['start_time']}-{$range['end_time']} 结束时间必须大于开始时间"
  543. );
  544. return [
  545. 'start_time' => $range['start_time'],
  546. 'end_time' => $range['end_time'],
  547. 'start_minutes' => $startMinutes,
  548. 'end_minutes' => $endMinutes,
  549. ];
  550. })
  551. ->sortBy('start_minutes')
  552. ->values();
  553. // 验证时间段是否重叠
  554. $ranges->each(function ($range, $index) use ($ranges) {
  555. if ($index > 0) {
  556. $prevRange = $ranges[$index - 1];
  557. abort_if(
  558. $range['start_minutes'] <= $prevRange['end_minutes'],
  559. 400,
  560. "时间段 {$prevRange['start_time']}-{$prevRange['end_time']} 和 " .
  561. "{$range['start_time']}-{$range['end_time']} 之间存在重叠"
  562. );
  563. }
  564. });
  565. // 返回排序后的时间,只保留需要的字段
  566. return $ranges->map(function ($range) {
  567. return [
  568. 'start_time' => $range['start_time'],
  569. 'end_time' => $range['end_time'],
  570. ];
  571. })->toArray();
  572. }
  573. /**
  574. * 将时间转换为分钟数
  575. */
  576. private function timeToMinutes(string $time): int
  577. {
  578. [$hours, $minutes] = explode(':', $time);
  579. return (int) $hours * 60 + (int) $minutes;
  580. }
  581. /**
  582. * 更新Redis缓存
  583. */
  584. private function updateScheduleCache(int $coachId, array $timeRanges): void
  585. {
  586. try {
  587. $cacheKey = "coach:schedule:{$coachId}";
  588. $cacheData = [
  589. 'updated_at' => now()->toDateTimeString(),
  590. 'time_ranges' => $timeRanges,
  591. ];
  592. Redis::setex($cacheKey, 86400, json_encode($cacheData));
  593. // 清除相关的可预约时间段缓存
  594. $this->clearTimeSlotCache($coachId);
  595. } catch (\Exception $e) {
  596. Log::error('更新排班缓存失败', [
  597. 'coach_id' => $coachId,
  598. 'error' => $e->getMessage(),
  599. ]);
  600. // 缓存更新失败不影响主流程
  601. }
  602. }
  603. /**
  604. * 清除可预约时间段缓存
  605. */
  606. public function clearTimeSlotCache(int $coachId): void
  607. {
  608. try {
  609. $pattern = "coach:timeslots:{$coachId}:*";
  610. $keys = Redis::keys($pattern);
  611. if (! empty($keys)) {
  612. Redis::del($keys);
  613. }
  614. } catch (\Exception $e) {
  615. Log::error('清除时间段缓存失败', [
  616. 'coach_id' => $coachId,
  617. 'error' => $e->getMessage(),
  618. ]);
  619. }
  620. }
  621. /**
  622. * 更改技师工作状态
  623. *
  624. * @param int $userId 用户ID
  625. * @param int $status 状态(1:休息中 2:工作中)
  626. */
  627. public function updateWorkStatus(int $userId, int $status): array
  628. {
  629. DB::beginTransaction();
  630. try {
  631. // 获取技师信息
  632. $user = MemberUser::with(['coach', 'coach.infoRecords', 'coach.qualRecords', 'coach.realRecords'])
  633. ->findOrFail($userId);
  634. $coach = $user->coach;
  635. abort_if(! $coach, 404, '技师信息不存在');
  636. // 验证状态值
  637. abort_if(! in_array($status, [1, 2]), 400, '无效的状态值');
  638. // 验证技师认证状态
  639. $this->validateCoachStatus($coach);
  640. // 获取当前时间是否在排班时间内
  641. $isInSchedule = $this->checkScheduleTime($coach->id);
  642. $currentStatus = $coach->work_status;
  643. $newStatus = $status;
  644. // 如果要切换到休息状态
  645. if ($status === 1) {
  646. // 验证当前状态是否允许切换到休息
  647. $this->validateRestStatus($currentStatus);
  648. $newStatus = TechnicianWorkStatus::REST->value;
  649. }
  650. // 如果要切换到工作状态
  651. elseif ($status === 2) {
  652. // 验证是否在排班时间内
  653. abort_if(! $isInSchedule, 422, '当前时间不在排班时间内,无法切换到工作状态');
  654. // 检查是否有进行中的订单
  655. $hasActiveOrder = $coach->orders()
  656. ->whereIn('state', [
  657. OrderStatus::ACCEPTED->value, // 已接单
  658. OrderStatus::DEPARTED->value, // 已出发
  659. OrderStatus::ARRIVED->value, // 已到达
  660. OrderStatus::SERVING->value, // 服务中
  661. ])
  662. ->exists();
  663. // 根据是否有进行中订单决定状态
  664. $newStatus = $hasActiveOrder ?
  665. TechnicianWorkStatus::BUSY->value :
  666. TechnicianWorkStatus::FREE->value;
  667. }
  668. // 如果状态没有变,则不需要更新
  669. if ($currentStatus === $newStatus) {
  670. DB::rollBack();
  671. return [
  672. 'status' => true,
  673. 'message' => '状态未发生变化',
  674. 'data' => [
  675. 'work_status' => $newStatus,
  676. 'work_status_text' => TechnicianWorkStatus::fromValue($newStatus)->label(),
  677. 'updated_at' => now()->toDateTimeString(),
  678. ],
  679. ];
  680. }
  681. // 更新状态
  682. $coach->work_status = $newStatus;
  683. $coach->save();
  684. // 更新Redis缓存
  685. $this->updateWorkStatusCache($coach->id, $newStatus);
  686. DB::commit();
  687. // 记录日志
  688. Log::info('技师工作状态更新成功', [
  689. 'coach_id' => $coach->id,
  690. 'old_status' => $currentStatus,
  691. 'new_status' => $newStatus,
  692. 'updated_at' => now()->toDateTimeString(),
  693. 'in_schedule' => $isInSchedule,
  694. ]);
  695. return [
  696. 'status' => true,
  697. 'message' => '状态更新成功',
  698. 'data' => [
  699. 'work_status' => $newStatus,
  700. 'work_status_text' => TechnicianWorkStatus::fromValue($newStatus)->label(),
  701. 'updated_at' => now()->toDateTimeString(),
  702. ],
  703. ];
  704. } catch (\Exception $e) {
  705. DB::rollBack();
  706. Log::error('技师工作状态更新失败', [
  707. 'user_id' => $userId,
  708. 'status' => $status,
  709. 'error' => $e->getMessage(),
  710. 'trace' => $e->getTraceAsString(),
  711. ]);
  712. throw $e;
  713. }
  714. }
  715. /**
  716. * 验证技师认证状态
  717. */
  718. private function validateCoachStatus($coach): void
  719. {
  720. // 验证基本信息认证
  721. $baseInfo = $coach->info;
  722. abort_if(
  723. ! $baseInfo || $baseInfo->state !== TechnicianAuthStatus::PASSED->value,
  724. 422,
  725. '基本信息未认证通过'
  726. );
  727. // 验证资质认证
  728. $qualification = $coach->qual;
  729. abort_if(
  730. ! $qualification || $qualification->state !== TechnicianAuthStatus::PASSED->value,
  731. 422,
  732. '资质信息未认证通过'
  733. );
  734. // 验证实名认证
  735. $realName = $coach->real;
  736. abort_if(
  737. ! $realName || $realName->state !== TechnicianAuthStatus::PASSED->value,
  738. 422,
  739. '实名信息未认证通过'
  740. );
  741. }
  742. /**
  743. * 验证是否可以切换到休息状态
  744. */
  745. private function validateRestStatus(int $currentStatus): void
  746. {
  747. // 只有在空闲或忙碌状态下才能改为休息状态
  748. abort_if(! in_array($currentStatus, [
  749. TechnicianWorkStatus::FREE->value,
  750. TechnicianWorkStatus::BUSY->value,
  751. ]), 422, '当前状态不能更改为休息状态');
  752. }
  753. /**
  754. * 检查当前时间是否在排班时间内
  755. */
  756. private function checkScheduleTime(int $coachId): bool
  757. {
  758. try {
  759. $schedule = CoachSchedule::where('coach_id', $coachId)
  760. ->where('state', 1)
  761. ->first();
  762. if (! $schedule) {
  763. return false;
  764. }
  765. $timeRanges = json_decode($schedule->time_ranges, true);
  766. if (empty($timeRanges)) {
  767. return false;
  768. }
  769. $currentTime = now()->format('H:i');
  770. foreach ($timeRanges as $range) {
  771. if ($currentTime >= $range['start_time'] && $currentTime <= $range['end_time']) {
  772. return true;
  773. }
  774. }
  775. return false;
  776. } catch (\Exception $e) {
  777. Log::error('检查排班时间异常', [
  778. 'coach_id' => $coachId,
  779. 'error' => $e->getMessage(),
  780. ]);
  781. return false;
  782. }
  783. }
  784. /**
  785. * 更新工作状态缓存
  786. */
  787. private function updateWorkStatusCache(int $coachId, int $status): void
  788. {
  789. try {
  790. $cacheKey = "coach:work_status:{$coachId}";
  791. $cacheData = [
  792. 'status' => $status,
  793. 'updated_at' => now()->toDateTimeString(),
  794. ];
  795. Redis::setex($cacheKey, 86400, json_encode($cacheData));
  796. } catch (\Exception $e) {
  797. Log::error('更新工作状态缓存失败', [
  798. 'coach_id' => $coachId,
  799. 'error' => $e->getMessage(),
  800. ]);
  801. // 缓存更新失败不影响主流程
  802. }
  803. }
  804. /**
  805. * 获取技师工作状态
  806. *
  807. * @param int $coachId 技师ID
  808. */
  809. public function getWorkStatus(int $coachId): array
  810. {
  811. try {
  812. // 验证技师信息
  813. $coach = CoachUser::find($coachId);
  814. abort_if(! $coach, 404, '技师不存在');
  815. // 直接获取技师信息里的work_status
  816. $workStatus = $coach->work_status;
  817. return [
  818. 'work_status' => $workStatus,
  819. 'work_status_text' => TechnicianWorkStatus::fromValue($workStatus)->label(),
  820. 'updated_at' => now()->toDateTimeString(),
  821. ];
  822. } catch (\Exception $e) {
  823. Log::error('获取技师工作状态失败', [
  824. 'coach_id' => $coachId,
  825. 'error' => $e->getMessage(),
  826. 'trace' => $e->getTraceAsString(),
  827. ]);
  828. throw $e;
  829. }
  830. }
  831. /**
  832. * 获取技师排班信息
  833. *
  834. * @param int $userId 用户ID
  835. */
  836. public function getSchedule(int $userId): array
  837. {
  838. try {
  839. // 获取技师信息
  840. $user = MemberUser::with(['coach'])->findOrFail($userId);
  841. $coach = $user->coach;
  842. abort_if(! $coach, 404, '技师信息不存在');
  843. // 先尝试缓存获取
  844. $cacheKey = "coach:schedule:{$coach->id}";
  845. $cached = Redis::get($cacheKey);
  846. if ($cached) {
  847. return json_decode($cached, true);
  848. }
  849. // 缓存不存在,从数据库获取
  850. $schedule = CoachSchedule::where('coach_id', $coach->id)
  851. ->where('state', 1)
  852. ->first();
  853. $result = [
  854. 'time_ranges' => $schedule ? json_decode($schedule->time_ranges, true) : [],
  855. 'updated_at' => $schedule ? $schedule->updated_at->toDateTimeString() : now()->toDateTimeString(),
  856. ];
  857. // 写入缓存
  858. Redis::setex($cacheKey, 86400, json_encode($result));
  859. // 记录日志
  860. Log::info('获取技师排班信息成功', [
  861. 'coach_id' => $coach->id,
  862. 'schedule' => $result,
  863. ]);
  864. return $result;
  865. } catch (\Exception $e) {
  866. Log::error('获取技师排班信息失败', [
  867. 'user_id' => $userId,
  868. 'error' => $e->getMessage(),
  869. 'trace' => $e->getTraceAsString(),
  870. ]);
  871. throw $e;
  872. }
  873. }
  874. /**
  875. * 验证技师基础信息
  876. *
  877. * @param User $user 用户对象
  878. * @param bool $throwError 是否抛出异常
  879. * @return bool
  880. */
  881. private function validateBasicCoach($user, bool $throwError = true): bool
  882. {
  883. if (!$user || !$user->coach) {
  884. if ($throwError) {
  885. abort_if(!$user, 404, '用户不存在');
  886. abort_if(!$user->coach, 404, '技师信息不存在');
  887. }
  888. return false;
  889. }
  890. return true;
  891. }
  892. /**
  893. * 检查是否存在审核记录
  894. *
  895. * @param CoachUser $coach 技师对象
  896. * @param string $type 记录类型(info|qual|real)
  897. * @return bool
  898. */
  899. private function hasPendingRecord($coach, string $type): bool
  900. {
  901. $method = match ($type) {
  902. 'info' => 'infoRecords',
  903. 'qual' => 'qualRecords',
  904. 'real' => 'realRecords',
  905. default => throw new \InvalidArgumentException('Invalid record type')
  906. };
  907. return $coach->{$method}()
  908. ->where('state', TechnicianAuthStatus::AUDITING->value)
  909. ->exists();
  910. }
  911. /**
  912. * 格式化位置信息
  913. * 过滤和验证位置相关字段
  914. *
  915. * @param array $locationInfo 原始位置信息
  916. * @return array 格式化后的位置信息
  917. * @throws \Exception 当行政区划代码格式无效时抛出异常
  918. */
  919. private function formatLocationInfo(array $locationInfo): array
  920. {
  921. // 定义允许的字段列表,确保数据安全性
  922. $allowedFields = [
  923. 'province', // 省份
  924. 'city', // 城市
  925. 'district', // 区县
  926. 'address', // 详细地址
  927. 'adcode' // 行政区划代码
  928. ];
  929. // 过滤并验证字段:
  930. // 1. 只保留允许的字段
  931. // 2. 移除空值
  932. $formatted = array_filter(
  933. array_intersect_key($locationInfo, array_flip($allowedFields)),
  934. function ($value) {
  935. return !is_null($value) && $value !== '';
  936. }
  937. );
  938. // 验证行政区划代码格式(6位数字)
  939. if (isset($formatted['adcode'])) {
  940. abort_if(!preg_match('/^\d{6}$/', $formatted['adcode']), 422, '无效的行政区划代码');
  941. }
  942. return $formatted;
  943. }
  944. /**
  945. * 更新位置缓存
  946. * 处理Redis地理位置数据结构的更新
  947. * 使用Redis的GEOADD命令存储地理位置信息
  948. *
  949. * @param int $coachId 技师ID
  950. * @param float $longitude 经度
  951. * @param float $latitude 纬度
  952. * @param int $type 位置类型
  953. * @return bool 操作是否成功
  954. */
  955. private function updateLocationCache(int $coachId, float $longitude, float $latitude, int $type): bool
  956. {
  957. // 生成缓存键:技师ID_位置类型
  958. $key = $coachId . '_' . $type;
  959. // 使用Redis的GEOADD命令添加地理位置信息
  960. // 参数顺序:key longitude latitude member
  961. return Redis::geoadd('coach_locations', $longitude, $latitude, $key);
  962. }
  963. /**
  964. * 获取技师最新基本信息
  965. *
  966. * @param CoachUser $coach 技师对象
  967. * @return CoachInfoRecord 最新的基本信息记录
  968. * @throws \Illuminate\Http\Exceptions\HttpResponseException 当信息不存在时抛出404异常
  969. */
  970. private function getLatestBaseInfo(CoachUser $coach): CoachInfoRecord
  971. {
  972. // 获取最新的技师信息记录(排除审核拒绝的记录)
  973. $latestInfo = $coach->infoRecords()
  974. ->where('state', '<>', TechnicianAuthStatus::REJECTED->value)
  975. ->latest()
  976. ->first();
  977. abort_if(!$latestInfo, 404, '技师基本信息不存在');
  978. return $latestInfo;
  979. }
  980. /**
  981. * 获取技师详细信息
  982. *
  983. * 业务逻辑:
  984. * 1. 获取技师最新基本信息(不包括审核拒绝的记录)
  985. * 2. 获取技师邀请码信息
  986. * 3. 获取钱包信息
  987. * 4. 组装返回数据
  988. *
  989. * @return array 技师详细信息
  990. * @throws \Exception 获取信息失败时抛出异常
  991. */
  992. public function getCoachDetail(): array
  993. {
  994. // 获取当前登录用户
  995. /** @var MemberUser $user */
  996. $user = Auth::user();
  997. // 获取用户的技师信息
  998. $coach = $user->coach;
  999. abort_if(!$coach, 404, '技师信息不存在');
  1000. // 获取最新的基本信息记录
  1001. $latestInfo = $this->getLatestBaseInfo($coach);
  1002. // 生成技师工号(例如:8位数字,不足前面补0)
  1003. $coachNo = str_pad($coach->id, 8, '0', STR_PAD_LEFT);
  1004. // 获取技师邀请码
  1005. $inviteCode = $this->generateInviteCode($coach->id);
  1006. // 获取钱包信息
  1007. $wallet = $this->getWalletInfo($coach->id);
  1008. // 获取基本信息
  1009. $baseInfo = $this->formatBaseInfo($latestInfo);
  1010. // 组装返回数据
  1011. return array_merge(
  1012. [
  1013. 'coach_no' => $coachNo,
  1014. 'invite_code' => $inviteCode,
  1015. 'wallet' => $wallet,
  1016. ],
  1017. $baseInfo
  1018. );
  1019. }
  1020. /**
  1021. * 生成技师邀请码
  1022. *
  1023. * @param int $coachId 技师ID
  1024. * @return string 邀请码
  1025. */
  1026. private function generateInviteCode(int $coachId): string
  1027. {
  1028. return sprintf('C%d', $coachId);
  1029. }
  1030. /**
  1031. * 获取技师钱包信息
  1032. *
  1033. * 业务逻辑:
  1034. * 1. 获取技师钱包关联数据
  1035. * 2. 如果钱包不存在,返回默认值
  1036. * 3. 返回钱包概况数据
  1037. *
  1038. * @param int $coachId 技师ID
  1039. * @return array 钱包概况信息
  1040. */
  1041. private function getWalletInfo(int $coachId): array
  1042. {
  1043. // 获取技师对象及其钱包关联
  1044. $coach = CoachUser::with('wallet')->find($coachId);
  1045. // 如果钱包不存在,返回默认值
  1046. if (!$coach || !$coach->wallet) {
  1047. return [
  1048. 'total_balance' => 0, // 总余额
  1049. 'available_balance' => 0, // 可用余额
  1050. 'frozen_amount' => 0, // 冻结金额
  1051. 'total_income' => 0, // 累计收入
  1052. 'total_expense' => 0, // 累计支出
  1053. ];
  1054. }
  1055. // 返回钱包概况数据
  1056. return [
  1057. 'total_balance' => $coach->wallet->total_balance ?? 0, // 总余额
  1058. 'available_balance' => $coach->wallet->available_balance ?? 0, // 可用余额
  1059. 'frozen_amount' => $coach->wallet->frozen_amount ?? 0, // 冻结金额
  1060. 'total_income' => $coach->wallet->total_income ?? 0, // 累计收入
  1061. 'total_expense' => $coach->wallet->total_expense ?? 0, // 累计支出
  1062. ];
  1063. }
  1064. }