AccountService.php 51 KB

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