AccountService.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473
  1. <?php
  2. namespace App\Services\Coach;
  3. use App\Models\Order;
  4. use App\Models\ShopInfo;
  5. use App\Models\CoachUser;
  6. use App\Enums\OrderStatus;
  7. use App\Models\MemberUser;
  8. use App\Enums\ProjectStatus;
  9. use App\Models\CoachProject;
  10. use App\Models\CoachLocation;
  11. use App\Models\CoachSchedule;
  12. use App\Models\CoachStatistic;
  13. use App\Enums\TechnicianStatus;
  14. use App\Models\CoachInfoRecord;
  15. use App\Models\OrderGrabRecord;
  16. use Illuminate\Support\Facades\DB;
  17. use App\Enums\TechnicianAuthStatus;
  18. use App\Enums\TechnicianWorkStatus;
  19. use Illuminate\Support\Facades\Log;
  20. use Illuminate\Support\Facades\Auth;
  21. use App\Enums\TechnicianLocationType;
  22. use Illuminate\Support\Facades\Cache;
  23. use Illuminate\Support\Facades\Redis;
  24. use App\Traits\LocationValidationTrait;
  25. class AccountService
  26. {
  27. use LocationValidationTrait;
  28. private const CACHE_KEY_PREFIX = 'coach_info_';
  29. private const CACHE_TTL = 300; // 5分钟
  30. /**
  31. * 提交技师基本信息
  32. * 包括个人基础资料的提交和审核
  33. *
  34. * 业务流程:
  35. * 1. 验证技师信息存在性
  36. * 2. 检查是否有待审核的记录
  37. * 3. 处理生活照片数据
  38. * 4. 创建新的基本信息记录
  39. * 5. 清除相关缓存
  40. *
  41. * 注意事项:
  42. * - 同一时间只能有一条待审核记录
  43. * - 审核不通过可以重新提交
  44. * - 头像和生活照片不限制格式
  45. * - 除性别和手机号外,其他字段均为可选
  46. * - 手机号会进行脱敏处理
  47. *
  48. * @param User $user 当前认证用户
  49. * @param array $data 基本信息数据,包含:
  50. * - nickname: string|null 昵称(可选)
  51. * - avatar: string|null 头像图片(可选)
  52. * - life_photos: array|null 生活照片数组(可选)
  53. * - gender: string 性别(1:男 2:女)
  54. * - mobile: string 手机号
  55. * - birthday: string|null 出生日期(可选)
  56. * - work_years: int|null 工作年限(可选)
  57. * - intention_city: string|null 意向城市(可选)
  58. * - introduction: string|null 个人简介(可选)
  59. * @return array 返回结果,包含:
  60. * - message: string 提示信息
  61. * @throws \Exception 当验证失败或保存失败时抛出异常
  62. */
  63. public function submitBaseInfo($user, array $data)
  64. {
  65. return DB::transaction(function () use ($user, $data) {
  66. // 验证技师信息是否存在,不存在则抛出404异常
  67. abort_if(!$user->coach, 404, '技师信息不存在');
  68. // 检查是否有待审核的记录,避免重复提交
  69. // 如果存在待审核记录,则抛出422异常
  70. $pendingRecord = $this->hasPendingRecord($user->coach, 'info');
  71. abort_if($pendingRecord, 422, '已有待审核的基本信息记录');
  72. // 处理生活照片数据:将数组转换为JSON格式存储
  73. // 如果没有生活照片数据,则保持原样
  74. if (isset($data['life_photos'])) {
  75. // 使用array_values确保数组索引连续
  76. $data['life_photos'] = json_encode(array_values($data['life_photos']));
  77. }
  78. // 创建新的基本信息记录,设置为待审核状态
  79. // 合并用户提交的数据和审核状态
  80. $user->coach->infoRecords()->create(array_merge($data, [
  81. 'state' => TechnicianAuthStatus::AUDITING->value, // 设置为待审核状态
  82. ]));
  83. // 清除技师信息缓存,确保数据一致性
  84. // 避免用户获取到旧的缓存数据
  85. $this->clearCoachCache($user->coach->id);
  86. return ['message' => '基本信息提交成功'];
  87. });
  88. }
  89. /**
  90. * 提交技师资质信息
  91. * 包括资质证书照片、营业执照和健康证照片的提交和审核
  92. *
  93. * 业务流程:
  94. * 1. 验证技师信息存在性
  95. * 2. 检查是否有待审核的记录
  96. * 3. 创建新的资质审核记录
  97. * 4. 清除相关缓存
  98. *
  99. * 注意事项:
  100. * - 同一时间只能有一条待审核记录
  101. * - 审核不通过可以重新提交
  102. * - 所有图片数据不限制格式
  103. *
  104. * @param User $user 当前认证用户
  105. * @param array $data 资质信息数据,包含:
  106. * - qual_type: int 资质类型(1:初级 2:中级 3:高级)
  107. * - qual_photo: string 资质证书照片
  108. * - business_license: string 营业执照照片
  109. * - health_cert: string 健康证照片
  110. * @return array 返回结果,包含:
  111. * - message: string 提示信息
  112. * - data: array 详细数据
  113. * - record_id: int 记录ID
  114. * - state: int 状态值
  115. * - state_text: string 状态文本
  116. * @throws \Exception 当验证失败或保存失败时抛出异常
  117. */
  118. public function submitQualification($user, array $data)
  119. {
  120. // 开启数据库事务
  121. DB::beginTransaction();
  122. try {
  123. // 验证技师信息是否存在
  124. abort_if(!$user->coach, 404, '技师信息不存在');
  125. // 检查是否有待审核的记录,避免重复提交
  126. $pendingRecord = $this->hasPendingRecord($user->coach, 'qual');
  127. abort_if($pendingRecord, 422, '已有待审核的资质信息记录');
  128. // 创建新的资质审核记录,设置为待审核状态
  129. $record = $user->coach->qualRecords()->create(array_merge($data, [
  130. 'state' => TechnicianAuthStatus::AUDITING->value,
  131. ]));
  132. // 清除技师信息缓存,确保数据一致性
  133. $this->clearCoachCache($user->coach->id);
  134. // 提交事务
  135. DB::commit();
  136. // 返回成功结果
  137. return [
  138. 'message' => '资质信息提交成功',
  139. 'data' => [
  140. 'record_id' => $record->id,
  141. 'state' => TechnicianAuthStatus::AUDITING->value,
  142. 'state_text' => TechnicianAuthStatus::fromValue(TechnicianAuthStatus::AUDITING->value)->label(),
  143. ]
  144. ];
  145. } catch (\Exception $e) {
  146. // 发生异常时回滚事务
  147. DB::rollBack();
  148. throw $e;
  149. }
  150. }
  151. /**
  152. * 提交实名认证信息
  153. * 包括姓名(可选)、身份证号(可选)和三张身份证照片的提交和审核
  154. *
  155. * 业务流程:
  156. * 1. 验证技师信息存在性
  157. * 2. 检查是否有待审核的记录
  158. * 3. 创建新的实名认证记录
  159. * 4. 清除相关缓存
  160. *
  161. * 注意事项:
  162. * - 同一时间只能有一条待审核记录
  163. * - 审核不通过可以重新提交
  164. * - 所有图片数据不限制格式
  165. * - 姓名和身份证号为可选字段
  166. * - 敏感信息会进行脱敏处理
  167. *
  168. * @param User $user 当前认证用户
  169. * @param array $data 实名认证数据,包含:
  170. * - real_name: string|null 真实姓名(可选)
  171. * - id_card: string|null 身份证号(可选)
  172. * - id_card_front_photo: string 身份证正面照片
  173. * - id_card_back_photo: string 身份证反面照片
  174. * - id_card_hand_photo: string 手持身份证照片
  175. * @return array 返回结果
  176. * @throws \Exception 当验证失败或保存失败时抛出异常
  177. */
  178. public function submitRealName($user, array $data)
  179. {
  180. // 开启数据库事务
  181. DB::beginTransaction();
  182. try {
  183. // 验证技师信息是否存在
  184. abort_if(!$user->coach, 404, '技师信息不存在');
  185. // TODO: 临时清除技师信息,便于对接调试
  186. $this->clearCoachCache($user->coach->id);
  187. // 检查是否有待审核的记录,避免重复提交
  188. $pendingRecord = $this->hasPendingRecord($user->coach, 'real');
  189. abort_if($pendingRecord, 422, '已有待审核的实名认证信息');
  190. // 创建新的实名认证记录,设置为待审核状态
  191. $user->coach->realRecords()->create(array_merge($data, [
  192. 'state' => TechnicianAuthStatus::AUDITING->value,
  193. ]));
  194. // 清除技师信息缓存,确保数据一致性
  195. $this->clearCoachCache($user->coach->id);
  196. // 提交事务
  197. DB::commit();
  198. // 返回成功结果
  199. return ['message' => '实名认证信息提交成功'];
  200. } catch (\Exception $e) {
  201. // 发生异常时回滚事务
  202. DB::rollBack();
  203. throw $e;
  204. }
  205. }
  206. /**
  207. * 获取技师信息
  208. * 包括基本信息、资质信息和实名认证信息
  209. *
  210. * 业务流程:
  211. * 1. 验证用户和技师信息存在性
  212. * 2. 尝试从缓存获取数据
  213. * 3. 如果缓存不存在,从数据库获取并缓存
  214. *
  215. * 注意事项:
  216. * - 所有图片数据不限制格式
  217. * - 敏感信息会进行脱敏处理
  218. * - 使用缓存提高性能
  219. *
  220. * @param User $user 当前认证用户
  221. * @return array 返回技师所有信息,包含:
  222. * - base_info: array|null 基本信息
  223. * - qualification: array|null 资质信息
  224. * - real_name: array|null 实名认证信息
  225. * @throws \Exception 当验证失败时抛出异常
  226. */
  227. public function getCoachInfo($user)
  228. {
  229. // 验证用户和技师信息
  230. abort_if(!$user, 404, '用户不存在');
  231. abort_if(!$user->coach, 404, '技师信息不存在');
  232. // 尝试从缓存获取数据
  233. return Cache::remember(
  234. self::CACHE_KEY_PREFIX . $user->coach->id,
  235. self::CACHE_TTL,
  236. function () use ($user) {
  237. // 缓存不存在时,从数据库获取
  238. return $this->fetchCoachInfo($user->coach);
  239. }
  240. );
  241. }
  242. /**
  243. * 获取技师详细信息
  244. */
  245. public function getCoachDetail(): array
  246. {
  247. $coach = Auth::user()->coach->load([
  248. 'latestInfoRecord',
  249. 'latestRealRecord',
  250. 'latestQualRecord',
  251. 'commonLocation',
  252. 'shop',
  253. 'statistics',
  254. ]);
  255. // 获取基本信息
  256. $baseInfo = $this->formatBaseInfo($coach->latestInfoRecord);
  257. // 获取订单统计
  258. $orderStats = $this->getOrderStatistics($coach->id);
  259. // 获取评分统计
  260. $statistics = $this->formatStatistics($coach->statistics);
  261. // 合并所有统计数据
  262. $statistics = array_merge($orderStats, $statistics);
  263. // 生成技师工号
  264. $coachNo = str_pad($coach->id, 8, '0', STR_PAD_LEFT);
  265. // 获取技师邀请码
  266. $inviteCode = $this->generateInviteCode($coach->id);
  267. // 获取钱包信息
  268. $wallet = $this->getWalletInfo($coach->id);
  269. // 获取审核状态信息
  270. $authStatus = $this->formatAuthStatus($coach);
  271. // 获取位置信息
  272. $location = $this->formatLocation($coach->commonLocation);
  273. // 获取店铺信息
  274. $shop = $this->formatShop($coach->shop);
  275. // 组装返回数据
  276. return array_merge(
  277. [
  278. 'coach_no' => $coachNo,
  279. 'invite_code' => $inviteCode,
  280. 'wallet' => $wallet,
  281. ],
  282. $baseInfo,
  283. [
  284. 'state' => $coach->state,
  285. 'state_text' => $coach->state
  286. ? TechnicianStatus::fromValue($coach->state)->label()
  287. : null,
  288. 'work_status' => $coach->work_status,
  289. 'work_status_text' => $coach->work_status
  290. ? TechnicianWorkStatus::fromValue($coach->work_status)->label()
  291. : null,
  292. ],
  293. [
  294. 'auth_status' => $authStatus,
  295. 'location' => $location,
  296. 'shop' => $shop,
  297. 'statistics' => $statistics,
  298. ]
  299. );
  300. }
  301. /**
  302. * 格式化审核状态信息
  303. * 包含基本信息、实名认证和资质认证的审核状态
  304. *
  305. * @param CoachUser $coach 技师对象
  306. * @return array 审核状态信息
  307. */
  308. private function formatAuthStatus(CoachUser $coach): array
  309. {
  310. return [
  311. 'base_info' => [
  312. 'state' => $coach->latestInfoRecord?->state,
  313. 'state_text' => $coach->latestInfoRecord?->state
  314. ? TechnicianAuthStatus::fromValue($coach->latestInfoRecord->state)->label()
  315. : null,
  316. 'audit_remark' => $coach->latestInfoRecord?->audit_remark,
  317. 'updated_at' => $coach->latestInfoRecord?->updated_at?->format('Y-m-d H:i:s'),
  318. ],
  319. 'real_name' => [
  320. 'state' => $coach->latestRealRecord?->state,
  321. 'state_text' => $coach->latestRealRecord?->state
  322. ? TechnicianAuthStatus::fromValue($coach->latestRealRecord->state)->label()
  323. : null,
  324. 'audit_remark' => $coach->latestRealRecord?->audit_remark,
  325. 'updated_at' => $coach->latestRealRecord?->updated_at?->format('Y-m-d H:i:s'),
  326. ],
  327. 'qualification' => [
  328. 'state' => $coach->latestQualRecord?->state,
  329. 'state_text' => $coach->latestQualRecord?->state
  330. ? TechnicianAuthStatus::fromValue($coach->latestQualRecord->state)->label()
  331. : null,
  332. 'audit_remark' => $coach->latestQualRecord?->audit_remark,
  333. 'updated_at' => $coach->latestQualRecord?->updated_at?->format('Y-m-d H:i:s'),
  334. ],
  335. ];
  336. }
  337. /**
  338. * 格式化位置信息
  339. * 处理技师的常用位置信息
  340. *
  341. * 业务逻辑:
  342. * 1. 检查位置信息是否存在
  343. * 2. 格式化地理位置信息
  344. * 3. 格式化行政区划信息
  345. *
  346. * @param CoachLocation|null $location 位置对象
  347. * @return array|null 格式化后的位置信息
  348. */
  349. private function formatLocation(?CoachLocation $location): ?array
  350. {
  351. // 如果没有位置信息,返回null
  352. if (!$location) {
  353. return null;
  354. }
  355. // 返回格式化的位置信息
  356. return [
  357. 'province' => $location->province, // 省份
  358. 'city' => $location->city, // 城市
  359. 'district' => $location->district, // 区县
  360. 'address' => $location->address, // 详细地址
  361. 'adcode' => $location->adcode, // 行政区划代码
  362. 'longitude' => $location->longitude, // 经度
  363. 'latitude' => $location->latitude, // 纬度
  364. ];
  365. }
  366. /**
  367. * 格式化店铺信息
  368. * 处理技师所属店铺的基本信息
  369. *
  370. * 业务逻辑:
  371. * 1. 检查店铺信息是否存在
  372. * 2. 格式化店铺基本信息
  373. * 3. 格式化联系信息
  374. *
  375. * @param ShopInfo|null $shop 店铺对象
  376. * @return array|null 格式化后的店铺信息
  377. */
  378. private function formatShop(?ShopInfo $shop): ?array
  379. {
  380. // 如果没有店铺信息,返回null
  381. if (!$shop) {
  382. return null;
  383. }
  384. // 返回格式化的店铺信息
  385. return [
  386. 'id' => $shop->id, // 店铺ID
  387. 'name' => $shop->name, // 店铺名称
  388. 'address' => $shop->address, // 店铺地址
  389. 'phone' => $shop->phone, // 联系电话
  390. ];
  391. }
  392. /**
  393. * 格式化评分统计信息
  394. * 处理技师的评分和等级信息
  395. *
  396. * @param CoachStatistic|null $statistics 评分统计对象
  397. * @return array 格式化后的评分信息
  398. */
  399. private function formatStatistics(?CoachStatistic $statistics): array
  400. {
  401. if (!$statistics) {
  402. return [
  403. 'level' => 1, // 技师等级
  404. 'level_text' => $this->getLevelText(1), // 等级文本
  405. 'rating' => 5.0, // 评分
  406. ];
  407. }
  408. return [
  409. 'level' => $statistics->level ?? 1,
  410. 'level_text' => $this->getLevelText($statistics->level ?? 1),
  411. 'rating' => $statistics->rating ?? 5.0,
  412. ];
  413. }
  414. /**
  415. * 获取技师详细信息
  416. * 从数据库获取最新的认证记录信息
  417. *
  418. * @param CoachUser $coach 技师对象
  419. * @return array 格式化后的技师信息
  420. */
  421. private function fetchCoachInfo($coach)
  422. {
  423. // 获取最新的各类认证记录
  424. $baseInfo = $coach->infoRecords()->latest()->first();
  425. $qualification = $coach->qualRecords()->latest()->first();
  426. $realName = $coach->realRecords()->latest()->first();
  427. // 格式化并返回数据
  428. return [
  429. 'base_info' => $baseInfo ? $this->formatBaseInfo($baseInfo) : null,
  430. 'qualification' => $qualification ? $this->formatQualification($qualification) : null,
  431. 'real_name' => $realName ? $this->formatRealName($realName) : null,
  432. ];
  433. }
  434. /**
  435. * 格式化基本信息
  436. * 处理技师基本信息的展示格式
  437. *
  438. * @param object $info 基本信息记录对象
  439. * @return array 格式化后的基本信息
  440. */
  441. private function formatBaseInfo($info): array
  442. {
  443. // 如果 $info 为空,返回空数组
  444. if (!$info) {
  445. return [];
  446. }
  447. // 返回格式化后的基本信息,包含状态文本
  448. return [
  449. 'nickname' => $info->nickname,
  450. 'avatar' => $info->avatar, // 支持任意格式的图片数据
  451. 'life_photos' => $info->life_photos ?? [], // 生活照片数组
  452. 'gender' => $info->gender,
  453. 'mobile' => $this->maskMobile($info->mobile), // 手机号脱敏处理
  454. 'birthday' => $info->birthday,
  455. 'work_years' => $info->work_years,
  456. 'intention_city' => $info->intention_city,
  457. 'introduction' => $info->introduction,
  458. 'state' => $info->state,
  459. 'state_text' => $info->state ? TechnicianAuthStatus::fromValue($info->state)->label() : null,
  460. 'audit_remark' => $info->audit_remark,
  461. ];
  462. }
  463. /**
  464. * 格式化资质信息
  465. * 处理技师资质信息的展示格式
  466. *
  467. * @param object|null $qual 资质记录对象
  468. * @return array|null 格式化后的资质信息
  469. */
  470. private function formatQualification($qual): ?array
  471. {
  472. // 如果资质信息为空,返回 null
  473. if (!$qual) {
  474. return null;
  475. }
  476. // 资质类型文本映射
  477. $qualTypeMap = [
  478. 1 => '初级按摩师',
  479. 2 => '中级按摩师',
  480. 3 => '高级按摩师',
  481. ];
  482. // 返回格式化后的资质信息,包含状态文本
  483. return [
  484. 'qual_type' => $qual->qual_type,
  485. 'qual_type_text' => $qualTypeMap[$qual->qual_type] ?? '未知类型',
  486. 'qual_photo' => $qual->qual_photo,
  487. 'business_license' => $qual->business_license,
  488. 'health_cert' => $qual->health_cert,
  489. 'state' => $qual->state,
  490. 'state_text' => $qual->state ? TechnicianAuthStatus::fromValue($qual->state)->label() : null,
  491. 'audit_remark' => $qual->audit_remark,
  492. ];
  493. }
  494. /**
  495. * 格式化实名信息
  496. * 处理技师实名认证信息的展示格式
  497. *
  498. * @param object|null $real 实名认证记录对象
  499. * @return array|null 格式化后的实名信息
  500. */
  501. private function formatRealName($real): ?array
  502. {
  503. // 如果实名信息为空,返回 null
  504. if (!$real) {
  505. return null;
  506. }
  507. // 返回格式化后的实名信息,包含状态文本和脱敏处理
  508. return [
  509. 'real_name' => $real->real_name,
  510. 'id_card' => $this->maskIdCard($real->id_card),
  511. 'id_card_front_photo' => $real->id_card_front_photo,
  512. 'id_card_back_photo' => $real->id_card_back_photo,
  513. 'id_card_hand_photo' => $real->id_card_hand_photo,
  514. 'state' => $real->state,
  515. 'state_text' => $real->state ? TechnicianAuthStatus::fromValue($real->state)->label() : null,
  516. 'audit_remark' => $real->audit_remark,
  517. ];
  518. }
  519. /**
  520. * 手机号脱敏
  521. * 将手机号中间4位替换为****
  522. *
  523. * @param string $mobile 原始手机号
  524. * @return string 脱敏后的手机号
  525. */
  526. private function maskMobile($mobile)
  527. {
  528. return substr_replace($mobile, '****', 3, 4);
  529. }
  530. /**
  531. * 身份证号脱敏
  532. * 将身份证号中间8位替换为****
  533. *
  534. * @param string|null $idCard 原始身份证号
  535. * @return string|null 脱敏后的身份证号
  536. */
  537. private function maskIdCard($idCard)
  538. {
  539. if (!$idCard) {
  540. return null;
  541. }
  542. return substr_replace($idCard, '****', 6, 8);
  543. }
  544. /**
  545. * 清除技师信息缓存
  546. */
  547. private function clearCoachCache($coachId)
  548. {
  549. Cache::forget(self::CACHE_KEY_PREFIX . $coachId);
  550. }
  551. /**
  552. * 设置定位信息
  553. * 支持设置当前位置和常用位置,包含地理位置和行政区划信息
  554. *
  555. * 业务流程:
  556. * 1. 验证经纬度参数
  557. * 2. 验证位置类型
  558. * 3. 保存到Redis的地理位置数据结构
  559. * 4. 同步保存到据库
  560. *
  561. * @param int $coachId 技师ID
  562. * @param float $latitude 纬度
  563. * @param float $longitude 经度
  564. * @param int $type 位置类型 (current:1|common:2)
  565. * @param array $locationInfo 位置信息,包含:
  566. * - province: string|null 省份
  567. * - city: string|null 城市
  568. * - district: string|null 区县
  569. * - address: string|null 详细地址
  570. * - adcode: string|null 行政区划代码
  571. * @return bool 返回缓存更新结果
  572. * @throws \Exception 当验证失败或保存失败时抛出异常
  573. */
  574. public function setLocation($coachId, $latitude, $longitude, $type = TechnicianLocationType::COMMON->value, array $locationInfo = [])
  575. {
  576. // 使用事务确保一致性
  577. return DB::transaction(function () use ($coachId, $latitude, $longitude, $type, $locationInfo) {
  578. // 验证经纬度的有效性(-90≤纬度≤90,-180≤经度≤180)
  579. $this->validateCoordinates($latitude, $longitude);
  580. // 验证位置类型是否为有效值(1:当前位置 2:常用位置)
  581. $this->validateLocationType($type);
  582. // 格式化并验证位置信息(省市区、地址、行政区划代码)
  583. $formattedLocation = $this->formatLocationInfo($locationInfo);
  584. // 更新Redis地理位置缓存,用于实时位置查询
  585. $result = $this->updateLocationCache($coachId, $longitude, $latitude, $type);
  586. // 同步更新数据库,保存历史位置记录
  587. CoachLocation::updateOrCreate(
  588. // 查询条件:根据技师ID和位置类型确定唯一记录
  589. ['coach_id' => $coachId, 'type' => $type],
  590. // 更新数据:合并基础位置信息和格式化后的地址信息
  591. array_merge([
  592. 'latitude' => $latitude,
  593. 'longitude' => $longitude,
  594. ], $formattedLocation)
  595. );
  596. return $result;
  597. });
  598. }
  599. /**
  600. * 获取技师位置信息
  601. *
  602. * 业务流程:
  603. * 1. 获取指定类型的位置记录
  604. * 2. 返回格式化的位置数据
  605. *
  606. * @param User $user 认证用户
  607. * @param int $type 位置类型 (1:当前位置 2:常用位置)
  608. * @return array 位置信息,包含:
  609. * - province: string 省份
  610. * - city: string 城市
  611. * - district: string 区县
  612. * - address: string 详细地址
  613. * - adcode: string 行政区划代码
  614. * - longitude: float 经度
  615. * - latitude: float 纬度
  616. * - updated_at: string 更新时间
  617. */
  618. public function getLocation($user, int $type): array
  619. {
  620. // 获取指定类型的位置记录
  621. $location = $this->getLocationByType($user->coach, $type);
  622. // 返回格式化的位置数据
  623. return $this->formatLocationResponse($location);
  624. }
  625. /**
  626. * 根据类型获取技师位置记录
  627. *
  628. * @param CoachUser $coach 技师对象
  629. * @param int $type 位置类型 (1:当前位置 2:常用位置)
  630. * @return CoachLocation 位置信息
  631. * @throws \Illuminate\Http\Exceptions\HttpResponseException 当位置信息不存在时抛出404异常
  632. */
  633. private function getLocationByType(CoachUser $coach, int $type): CoachLocation
  634. {
  635. // 获取指定类型的位置记录
  636. $location = $coach->locations()
  637. ->where('type', $type)
  638. ->first();
  639. abort_if(!$location, 404, '位置信息不存在');
  640. // 返回位置数据
  641. return $location;
  642. }
  643. /**
  644. * 格式化位置响应数据
  645. *
  646. * @param CoachLocation $location 位置记录
  647. * @return array 格式化后的位置信息,包含:
  648. * - province: string 省份
  649. * - city: string 城市
  650. * - district: string 区县
  651. * - address: string 详细地址
  652. * - adcode: string 行政区划代码
  653. * - longitude: float 经度
  654. * - latitude: float 纬度
  655. * - updated_at: string 更新时间
  656. */
  657. private function formatLocationResponse(CoachLocation $location): array
  658. {
  659. return [
  660. 'province' => $location->province, // 省份
  661. 'city' => $location->city, // 城市
  662. 'district' => $location->district, // 区县
  663. 'address' => $location->address, // 详细地址
  664. 'adcode' => $location->adcode, // 行政区划代码
  665. 'longitude' => $location->longitude, // 经度
  666. 'latitude' => $location->latitude, // 纬度
  667. 'updated_at' => $location->updated_at->toDateTimeString(), // 更新时间
  668. ];
  669. }
  670. /**
  671. * 设置技师排班时间(每天通用)
  672. *
  673. * @param CoachUser $coach 技师对象
  674. * @param array $timeRanges 时间段数组
  675. * @return array 返回设置结果
  676. * @throws \Exception 当设置失败时抛出异常
  677. */
  678. public function setSchedule(CoachUser $coach, array $timeRanges): array
  679. {
  680. return DB::transaction(function () use ($coach, $timeRanges) {
  681. // 验证并排序时间段
  682. $sortedRanges = $this->validateAndSortTimeRanges($timeRanges);
  683. // 创建或更新排班记录
  684. $schedule = CoachSchedule::updateOrCreate(
  685. ['coach_id' => $coach->id],
  686. [
  687. 'time_ranges' => $sortedRanges, // 直接传入数组,模型会自动处理JSON转换
  688. 'state' => 1,
  689. ]
  690. );
  691. // 更新Redis缓存
  692. $this->updateScheduleCache($coach->id, $sortedRanges);
  693. // 返回设置结果
  694. return [
  695. 'status' => true,
  696. 'message' => '排班设置成功',
  697. 'data' => [
  698. 'coach_id' => $coach->id,
  699. 'time_ranges' => $sortedRanges,
  700. 'updated_at' => $schedule->updated_at->toDateTimeString(),
  701. ],
  702. ];
  703. });
  704. }
  705. /**
  706. * 验证并排序时间段
  707. */
  708. private function validateAndSortTimeRanges(array $timeRanges): array
  709. {
  710. // 验证时间段数组
  711. abort_if(empty($timeRanges), 400, '必须至少设置一个时间段');
  712. // 验证每个时间段格式并转换为分钟数进行比较
  713. $ranges = collect($timeRanges)->map(function ($range) {
  714. abort_if(
  715. !isset($range['start_time'], $range['end_time']),
  716. 400,
  717. '时间段格式错误'
  718. );
  719. // 验证时间格式,限制在 00:00-24:00
  720. foreach (['start_time', 'end_time'] as $field) {
  721. // 先检查是否为 24:00
  722. if ($range[$field] === '24:00') {
  723. continue;
  724. }
  725. // 其他时间格式验证 (00:00-23:59)
  726. abort_if(
  727. !preg_match('/^((?:[01][0-9]|2[0-3]):[0-5][0-9]|24:00)$/', $range[$field]),
  728. 400,
  729. '时间格式错误,应为00:00-24:00格式'
  730. );
  731. }
  732. // 转换为分钟数便于比较
  733. $startMinutes = $this->timeToMinutes($range['start_time']);
  734. $endMinutes = $this->timeToMinutes($range['end_time']);
  735. // 验证时间先后
  736. abort_if(
  737. $startMinutes >= $endMinutes,
  738. 400,
  739. "时间段 {$range['start_time']}-{$range['end_time']} 结束时间必须大于开始时间"
  740. );
  741. return [
  742. 'start_time' => $range['start_time'],
  743. 'end_time' => $range['end_time'],
  744. 'start_minutes' => $startMinutes,
  745. 'end_minutes' => $endMinutes,
  746. ];
  747. })
  748. ->sortBy('start_minutes')
  749. ->values();
  750. // 验证时间段是否重叠
  751. $ranges->each(function ($range, $index) use ($ranges) {
  752. if ($index > 0) {
  753. $prevRange = $ranges[$index - 1];
  754. abort_if(
  755. $range['start_minutes'] <= $prevRange['end_minutes'],
  756. 400,
  757. "时间段 {$prevRange['start_time']}-{$prevRange['end_time']} 和 " .
  758. "{$range['start_time']}-{$range['end_time']} 之间有重叠"
  759. );
  760. }
  761. });
  762. // 返回排序后的时间,只保留需要的字段
  763. return $ranges->map(function ($range) {
  764. return [
  765. 'start_time' => $range['start_time'],
  766. 'end_time' => $range['end_time'],
  767. ];
  768. })->toArray();
  769. }
  770. /**
  771. * 将时间转换为分钟数
  772. */
  773. private function timeToMinutes(string $time): int
  774. {
  775. if ($time === '24:00') {
  776. return 24 * 60; // 特殊处理 24:00
  777. }
  778. [$hours, $minutes] = explode(':', $time);
  779. return (int)$hours * 60 + (int)$minutes;
  780. }
  781. /**
  782. * 更新Redis缓存
  783. */
  784. private function updateScheduleCache(int $coachId, array $timeRanges): void
  785. {
  786. $cacheKey = "coach:schedule:{$coachId}";
  787. $cacheData = [
  788. 'time_ranges' => $timeRanges,
  789. 'updated_at' => now()->toDateTimeString(),
  790. ];
  791. // 使用 Redis 存储,24小时过期
  792. Redis::setex($cacheKey, 86400, json_encode($cacheData));
  793. // 清除相关的可预约时间段缓存
  794. $this->clearTimeSlotCache($coachId);
  795. }
  796. /**
  797. * 清除可预约时间段缓存
  798. */
  799. public function clearTimeSlotCache(int $coachId): void
  800. {
  801. $pattern = "coach:timeslots:{$coachId}:*";
  802. $keys = Redis::keys($pattern);
  803. if (! empty($keys)) {
  804. Redis::del($keys);
  805. }
  806. }
  807. /**
  808. * 更改技师工作状态
  809. *
  810. * 业务流程:
  811. * 1. 验证技师认证状态
  812. * 2. 处理状态切换逻辑
  813. * 3. 更新状态并同步缓存
  814. *
  815. * @param CoachUser $coach 技师对象
  816. * @param int $status 目标状态(1:休息中 2:工作中)
  817. * @return array 返回更新结果,包含:
  818. * - status: bool 更新是否成功
  819. * - message: string 提示信息
  820. * - data: array 状态信息
  821. * - work_status: int 工作状态值
  822. * - work_status_text: string 状态文本
  823. * @throws \Exception 当状态更新失败时抛出异常
  824. */
  825. public function updateWorkStatus(CoachUser $coach, int $status): array
  826. {
  827. DB::beginTransaction();
  828. try {
  829. // 验证技师认证状态
  830. $this->validateCoachStatus($coach);
  831. // 确保状态值为整数
  832. $status = (int)$status;
  833. // 更新状态
  834. $coach->work_status = $status;
  835. $coach->save();
  836. // 更新Redis缓存
  837. $this->updateWorkStatusCache($coach->id, $status);
  838. DB::commit();
  839. // 返回更新结果
  840. return [
  841. 'status' => true,
  842. 'message' => '状态更新成功',
  843. 'data' => [
  844. 'work_status' => $status,
  845. 'work_status_text' => TechnicianWorkStatus::fromValue($status)->label()
  846. ],
  847. ];
  848. } catch (\Exception $e) {
  849. DB::rollBack();
  850. throw $e;
  851. }
  852. }
  853. /**
  854. * 验证技师认证状态
  855. */
  856. private function validateCoachStatus($coach): void
  857. {
  858. // 验证基本信息认证
  859. $baseInfo = $coach->info;
  860. abort_if(
  861. ! $baseInfo || (int)$baseInfo->state !== TechnicianAuthStatus::PASSED->value,
  862. 422,
  863. '基本信息未认证通过'
  864. );
  865. // 验证资质认证
  866. $qualification = $coach->qual;
  867. abort_if(
  868. ! $qualification || (int)$qualification->state !== TechnicianAuthStatus::PASSED->value,
  869. 422,
  870. '资质信息未认证通过'
  871. );
  872. // 验证实名认证
  873. $realName = $coach->real;
  874. abort_if(
  875. ! $realName || (int)$realName->state !== TechnicianAuthStatus::PASSED->value,
  876. 422,
  877. '实名信息未认证通过'
  878. );
  879. }
  880. /**
  881. * 更新工作状态缓存
  882. */
  883. private function updateWorkStatusCache(int $coachId, int $status): void
  884. {
  885. try {
  886. $cacheKey = "coach:work_status:{$coachId}";
  887. $cacheData = [
  888. 'status' => $status,
  889. 'updated_at' => now()->toDateTimeString(),
  890. ];
  891. Redis::setex($cacheKey, 86400, json_encode($cacheData));
  892. } catch (\Exception $e) {
  893. Log::error('更新工作状态缓存失败', [
  894. 'coach_id' => $coachId,
  895. 'error' => $e->getMessage(),
  896. ]);
  897. // 缓存更新失败不影响主流程
  898. }
  899. }
  900. /**
  901. * 获取技师工作状态
  902. *
  903. * @param int $coachId 技师ID
  904. */
  905. public function getWorkStatus(int $coachId): array
  906. {
  907. try {
  908. // 验证技师信息
  909. $coach = CoachUser::find($coachId);
  910. abort_if(! $coach, 404, '技师不存在');
  911. // 直接获取技师信息里的work_status
  912. $workStatus = $coach->work_status;
  913. return [
  914. 'work_status' => $workStatus,
  915. 'work_status_text' => TechnicianWorkStatus::fromValue($workStatus)->label(),
  916. 'updated_at' => now()->toDateTimeString(),
  917. ];
  918. } catch (\Exception $e) {
  919. Log::error('获取技师工作状态失败', [
  920. 'coach_id' => $coachId,
  921. 'error' => $e->getMessage(),
  922. 'trace' => $e->getTraceAsString(),
  923. ]);
  924. throw $e;
  925. }
  926. }
  927. /**
  928. * 获取技师排班信息
  929. *
  930. * @param CoachUser $coach 技师对象
  931. * @return array 返回排班信息
  932. */
  933. public function getSchedule(CoachUser $coach): array
  934. {
  935. $cacheKey = "coach:schedule:{$coach->id}";
  936. // 尝试从 Redis 获取缓存
  937. $cached = Redis::get($cacheKey);
  938. if ($cached) {
  939. return json_decode($cached, true);
  940. }
  941. // 缓存不存在,从数据库获取
  942. $schedule = CoachSchedule::where('coach_id', $coach->id)
  943. ->where('state', 1)
  944. ->first();
  945. $data = [
  946. 'time_ranges' => $schedule ? $schedule->time_ranges : [],
  947. 'updated_at' => $schedule ? $schedule->updated_at->toDateTimeString() : now()->toDateTimeString(),
  948. ];
  949. // 写入 Redis 缓存
  950. Redis::setex($cacheKey, 86400, json_encode($data));
  951. return $data;
  952. }
  953. /**
  954. * 验证技师基础信息
  955. *
  956. * @param User $user 用户对象
  957. * @param bool $throwError 是否抛出异常
  958. * @return bool
  959. */
  960. private function validateBasicCoach($user, bool $throwError = true): bool
  961. {
  962. if (!$user || !$user->coach) {
  963. if ($throwError) {
  964. abort_if(!$user, 404, '用户不存在');
  965. abort_if(!$user->coach, 404, '技师信息不存在');
  966. }
  967. return false;
  968. }
  969. return true;
  970. }
  971. /**
  972. * 检查是否存在审核记录
  973. *
  974. * @param CoachUser $coach 技师对象
  975. * @param string $type 记录类型(info|qual|real)
  976. * @return bool
  977. */
  978. private function hasPendingRecord($coach, string $type): bool
  979. {
  980. $method = match ($type) {
  981. 'info' => 'infoRecords',
  982. 'qual' => 'qualRecords',
  983. 'real' => 'realRecords',
  984. default => throw new \InvalidArgumentException('Invalid record type')
  985. };
  986. return $coach->{$method}()
  987. ->where('state', TechnicianAuthStatus::AUDITING->value)
  988. ->exists();
  989. }
  990. /**
  991. * 格式化位置信息
  992. * 过滤和验证位置相关字段
  993. *
  994. * @param array $locationInfo 原始位置信息
  995. * @return array 格式化后的位置信息
  996. * @throws \Exception 当行政区划代码格式无效时抛出异常
  997. */
  998. private function formatLocationInfo(array $locationInfo): array
  999. {
  1000. // 定义允许的字段列表,确保数据安全性
  1001. $allowedFields = [
  1002. 'province', // 省份
  1003. 'city', // 城市
  1004. 'district', // 区县
  1005. 'address', // 详细地址
  1006. 'adcode' // 行政区划代码
  1007. ];
  1008. // 过滤并验证字段:
  1009. // 1. 只保留允许的字段
  1010. // 2. 移除空值
  1011. $formatted = array_filter(
  1012. array_intersect_key($locationInfo, array_flip($allowedFields)),
  1013. function ($value) {
  1014. return !is_null($value) && $value !== '';
  1015. }
  1016. );
  1017. // 验证行政区划代码格式(6位数字)
  1018. if (isset($formatted['adcode'])) {
  1019. abort_if(!preg_match('/^\d{6}$/', $formatted['adcode']), 422, '无效的行政区划代码');
  1020. }
  1021. return $formatted;
  1022. }
  1023. /**
  1024. * 更新位置缓存
  1025. * 处理Redis地理位置数据结构的更新
  1026. * 使用Redis的GEOADD命令存储地理位置信息
  1027. *
  1028. * @param int $coachId 技师ID
  1029. * @param float $longitude 经度
  1030. * @param float $latitude 纬度
  1031. * @param int $type 位置类型
  1032. * @return bool 操作是否成功
  1033. */
  1034. private function updateLocationCache(int $coachId, float $longitude, float $latitude, int $type): bool
  1035. {
  1036. // 生成缓存键:技师ID_位置类型
  1037. $key = $coachId . '_' . $type;
  1038. // 使用Redis的GEOADD命令添加地理位置信息
  1039. // 参数顺序:key longitude latitude member
  1040. return Redis::geoadd('coach_locations', $longitude, $latitude, $key);
  1041. }
  1042. /**
  1043. * 获取技师最新基本信息
  1044. *
  1045. * @param CoachUser $coach 技师对象
  1046. * @return CoachInfoRecord 最新的基本信息记录
  1047. * @throws \Illuminate\Http\Exceptions\HttpResponseException 当信息不存在时抛出404异常
  1048. */
  1049. private function getLatestBaseInfo(CoachUser $coach): CoachInfoRecord
  1050. {
  1051. // 获取最新的技师信息记录(排除审核拒绝的记录)
  1052. $latestInfo = $coach->infoRecords()
  1053. ->where('state', '<>', TechnicianAuthStatus::REJECTED->value)
  1054. ->latest()
  1055. ->first();
  1056. abort_if(!$latestInfo, 404, '技师基本信息不存在');
  1057. return $latestInfo;
  1058. }
  1059. /**
  1060. * 生成技师邀请码
  1061. *
  1062. * @param int $coachId 技师ID
  1063. * @return string 邀请码
  1064. */
  1065. private function generateInviteCode(int $coachId): string
  1066. {
  1067. return sprintf('C%d', $coachId);
  1068. }
  1069. /**
  1070. * 获取技师钱包信息
  1071. *
  1072. * 业务逻辑:
  1073. * 1. 获取技师钱包关联数据
  1074. * 2. 如果钱包不存在,返回默认值
  1075. * 3. 返回钱包概况数据
  1076. *
  1077. * @param int $coachId 技师ID
  1078. * @return array 钱包概况信息
  1079. */
  1080. private function getWalletInfo(int $coachId): array
  1081. {
  1082. // 获取技师及其钱包关联
  1083. $coach = CoachUser::with('wallet')->find($coachId);
  1084. // 如果钱包不存在,返回默认值
  1085. if (!$coach || !$coach->wallet) {
  1086. return [
  1087. 'total_balance' => 0, // 总余额
  1088. 'available_balance' => 0, // 可用余额
  1089. 'frozen_amount' => 0, // 冻结金额
  1090. 'total_income' => 0, // 累计收入
  1091. 'total_expense' => 0, // 累计支出
  1092. ];
  1093. }
  1094. // 返回钱包概况数据
  1095. return [
  1096. 'total_balance' => $coach->wallet->total_balance ?? 0, // 总余额
  1097. 'available_balance' => $coach->wallet->available_balance ?? 0, // 可用余额
  1098. 'frozen_amount' => $coach->wallet->frozen_amount ?? 0, // 冻结金额
  1099. 'total_income' => $coach->wallet->total_income ?? 0, // 累计收入
  1100. 'total_expense' => $coach->wallet->total_expense ?? 0, // 累计支出
  1101. ];
  1102. }
  1103. /**
  1104. * 更新技师基础信息
  1105. *
  1106. * 业务流程:
  1107. * 1. 获取最新的非拒绝记录
  1108. * 2. 验证手机验证码(如果修改手机号)
  1109. * 3. 如果是待审核状态,直接更新字段
  1110. * 4. 如果是已通过状态,创建新记录并复制字段
  1111. *
  1112. * @param CoachUser $coach 技师对象
  1113. * @param array $data 待更新的数据,可包含:
  1114. * - nickname: ?string 昵称
  1115. * - gender: ?int 性别(1:男 2:女)
  1116. * - mobile: ?string 手机号
  1117. * - code: ?string 验证码(修改手机号时必填)
  1118. * @return array 返回结果
  1119. */
  1120. public function updateBasicInfo(CoachUser $coach, array $data): array
  1121. {
  1122. return DB::transaction(function () use ($coach, $data) {
  1123. // 获取最新的非拒绝记录
  1124. $latestRecord = $coach->infoRecords()
  1125. ->where('state', '<>', TechnicianAuthStatus::REJECTED->value)
  1126. ->latest()
  1127. ->first();
  1128. abort_if(!$latestRecord, 404, '未找到有效的基础信息记录');
  1129. // 如果要修改手机号,验证验证码
  1130. if (isset($data['mobile'])) {
  1131. $this->verifyMobileCode($data['mobile'], $data['code']);
  1132. }
  1133. // 提取要更新的字段
  1134. $updateFields = array_intersect_key($data, [
  1135. 'nickname' => '',
  1136. 'gender' => '',
  1137. 'mobile' => '',
  1138. ]);
  1139. // 如果没有要更新的字段,直接返回
  1140. abort_if(empty($updateFields), 422, '没有需要更新的字段');
  1141. // 如果最新记录是待审核状态,直接更新
  1142. if ($latestRecord->state === TechnicianAuthStatus::AUDITING->value) {
  1143. $latestRecord->update($updateFields);
  1144. return [
  1145. 'message' => '基础信息修改申请已更新',
  1146. 'record_id' => $latestRecord->id,
  1147. 'updated_fields' => array_keys($updateFields)
  1148. ];
  1149. }
  1150. // 创建新的审核记录,复制其他字段
  1151. $newRecord = $coach->infoRecords()->create(array_merge([
  1152. 'avatar' => $latestRecord->avatar,
  1153. 'life_photos' => $latestRecord->life_photos,
  1154. 'gender' => $latestRecord->gender,
  1155. 'mobile' => $latestRecord->mobile,
  1156. 'birthday' => $latestRecord->birthday,
  1157. 'work_years' => $latestRecord->work_years,
  1158. 'intention_city' => $latestRecord->intention_city,
  1159. 'introduction' => $latestRecord->introduction,
  1160. 'state' => TechnicianAuthStatus::AUDITING->value,
  1161. ], $updateFields)); // 使用新的字段值覆盖
  1162. return [
  1163. 'message' => '基础信息修改申请已提交',
  1164. 'record_id' => $newRecord->id,
  1165. 'updated_fields' => array_keys($updateFields)
  1166. ];
  1167. });
  1168. }
  1169. /**
  1170. * 验证手机验证码
  1171. *
  1172. * @param string $mobile 手机号
  1173. * @param string $code 验证码
  1174. * @throws \Illuminate\Http\Exceptions\HttpResponseException
  1175. */
  1176. private function verifyMobileCode(string $mobile, string $code): void
  1177. {
  1178. // 缓存键
  1179. $cacheKey = "sms_code:update:{$mobile}";
  1180. // 获取缓存中的验证码
  1181. $cacheCode = Redis::get($cacheKey);
  1182. // 验证码不存在或不匹配
  1183. abort_if(!$cacheCode || $cacheCode !== $code, 422, '验证码错误或已过期');
  1184. // 验证成功后删除验证码
  1185. Redis::del($cacheKey);
  1186. }
  1187. /**
  1188. * 发送验证码
  1189. *
  1190. * 业务流程:
  1191. * 1. 检查手机号是否已被使用
  1192. * 2. 生成验证码
  1193. * 3. 保存到 Redis
  1194. * 4. 发送验证码
  1195. *
  1196. * @param array $data 包含:
  1197. * - mobile: string 手机号
  1198. * - type: string 验证码类型
  1199. * @return array 返回结果
  1200. */
  1201. public function sendVerifyCode(array $data): array
  1202. {
  1203. // 检查手机号是否已被使用
  1204. $exists = MemberUser::where('mobile', $data['mobile'])
  1205. ->whereHas('coach')
  1206. ->exists();
  1207. abort_if($exists, 422, '该手机号已被使用');
  1208. // 生成6位随机验证码
  1209. $code = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
  1210. // 验证码有效期(5分钟)
  1211. $expireTime = 300;
  1212. // 缓存键
  1213. $cacheKey = "sms_code:{$data['type']}:{$data['mobile']}";
  1214. // 保存到Redis,设置5分钟过期
  1215. Redis::setex($cacheKey, $expireTime, $code);
  1216. return [
  1217. 'code' => $code,
  1218. 'mobile' => substr_replace($data['mobile'], '****', 3, 4),
  1219. 'expire_time' => $expireTime
  1220. ];
  1221. }
  1222. /**
  1223. * 获取等级文本
  1224. * 将等级数值转换为对应的文本描述
  1225. *
  1226. * @param int $level 等级值
  1227. * @return string 等级文本描述
  1228. */
  1229. private function getLevelText(int $level): string
  1230. {
  1231. // 使用 match 表达式转换等级文本
  1232. return match ($level) {
  1233. 1 => '初级技师',
  1234. 2 => '中级技师',
  1235. 3 => '高级技师',
  1236. default => '未知等级',
  1237. };
  1238. }
  1239. /**
  1240. * 获取技师已开通的项目列表
  1241. *
  1242. * 业务逻辑:
  1243. * 1. 获取技师开通的所有项目
  1244. * 2. 预加载项目基础信息
  1245. * 3. 格式化返回数据
  1246. *
  1247. * @param int $coachId 技师ID
  1248. * @return array 项目列表数据,包含:
  1249. * - total: int 总数
  1250. * - list: array 项目列表
  1251. */
  1252. public function getEnabledProjects(int $coachId): array
  1253. {
  1254. // 获取技师开通且启用的项目
  1255. $projects = CoachProject::with(['project', 'project.category'])
  1256. ->where('coach_id', $coachId)
  1257. ->where('state', ProjectStatus::OPEN->value)
  1258. ->get();
  1259. // 格式化项目数据
  1260. $list = $projects->map(function ($item) {
  1261. return [
  1262. 'id' => $item->id,
  1263. 'project_id' => $item->project_id,
  1264. 'project_name' => $item->project?->name,
  1265. 'category_id' => $item->project?->category_id,
  1266. 'category_name' => $item->project?->category?->name,
  1267. 'duration' => $item->project?->duration, // 服务时长(分钟)
  1268. 'price' => $item->project?->price, // 项目价格
  1269. 'discount_amount' => $item->discount_amount, // 优惠金额
  1270. 'final_price' => $item->project?->price - $item->discount_amount, // 最终价格
  1271. 'service_gender' => $item->service_gender, // 服务性别
  1272. 'service_distance' => $item->service_distance, // 服务距离(米)
  1273. 'traffic_fee_type' => $item->traffic_fee_type, // 路费类型
  1274. 'traffic_fee' => $item->traffic_fee, // 路费金额
  1275. 'created_at' => $item->created_at?->format('Y-m-d H:i:s'),
  1276. 'updated_at' => $item->updated_at?->format('Y-m-d H:i:s'),
  1277. ];
  1278. })->values()->all();
  1279. return [
  1280. 'total' => count($list),
  1281. 'list' => $list
  1282. ];
  1283. }
  1284. /**
  1285. * 获取订单统计数据
  1286. *
  1287. * @param int $coachId 技师ID
  1288. * @return array 订单统计数据
  1289. */
  1290. private function getOrderStatistics(int $coachId): array
  1291. {
  1292. // 从 Order 表获取订单统计
  1293. $orderStats = Order::where('coach_id', $coachId)
  1294. ->selectRaw('
  1295. COUNT(*) as total_count,
  1296. SUM(CASE WHEN state = ? THEN 1 ELSE 0 END) as completed_count,
  1297. SUM(CASE WHEN state IN (?,?,?,?,?,?,?,?) THEN 1 ELSE 0 END) as pending_count,
  1298. SUM(CASE WHEN state = ? THEN 1 ELSE 0 END) as carrying_count
  1299. ', [
  1300. OrderStatus::COMPLETED->value, // 已完成
  1301. OrderStatus::PAID->value, // 已支付
  1302. OrderStatus::ACCEPTED->value, // 已接单
  1303. OrderStatus::DEPARTED->value, // 已出发
  1304. OrderStatus::ARRIVED->value, // 已到达
  1305. OrderStatus::SERVICE_START->value, // 开始服务
  1306. OrderStatus::SERVICING->value, // 服务中
  1307. OrderStatus::SERVICE_END->value, // 服务结束
  1308. OrderStatus::LEAVING->value, // 撤离中
  1309. OrderStatus::PAID->value // 带接单(已支付)
  1310. ])
  1311. ->first();
  1312. // 获取抢单数量
  1313. $grabOrderCount = OrderGrabRecord::where('coach_id', $coachId)->count();
  1314. return [
  1315. 'order_count' => $orderStats->total_count ?? 0, // 总订单数
  1316. 'completed_order_count' => $orderStats->completed_count ?? 0, // 已完成订单数
  1317. 'pending_order_count' => $orderStats->pending_count ?? 0, // 进行中订单数
  1318. 'carrying_order_count' => $orderStats->carrying_count ?? 0, // 带接单数量
  1319. 'grab_order_count' => $grabOrderCount, // 抢单数量
  1320. ];
  1321. }
  1322. }