AccountService.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  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. * 业务逻辑:
  967. * 1. 获取技师最新基本信息(不包括审核拒绝的记录)
  968. * 2. 获取技师邀请码信息
  969. * 3. 获取钱包信息
  970. * 4. 组装返回数据
  971. *
  972. * @return array 技师详细信息
  973. * @throws \Exception 获取信息失败时抛出异常
  974. */
  975. public function getCoachDetail(): array
  976. {
  977. // 获取当前登录用户
  978. /** @var MemberUser $user */
  979. $user = Auth::user();
  980. // 获取用户的技师信息
  981. $coach = $user->coach;
  982. abort_if(!$coach, 404, '技师信息不存在');
  983. // 获取最新的技师信息记录(排除审核拒绝的记录)
  984. $latestInfo = CoachInfoRecord::where('coach_id', $coach->id)
  985. ->where('state', '<>', TechnicianAuthStatus::REJECTED->value)
  986. ->latest()
  987. ->first();
  988. abort_if(!$latestInfo, 404, '技师基本信息不存在');
  989. // 生成技师工号(例如:8位数字,不足前面补0)
  990. $coachNo = str_pad($coach->id, 8, '0', STR_PAD_LEFT);
  991. // 获取技师邀请码
  992. $inviteCode = $this->generateInviteCode($coach->id);
  993. // 获取钱包信息
  994. $wallet = $this->getWalletInfo($coach->id);
  995. // 获取基本信息
  996. $baseInfo = $this->formatBaseInfo($latestInfo);
  997. // 组装返回数据
  998. return array_merge(
  999. [
  1000. 'coach_no' => $coachNo,
  1001. 'invite_code' => $inviteCode,
  1002. 'wallet' => $wallet,
  1003. ],
  1004. $baseInfo
  1005. );
  1006. }
  1007. /**
  1008. * 生成技师邀请码
  1009. *
  1010. * @param int $coachId 技师ID
  1011. * @return string 邀请码
  1012. */
  1013. private function generateInviteCode(int $coachId): string
  1014. {
  1015. return sprintf('C%d', $coachId);
  1016. }
  1017. /**
  1018. * 获取技师钱包信息
  1019. *
  1020. * 业务逻辑:
  1021. * 1. 获取技师钱包关联数据
  1022. * 2. 如果钱包不存在,返回默认值
  1023. * 3. 返回钱包概况数据
  1024. *
  1025. * @param int $coachId 技师ID
  1026. * @return array 钱包概况信息
  1027. */
  1028. private function getWalletInfo(int $coachId): array
  1029. {
  1030. // 获取技师对象及其钱包关联
  1031. $coach = CoachUser::with('wallet')->find($coachId);
  1032. // 如果钱包不存在,返回默认值
  1033. if (!$coach || !$coach->wallet) {
  1034. return [
  1035. 'total_balance' => 0, // 总余额
  1036. 'available_balance' => 0, // 可用余额
  1037. 'frozen_amount' => 0, // 冻结金额
  1038. 'total_income' => 0, // 累计收入
  1039. 'total_expense' => 0, // 累计支出
  1040. ];
  1041. }
  1042. // 返回钱包概况数据
  1043. return [
  1044. 'total_balance' => $coach->wallet->total_balance ?? 0, // 总余额
  1045. 'available_balance' => $coach->wallet->available_balance ?? 0, // 可用余额
  1046. 'frozen_amount' => $coach->wallet->frozen_amount ?? 0, // 冻结金额
  1047. 'total_income' => $coach->wallet->total_income ?? 0, // 累计收入
  1048. 'total_expense' => $coach->wallet->total_expense ?? 0, // 累计支出
  1049. ];
  1050. }
  1051. }