PractitionerServiceImpl.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. package com.train.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.train.common.Result;
  4. import com.train.entity.TrainCreditAccount;
  5. import com.train.entity.TrainCreditLedger;
  6. import com.train.entity.TrainOrgMember;
  7. import com.train.entity.TrainPractitionerLicense;
  8. import com.train.entity.TrainPractitionerProfile;
  9. import com.train.entity.TrainUser;
  10. import com.train.mapper.TrainCreditAccountMapper;
  11. import com.train.mapper.TrainCreditLedgerMapper;
  12. import com.train.mapper.TrainOrgMemberMapper;
  13. import com.train.mapper.TrainPractitionerLicenseMapper;
  14. import com.train.mapper.TrainPractitionerProfileMapper;
  15. import com.train.mapper.TrainUserMapper;
  16. import com.train.service.PractitionerService;
  17. import com.train.service.RoleGuard;
  18. import lombok.extern.slf4j.Slf4j;
  19. import org.springframework.stereotype.Service;
  20. import org.springframework.util.StringUtils;
  21. import javax.annotation.Resource;
  22. import java.text.SimpleDateFormat;
  23. import java.util.ArrayList;
  24. import java.util.Calendar;
  25. import java.util.Date;
  26. import java.util.HashMap;
  27. import java.util.List;
  28. import java.util.Map;
  29. /**
  30. * 人员档案服务实现(服务人员工作助手 · 健康服务人员助手)
  31. *
  32. * 脱敏规则:
  33. * - display_name 落库即脱敏(张*三),读时再兜底 maskName 一次(幂等);
  34. * - 电话 138****1234(maskPhone);地址截断(maskAddress,M2 引入地址来源字段后接入)。
  35. * 权限:mine=本人;detail/adminList 在 Service 层做角色校验(admin 或 org 成员可查)。
  36. */
  37. @Slf4j
  38. @Service
  39. public class PractitionerServiceImpl implements PractitionerService {
  40. /** 档案默认值(对齐 DDL 默认值) */
  41. private static final String PROFILE_LIFECYCLE_TRAINING = "training";
  42. private static final String PROFILE_AUTH_NONE = "none";
  43. private static final String PROFILE_SERVICE_OFF = "off";
  44. private static final String PROFILE_STATUS_PENDING = "pending";
  45. /** 软删除位默认值 = 0 正常(对齐 DDL DEFAULT 0) */
  46. private static final int DELETED_NORMAL = 0;
  47. private static final String ORG_MEMBER_STATUS_ACTIVE = "active";
  48. /** 资质核验状态:verified 已核(有效证书口径) */
  49. private static final String LICENSE_VERIFY_VERIFIED = "verified";
  50. /** 学时台账状态:effective 已生效 */
  51. private static final String LEDGER_STATUS_EFFECTIVE = "effective";
  52. @Resource
  53. private TrainPractitionerProfileMapper trainPractitionerProfileMapper;
  54. @Resource
  55. private TrainUserMapper trainUserMapper;
  56. @Resource
  57. private TrainOrgMemberMapper trainOrgMemberMapper;
  58. @Resource
  59. private TrainPractitionerLicenseMapper trainPractitionerLicenseMapper;
  60. @Resource
  61. private TrainCreditAccountMapper trainCreditAccountMapper;
  62. @Resource
  63. private TrainCreditLedgerMapper trainCreditLedgerMapper;
  64. @Resource
  65. private RoleGuard roleGuard;
  66. @Override
  67. public Result<Map<String, Object>> mine(Long userId) {
  68. if (userId == null) {
  69. return Result.error("请先登录");
  70. }
  71. TrainPractitionerProfile p = ensureProfile(userId);
  72. if (p == null) {
  73. return Result.error("档案创建失败,请稍后重试");
  74. }
  75. TrainUser user = trainUserMapper.selectById(userId);
  76. return Result.success(toVO(p, user));
  77. }
  78. @Override
  79. public Result<Map<String, Object>> detail(Long userId, Boolean isAdmin, Long targetUserId) {
  80. if (targetUserId == null) {
  81. return Result.error("缺少目标用户ID");
  82. }
  83. // 角色校验下沉 Service 层:admin 或 org 成员可查(本人恒可查)
  84. boolean allowed = Boolean.TRUE.equals(isAdmin)
  85. || (userId != null && userId.equals(targetUserId))
  86. || isActiveOrgMember(userId);
  87. if (!allowed) {
  88. return Result.error("无权限查看档案");
  89. }
  90. TrainPractitionerProfile p = selectByUserId(targetUserId);
  91. if (p == null) {
  92. return Result.error("档案不存在");
  93. }
  94. TrainUser user = trainUserMapper.selectById(targetUserId);
  95. return Result.success(toVO(p, user));
  96. }
  97. @Override
  98. public Result<Map<String, Object>> adminList(Long userId, Boolean isAdmin, Map<String, Object> body) {
  99. int page = body == null ? 1 : toInt(body.get("page"), 1);
  100. int size = body == null ? 20 : toInt(body.get("size"), 20);
  101. if (page < 1) {
  102. page = 1;
  103. }
  104. if (size < 1) {
  105. size = 20;
  106. }
  107. if (size > 100) {
  108. size = 100;
  109. }
  110. String keyword = body == null ? null : str(body.get("keyword"));
  111. String level = body == null ? null : str(body.get("level"));
  112. String authLevel = body == null ? null : str(body.get("authLevel"));
  113. List<Long> orgUserIds = null;
  114. if (!Boolean.TRUE.equals(isAdmin)) {
  115. // org 成员:必须指定 orgId 且做归属校验,只能查本机构成员档案
  116. if (userId == null) {
  117. return Result.error("请先登录");
  118. }
  119. Long orgId = body == null ? null : toLong(body.get("orgId"));
  120. if (orgId == null) {
  121. return Result.error("非管理员查询需指定 orgId");
  122. }
  123. String guardErr = roleGuard.requireOrgMember(userId, orgId);
  124. if (guardErr != null) {
  125. return Result.error(guardErr);
  126. }
  127. orgUserIds = orgMemberUserIds(orgId);
  128. }
  129. LambdaQueryWrapper<TrainPractitionerProfile> base = baseWrapper(keyword, level, authLevel, orgUserIds);
  130. Long total = trainPractitionerProfileMapper.selectCount(base);
  131. if (total == null) {
  132. total = 0L;
  133. }
  134. int offset = (page - 1) * size;
  135. LambdaQueryWrapper<TrainPractitionerProfile> pageQ = baseWrapper(keyword, level, authLevel, orgUserIds);
  136. pageQ.orderByDesc(TrainPractitionerProfile::getId).last("LIMIT " + offset + "," + size);
  137. List<TrainPractitionerProfile> list = trainPractitionerProfileMapper.selectList(pageQ);
  138. // 批量预取证书数/学时余额,避免逐行 N+1(与 mine/detail 共用同一 VO 组装口径)
  139. List<Long> rowUserIds = new ArrayList<>();
  140. for (TrainPractitionerProfile p : list) {
  141. if (p.getUserId() != null) {
  142. rowUserIds.add(p.getUserId());
  143. }
  144. }
  145. Map<Long, Integer> certCounts = batchCertCounts(rowUserIds);
  146. Map<Long, Integer> creditTotals = batchCreditTotals(rowUserIds);
  147. List<Map<String, Object>> rows = new ArrayList<>();
  148. for (TrainPractitionerProfile p : list) {
  149. rows.add(toVO(p, trainUserMapper.selectById(p.getUserId()), certCounts, creditTotals));
  150. }
  151. Map<String, Object> result = new HashMap<>();
  152. result.put("total", total);
  153. result.put("page", page);
  154. result.put("size", size);
  155. result.put("list", rows);
  156. return Result.success(result);
  157. }
  158. @Override
  159. public TrainPractitionerProfile ensureProfile(Long userId) {
  160. if (userId == null) {
  161. return null;
  162. }
  163. TrainPractitionerProfile exist = selectByUserId(userId);
  164. if (exist != null) {
  165. return exist;
  166. }
  167. TrainUser user = trainUserMapper.selectById(userId);
  168. TrainPractitionerProfile p = new TrainPractitionerProfile();
  169. p.setUserId(userId);
  170. if (user != null) {
  171. p.setCfcUserId(user.getCfcUserId());
  172. }
  173. p.setDisplayName(maskName(user == null ? null : user.getName()));
  174. p.setLifecycleStage(PROFILE_LIFECYCLE_TRAINING);
  175. p.setAuthLevel(PROFILE_AUTH_NONE);
  176. p.setPracticeYears(0);
  177. p.setServiceStatus(PROFILE_SERVICE_OFF);
  178. p.setRating(0D);
  179. p.setServeCount(0);
  180. p.setStatus(PROFILE_STATUS_PENDING);
  181. p.setDeleted(DELETED_NORMAL);
  182. p.setCreatedAt(new Date());
  183. p.setUpdatedAt(new Date());
  184. try {
  185. trainPractitionerProfileMapper.insert(p);
  186. } catch (Exception e) {
  187. // uk user_id 并发冲突/重复建档:已存在则返回既有档案
  188. log.warn("建档插入冲突或失败: userId={}, err={}", userId, e.getMessage());
  189. TrainPractitionerProfile again = selectByUserId(userId);
  190. if (again != null) {
  191. return again;
  192. }
  193. return null;
  194. }
  195. return p;
  196. }
  197. // ---------- 内部工具 ----------
  198. private LambdaQueryWrapper<TrainPractitionerProfile> baseWrapper(String keyword, String level,
  199. String authLevel, List<Long> orgUserIds) {
  200. LambdaQueryWrapper<TrainPractitionerProfile> qw = new LambdaQueryWrapper<>();
  201. qw.eq(TrainPractitionerProfile::getDeleted, 0);
  202. if (StringUtils.hasText(keyword)) {
  203. qw.like(TrainPractitionerProfile::getDisplayName, keyword.trim());
  204. }
  205. if (StringUtils.hasText(level)) {
  206. qw.eq(TrainPractitionerProfile::getLevel, level.trim());
  207. }
  208. if (StringUtils.hasText(authLevel)) {
  209. qw.eq(TrainPractitionerProfile::getAuthLevel, authLevel.trim());
  210. }
  211. if (orgUserIds != null) {
  212. if (orgUserIds.isEmpty()) {
  213. qw.eq(TrainPractitionerProfile::getUserId, -1L); // 空集合 → 恒 false
  214. } else {
  215. qw.in(TrainPractitionerProfile::getUserId, orgUserIds);
  216. }
  217. }
  218. return qw;
  219. }
  220. private List<Long> orgMemberUserIds(Long orgId) {
  221. List<TrainOrgMember> members = trainOrgMemberMapper.selectList(
  222. new LambdaQueryWrapper<TrainOrgMember>()
  223. .eq(TrainOrgMember::getOrgId, orgId)
  224. .eq(TrainOrgMember::getStatus, ORG_MEMBER_STATUS_ACTIVE)
  225. .eq(TrainOrgMember::getDeleted, 0));
  226. List<Long> ids = new ArrayList<>();
  227. if (members != null) {
  228. for (TrainOrgMember m : members) {
  229. ids.add(m.getUserId());
  230. }
  231. }
  232. return ids;
  233. }
  234. private boolean isActiveOrgMember(Long userId) {
  235. if (userId == null) {
  236. return false;
  237. }
  238. Long cnt = trainOrgMemberMapper.selectCount(
  239. new LambdaQueryWrapper<TrainOrgMember>()
  240. .eq(TrainOrgMember::getUserId, userId)
  241. .eq(TrainOrgMember::getStatus, ORG_MEMBER_STATUS_ACTIVE)
  242. .eq(TrainOrgMember::getDeleted, 0));
  243. return cnt != null && cnt > 0;
  244. }
  245. private TrainPractitionerProfile selectByUserId(Long userId) {
  246. if (userId == null) {
  247. return null;
  248. }
  249. return trainPractitionerProfileMapper.selectOne(
  250. new LambdaQueryWrapper<TrainPractitionerProfile>()
  251. .eq(TrainPractitionerProfile::getUserId, userId)
  252. .eq(TrainPractitionerProfile::getDeleted, 0)
  253. .last("LIMIT 1"));
  254. }
  255. private Map<String, Object> toVO(TrainPractitionerProfile p, TrainUser u) {
  256. return toVO(p, u, null, null);
  257. }
  258. /**
  259. * 档案 VO 组装(mine / detail / adminList 三处共用同一组装函数,保证字段口径一致)。
  260. *
  261. * 字段键契约(与前端 pages/practitioner/index.vue、detail.vue 绑定一致):
  262. * - name = displayName 同值(保持脱敏)
  263. * - certCount = 有效证书数(verify_status=verified 且未过期)
  264. * - creditTotal = 学时账户余额(分钟整数,来自 train_credit_account.effective_hours;
  265. * 无账户行时回退为台账 effective 汇总;无记录返回 0)
  266. * - address = 服务地址(M1 基线无个人地址列,返回空串,前端 v-if 隐藏)
  267. *
  268. * @param certCounts 批量证书数(adminList 传入,null 则单查)
  269. * @param creditTotals 批量学时余额(adminList 传入,null 则单查)
  270. */
  271. private Map<String, Object> toVO(TrainPractitionerProfile p, TrainUser u,
  272. Map<Long, Integer> certCounts, Map<Long, Integer> creditTotals) {
  273. Map<String, Object> m = new HashMap<>();
  274. String displayName = maskName(p.getDisplayName());
  275. m.put("id", p.getId());
  276. m.put("userId", p.getUserId());
  277. m.put("cfcUserId", p.getCfcUserId());
  278. m.put("displayName", displayName);
  279. // 前端绑定键:姓名(与 displayName 同值,保持脱敏)
  280. m.put("name", displayName);
  281. m.put("level", p.getLevel());
  282. m.put("lifecycleStage", p.getLifecycleStage());
  283. m.put("authLevel", p.getAuthLevel());
  284. m.put("specialties", p.getSpecialties());
  285. m.put("practiceYears", p.getPracticeYears() == null ? 0 : p.getPracticeYears());
  286. m.put("serviceStatus", p.getServiceStatus());
  287. m.put("rating", p.getRating() == null ? 0 : p.getRating());
  288. m.put("serveCount", p.getServeCount() == null ? 0 : p.getServeCount());
  289. m.put("status", p.getStatus());
  290. m.put("phone", maskPhone(u == null ? null : u.getPhone()));
  291. // 前端绑定键:有效证书数 / 学时余额(分钟) / 服务地址
  292. m.put("certCount", certCountOf(p.getUserId(), certCounts));
  293. m.put("creditTotal", creditTotalOf(p.getUserId(), creditTotals));
  294. m.put("address", "");
  295. m.put("createdAt", fmt(p.getCreatedAt()));
  296. m.put("updatedAt", fmt(p.getUpdatedAt()));
  297. return m;
  298. }
  299. /** 有效证书数:批量优先,否则单查;无证书返回 0 */
  300. private int certCountOf(Long userId, Map<Long, Integer> certCounts) {
  301. if (userId == null) {
  302. return 0;
  303. }
  304. if (certCounts != null) {
  305. Integer c = certCounts.get(userId);
  306. return c == null ? 0 : c;
  307. }
  308. Long cnt = trainPractitionerLicenseMapper.selectCount(validCertWrapper()
  309. .eq(TrainPractitionerLicense::getUserId, userId));
  310. return cnt == null ? 0 : cnt.intValue();
  311. }
  312. /** 学时账户余额(分钟整数):批量优先,否则单查;无记录返回 0 */
  313. private int creditTotalOf(Long userId, Map<Long, Integer> creditTotals) {
  314. if (userId == null) {
  315. return 0;
  316. }
  317. if (creditTotals != null) {
  318. Integer c = creditTotals.get(userId);
  319. return c == null ? 0 : c;
  320. }
  321. TrainCreditAccount account = trainCreditAccountMapper.selectOne(
  322. new LambdaQueryWrapper<TrainCreditAccount>()
  323. .eq(TrainCreditAccount::getUserId, userId)
  324. .last("LIMIT 1"));
  325. if (account != null) {
  326. return account.getEffectiveHours() == null ? 0 : account.getEffectiveHours();
  327. }
  328. // 无账户行 → 回退为台账 effective 汇总
  329. List<TrainCreditLedger> ledgers = trainCreditLedgerMapper.selectList(
  330. new LambdaQueryWrapper<TrainCreditLedger>()
  331. .eq(TrainCreditLedger::getUserId, userId)
  332. .eq(TrainCreditLedger::getStatus, LEDGER_STATUS_EFFECTIVE)
  333. .eq(TrainCreditLedger::getDeleted, DELETED_NORMAL));
  334. int sum = 0;
  335. if (ledgers != null) {
  336. for (TrainCreditLedger l : ledgers) {
  337. sum += l.getHours() == null ? 0 : l.getHours();
  338. }
  339. }
  340. return sum;
  341. }
  342. /** 有效证书条件:已核验(verified)+ 未软删 + 未过期(expire_at 为空视为长期有效) */
  343. private LambdaQueryWrapper<TrainPractitionerLicense> validCertWrapper() {
  344. LambdaQueryWrapper<TrainPractitionerLicense> qw = new LambdaQueryWrapper<>();
  345. qw.eq(TrainPractitionerLicense::getDeleted, DELETED_NORMAL);
  346. qw.eq(TrainPractitionerLicense::getVerifyStatus, LICENSE_VERIFY_VERIFIED);
  347. qw.and(w -> w.isNull(TrainPractitionerLicense::getExpireAt)
  348. .or().ge(TrainPractitionerLicense::getExpireAt, todayStart()));
  349. return qw;
  350. }
  351. /** 今日 00:00:00(证书到期日当天仍视为有效) */
  352. private Date todayStart() {
  353. Calendar cal = Calendar.getInstance();
  354. cal.set(Calendar.HOUR_OF_DAY, 0);
  355. cal.set(Calendar.MINUTE, 0);
  356. cal.set(Calendar.SECOND, 0);
  357. cal.set(Calendar.MILLISECOND, 0);
  358. return cal.getTime();
  359. }
  360. /** 批量统计有效证书数(adminList 用,避免 N+1) */
  361. private Map<Long, Integer> batchCertCounts(List<Long> userIds) {
  362. Map<Long, Integer> map = new HashMap<>();
  363. if (userIds == null || userIds.isEmpty()) {
  364. return map;
  365. }
  366. List<TrainPractitionerLicense> list = trainPractitionerLicenseMapper.selectList(
  367. validCertWrapper().in(TrainPractitionerLicense::getUserId, userIds));
  368. if (list != null) {
  369. for (TrainPractitionerLicense lic : list) {
  370. Long uid = lic.getUserId();
  371. Integer c = map.get(uid);
  372. map.put(uid, c == null ? 1 : c + 1);
  373. }
  374. }
  375. return map;
  376. }
  377. /** 批量取学时账户余额(adminList 用,避免 N+1) */
  378. private Map<Long, Integer> batchCreditTotals(List<Long> userIds) {
  379. Map<Long, Integer> map = new HashMap<>();
  380. if (userIds == null || userIds.isEmpty()) {
  381. return map;
  382. }
  383. List<TrainCreditAccount> accounts = trainCreditAccountMapper.selectList(
  384. new LambdaQueryWrapper<TrainCreditAccount>()
  385. .in(TrainCreditAccount::getUserId, userIds));
  386. if (accounts != null) {
  387. for (TrainCreditAccount a : accounts) {
  388. map.put(a.getUserId(), a.getEffectiveHours() == null ? 0 : a.getEffectiveHours());
  389. }
  390. }
  391. return map;
  392. }
  393. /** 姓名脱敏:张*三(幂等,对已脱敏串再脱敏结果不变) */
  394. private String maskName(String name) {
  395. if (name == null || name.trim().isEmpty()) {
  396. return name;
  397. }
  398. name = name.trim();
  399. int len = name.length();
  400. if (len == 1) {
  401. return "*";
  402. }
  403. if (len == 2) {
  404. return name.substring(0, 1) + "*";
  405. }
  406. return name.substring(0, 1) + "*" + name.substring(len - 1);
  407. }
  408. /** 电话脱敏:138****1234 */
  409. private String maskPhone(String phone) {
  410. if (phone == null || phone.trim().isEmpty()) {
  411. return phone;
  412. }
  413. phone = phone.trim();
  414. if (phone.length() < 7) {
  415. return phone.substring(0, 1) + "****";
  416. }
  417. return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4);
  418. }
  419. /**
  420. * 地址截断脱敏(保留前 12 字 + …)。
  421. * M1 基线 schema 无个人地址列(train_user 无 address),地址来源为 M2 工单/机构,
  422. * 本方法为统一脱敏工具预留,接入后统一调用。
  423. */
  424. private String maskAddress(String address) {
  425. if (address == null || address.trim().isEmpty()) {
  426. return address;
  427. }
  428. address = address.trim();
  429. return address.length() <= 12 ? address : address.substring(0, 12) + "…";
  430. }
  431. private String fmt(Date d) {
  432. return d == null ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm").format(d);
  433. }
  434. private String str(Object v) {
  435. return v == null ? null : v.toString();
  436. }
  437. private Long toLong(Object v) {
  438. if (v == null) {
  439. return null;
  440. }
  441. try {
  442. return Long.valueOf(v.toString().trim());
  443. } catch (NumberFormatException e) {
  444. return null;
  445. }
  446. }
  447. private int toInt(Object v, int def) {
  448. if (v == null) {
  449. return def;
  450. }
  451. try {
  452. return Integer.parseInt(v.toString().trim());
  453. } catch (NumberFormatException e) {
  454. return def;
  455. }
  456. }
  457. }