| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496 |
- package com.train.service.impl;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.train.common.Result;
- import com.train.entity.TrainCreditAccount;
- import com.train.entity.TrainCreditLedger;
- import com.train.entity.TrainOrgMember;
- import com.train.entity.TrainPractitionerLicense;
- import com.train.entity.TrainPractitionerProfile;
- import com.train.entity.TrainUser;
- import com.train.mapper.TrainCreditAccountMapper;
- import com.train.mapper.TrainCreditLedgerMapper;
- import com.train.mapper.TrainOrgMemberMapper;
- import com.train.mapper.TrainPractitionerLicenseMapper;
- import com.train.mapper.TrainPractitionerProfileMapper;
- import com.train.mapper.TrainUserMapper;
- import com.train.service.PractitionerService;
- import com.train.service.RoleGuard;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.stereotype.Service;
- import org.springframework.util.StringUtils;
- import javax.annotation.Resource;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- /**
- * 人员档案服务实现(服务人员工作助手 · 健康服务人员助手)
- *
- * 脱敏规则:
- * - display_name 落库即脱敏(张*三),读时再兜底 maskName 一次(幂等);
- * - 电话 138****1234(maskPhone);地址截断(maskAddress,M2 引入地址来源字段后接入)。
- * 权限:mine=本人;detail/adminList 在 Service 层做角色校验(admin 或 org 成员可查)。
- */
- @Slf4j
- @Service
- public class PractitionerServiceImpl implements PractitionerService {
- /** 档案默认值(对齐 DDL 默认值) */
- private static final String PROFILE_LIFECYCLE_TRAINING = "training";
- private static final String PROFILE_AUTH_NONE = "none";
- private static final String PROFILE_SERVICE_OFF = "off";
- private static final String PROFILE_STATUS_PENDING = "pending";
- /** 软删除位默认值 = 0 正常(对齐 DDL DEFAULT 0) */
- private static final int DELETED_NORMAL = 0;
- private static final String ORG_MEMBER_STATUS_ACTIVE = "active";
- /** 资质核验状态:verified 已核(有效证书口径) */
- private static final String LICENSE_VERIFY_VERIFIED = "verified";
- /** 学时台账状态:effective 已生效 */
- private static final String LEDGER_STATUS_EFFECTIVE = "effective";
- @Resource
- private TrainPractitionerProfileMapper trainPractitionerProfileMapper;
- @Resource
- private TrainUserMapper trainUserMapper;
- @Resource
- private TrainOrgMemberMapper trainOrgMemberMapper;
- @Resource
- private TrainPractitionerLicenseMapper trainPractitionerLicenseMapper;
- @Resource
- private TrainCreditAccountMapper trainCreditAccountMapper;
- @Resource
- private TrainCreditLedgerMapper trainCreditLedgerMapper;
- @Resource
- private RoleGuard roleGuard;
- @Override
- public Result<Map<String, Object>> mine(Long userId) {
- if (userId == null) {
- return Result.error("请先登录");
- }
- TrainPractitionerProfile p = ensureProfile(userId);
- if (p == null) {
- return Result.error("档案创建失败,请稍后重试");
- }
- TrainUser user = trainUserMapper.selectById(userId);
- return Result.success(toVO(p, user));
- }
- @Override
- public Result<Map<String, Object>> detail(Long userId, Boolean isAdmin, Long targetUserId) {
- if (targetUserId == null) {
- return Result.error("缺少目标用户ID");
- }
- // 角色校验下沉 Service 层:admin 或 org 成员可查(本人恒可查)
- boolean allowed = Boolean.TRUE.equals(isAdmin)
- || (userId != null && userId.equals(targetUserId))
- || isActiveOrgMember(userId);
- if (!allowed) {
- return Result.error("无权限查看档案");
- }
- TrainPractitionerProfile p = selectByUserId(targetUserId);
- if (p == null) {
- return Result.error("档案不存在");
- }
- TrainUser user = trainUserMapper.selectById(targetUserId);
- return Result.success(toVO(p, user));
- }
- @Override
- public Result<Map<String, Object>> adminList(Long userId, Boolean isAdmin, Map<String, Object> body) {
- int page = body == null ? 1 : toInt(body.get("page"), 1);
- int size = body == null ? 20 : toInt(body.get("size"), 20);
- if (page < 1) {
- page = 1;
- }
- if (size < 1) {
- size = 20;
- }
- if (size > 100) {
- size = 100;
- }
- String keyword = body == null ? null : str(body.get("keyword"));
- String level = body == null ? null : str(body.get("level"));
- String authLevel = body == null ? null : str(body.get("authLevel"));
- List<Long> orgUserIds = null;
- if (!Boolean.TRUE.equals(isAdmin)) {
- // org 成员:必须指定 orgId 且做归属校验,只能查本机构成员档案
- if (userId == null) {
- return Result.error("请先登录");
- }
- Long orgId = body == null ? null : toLong(body.get("orgId"));
- if (orgId == null) {
- return Result.error("非管理员查询需指定 orgId");
- }
- String guardErr = roleGuard.requireOrgMember(userId, orgId);
- if (guardErr != null) {
- return Result.error(guardErr);
- }
- orgUserIds = orgMemberUserIds(orgId);
- }
- LambdaQueryWrapper<TrainPractitionerProfile> base = baseWrapper(keyword, level, authLevel, orgUserIds);
- Long total = trainPractitionerProfileMapper.selectCount(base);
- if (total == null) {
- total = 0L;
- }
- int offset = (page - 1) * size;
- LambdaQueryWrapper<TrainPractitionerProfile> pageQ = baseWrapper(keyword, level, authLevel, orgUserIds);
- pageQ.orderByDesc(TrainPractitionerProfile::getId).last("LIMIT " + offset + "," + size);
- List<TrainPractitionerProfile> list = trainPractitionerProfileMapper.selectList(pageQ);
- // 批量预取证书数/学时余额,避免逐行 N+1(与 mine/detail 共用同一 VO 组装口径)
- List<Long> rowUserIds = new ArrayList<>();
- for (TrainPractitionerProfile p : list) {
- if (p.getUserId() != null) {
- rowUserIds.add(p.getUserId());
- }
- }
- Map<Long, Integer> certCounts = batchCertCounts(rowUserIds);
- Map<Long, Integer> creditTotals = batchCreditTotals(rowUserIds);
- List<Map<String, Object>> rows = new ArrayList<>();
- for (TrainPractitionerProfile p : list) {
- rows.add(toVO(p, trainUserMapper.selectById(p.getUserId()), certCounts, creditTotals));
- }
- Map<String, Object> result = new HashMap<>();
- result.put("total", total);
- result.put("page", page);
- result.put("size", size);
- result.put("list", rows);
- return Result.success(result);
- }
- @Override
- public TrainPractitionerProfile ensureProfile(Long userId) {
- if (userId == null) {
- return null;
- }
- TrainPractitionerProfile exist = selectByUserId(userId);
- if (exist != null) {
- return exist;
- }
- TrainUser user = trainUserMapper.selectById(userId);
- TrainPractitionerProfile p = new TrainPractitionerProfile();
- p.setUserId(userId);
- if (user != null) {
- p.setCfcUserId(user.getCfcUserId());
- }
- p.setDisplayName(maskName(user == null ? null : user.getName()));
- p.setLifecycleStage(PROFILE_LIFECYCLE_TRAINING);
- p.setAuthLevel(PROFILE_AUTH_NONE);
- p.setPracticeYears(0);
- p.setServiceStatus(PROFILE_SERVICE_OFF);
- p.setRating(0D);
- p.setServeCount(0);
- p.setStatus(PROFILE_STATUS_PENDING);
- p.setDeleted(DELETED_NORMAL);
- p.setCreatedAt(new Date());
- p.setUpdatedAt(new Date());
- try {
- trainPractitionerProfileMapper.insert(p);
- } catch (Exception e) {
- // uk user_id 并发冲突/重复建档:已存在则返回既有档案
- log.warn("建档插入冲突或失败: userId={}, err={}", userId, e.getMessage());
- TrainPractitionerProfile again = selectByUserId(userId);
- if (again != null) {
- return again;
- }
- return null;
- }
- return p;
- }
- // ---------- 内部工具 ----------
- private LambdaQueryWrapper<TrainPractitionerProfile> baseWrapper(String keyword, String level,
- String authLevel, List<Long> orgUserIds) {
- LambdaQueryWrapper<TrainPractitionerProfile> qw = new LambdaQueryWrapper<>();
- qw.eq(TrainPractitionerProfile::getDeleted, 0);
- if (StringUtils.hasText(keyword)) {
- qw.like(TrainPractitionerProfile::getDisplayName, keyword.trim());
- }
- if (StringUtils.hasText(level)) {
- qw.eq(TrainPractitionerProfile::getLevel, level.trim());
- }
- if (StringUtils.hasText(authLevel)) {
- qw.eq(TrainPractitionerProfile::getAuthLevel, authLevel.trim());
- }
- if (orgUserIds != null) {
- if (orgUserIds.isEmpty()) {
- qw.eq(TrainPractitionerProfile::getUserId, -1L); // 空集合 → 恒 false
- } else {
- qw.in(TrainPractitionerProfile::getUserId, orgUserIds);
- }
- }
- return qw;
- }
- private List<Long> orgMemberUserIds(Long orgId) {
- List<TrainOrgMember> members = trainOrgMemberMapper.selectList(
- new LambdaQueryWrapper<TrainOrgMember>()
- .eq(TrainOrgMember::getOrgId, orgId)
- .eq(TrainOrgMember::getStatus, ORG_MEMBER_STATUS_ACTIVE)
- .eq(TrainOrgMember::getDeleted, 0));
- List<Long> ids = new ArrayList<>();
- if (members != null) {
- for (TrainOrgMember m : members) {
- ids.add(m.getUserId());
- }
- }
- return ids;
- }
- private boolean isActiveOrgMember(Long userId) {
- if (userId == null) {
- return false;
- }
- Long cnt = trainOrgMemberMapper.selectCount(
- new LambdaQueryWrapper<TrainOrgMember>()
- .eq(TrainOrgMember::getUserId, userId)
- .eq(TrainOrgMember::getStatus, ORG_MEMBER_STATUS_ACTIVE)
- .eq(TrainOrgMember::getDeleted, 0));
- return cnt != null && cnt > 0;
- }
- private TrainPractitionerProfile selectByUserId(Long userId) {
- if (userId == null) {
- return null;
- }
- return trainPractitionerProfileMapper.selectOne(
- new LambdaQueryWrapper<TrainPractitionerProfile>()
- .eq(TrainPractitionerProfile::getUserId, userId)
- .eq(TrainPractitionerProfile::getDeleted, 0)
- .last("LIMIT 1"));
- }
- private Map<String, Object> toVO(TrainPractitionerProfile p, TrainUser u) {
- return toVO(p, u, null, null);
- }
- /**
- * 档案 VO 组装(mine / detail / adminList 三处共用同一组装函数,保证字段口径一致)。
- *
- * 字段键契约(与前端 pages/practitioner/index.vue、detail.vue 绑定一致):
- * - name = displayName 同值(保持脱敏)
- * - certCount = 有效证书数(verify_status=verified 且未过期)
- * - creditTotal = 学时账户余额(分钟整数,来自 train_credit_account.effective_hours;
- * 无账户行时回退为台账 effective 汇总;无记录返回 0)
- * - address = 服务地址(M1 基线无个人地址列,返回空串,前端 v-if 隐藏)
- *
- * @param certCounts 批量证书数(adminList 传入,null 则单查)
- * @param creditTotals 批量学时余额(adminList 传入,null 则单查)
- */
- private Map<String, Object> toVO(TrainPractitionerProfile p, TrainUser u,
- Map<Long, Integer> certCounts, Map<Long, Integer> creditTotals) {
- Map<String, Object> m = new HashMap<>();
- String displayName = maskName(p.getDisplayName());
- m.put("id", p.getId());
- m.put("userId", p.getUserId());
- m.put("cfcUserId", p.getCfcUserId());
- m.put("displayName", displayName);
- // 前端绑定键:姓名(与 displayName 同值,保持脱敏)
- m.put("name", displayName);
- m.put("level", p.getLevel());
- m.put("lifecycleStage", p.getLifecycleStage());
- m.put("authLevel", p.getAuthLevel());
- m.put("specialties", p.getSpecialties());
- m.put("practiceYears", p.getPracticeYears() == null ? 0 : p.getPracticeYears());
- m.put("serviceStatus", p.getServiceStatus());
- m.put("rating", p.getRating() == null ? 0 : p.getRating());
- m.put("serveCount", p.getServeCount() == null ? 0 : p.getServeCount());
- m.put("status", p.getStatus());
- m.put("phone", maskPhone(u == null ? null : u.getPhone()));
- // 前端绑定键:有效证书数 / 学时余额(分钟) / 服务地址
- m.put("certCount", certCountOf(p.getUserId(), certCounts));
- m.put("creditTotal", creditTotalOf(p.getUserId(), creditTotals));
- m.put("address", "");
- m.put("createdAt", fmt(p.getCreatedAt()));
- m.put("updatedAt", fmt(p.getUpdatedAt()));
- return m;
- }
- /** 有效证书数:批量优先,否则单查;无证书返回 0 */
- private int certCountOf(Long userId, Map<Long, Integer> certCounts) {
- if (userId == null) {
- return 0;
- }
- if (certCounts != null) {
- Integer c = certCounts.get(userId);
- return c == null ? 0 : c;
- }
- Long cnt = trainPractitionerLicenseMapper.selectCount(validCertWrapper()
- .eq(TrainPractitionerLicense::getUserId, userId));
- return cnt == null ? 0 : cnt.intValue();
- }
- /** 学时账户余额(分钟整数):批量优先,否则单查;无记录返回 0 */
- private int creditTotalOf(Long userId, Map<Long, Integer> creditTotals) {
- if (userId == null) {
- return 0;
- }
- if (creditTotals != null) {
- Integer c = creditTotals.get(userId);
- return c == null ? 0 : c;
- }
- TrainCreditAccount account = trainCreditAccountMapper.selectOne(
- new LambdaQueryWrapper<TrainCreditAccount>()
- .eq(TrainCreditAccount::getUserId, userId)
- .last("LIMIT 1"));
- if (account != null) {
- return account.getEffectiveHours() == null ? 0 : account.getEffectiveHours();
- }
- // 无账户行 → 回退为台账 effective 汇总
- List<TrainCreditLedger> ledgers = trainCreditLedgerMapper.selectList(
- new LambdaQueryWrapper<TrainCreditLedger>()
- .eq(TrainCreditLedger::getUserId, userId)
- .eq(TrainCreditLedger::getStatus, LEDGER_STATUS_EFFECTIVE)
- .eq(TrainCreditLedger::getDeleted, DELETED_NORMAL));
- int sum = 0;
- if (ledgers != null) {
- for (TrainCreditLedger l : ledgers) {
- sum += l.getHours() == null ? 0 : l.getHours();
- }
- }
- return sum;
- }
- /** 有效证书条件:已核验(verified)+ 未软删 + 未过期(expire_at 为空视为长期有效) */
- private LambdaQueryWrapper<TrainPractitionerLicense> validCertWrapper() {
- LambdaQueryWrapper<TrainPractitionerLicense> qw = new LambdaQueryWrapper<>();
- qw.eq(TrainPractitionerLicense::getDeleted, DELETED_NORMAL);
- qw.eq(TrainPractitionerLicense::getVerifyStatus, LICENSE_VERIFY_VERIFIED);
- qw.and(w -> w.isNull(TrainPractitionerLicense::getExpireAt)
- .or().ge(TrainPractitionerLicense::getExpireAt, todayStart()));
- return qw;
- }
- /** 今日 00:00:00(证书到期日当天仍视为有效) */
- private Date todayStart() {
- Calendar cal = Calendar.getInstance();
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
- return cal.getTime();
- }
- /** 批量统计有效证书数(adminList 用,避免 N+1) */
- private Map<Long, Integer> batchCertCounts(List<Long> userIds) {
- Map<Long, Integer> map = new HashMap<>();
- if (userIds == null || userIds.isEmpty()) {
- return map;
- }
- List<TrainPractitionerLicense> list = trainPractitionerLicenseMapper.selectList(
- validCertWrapper().in(TrainPractitionerLicense::getUserId, userIds));
- if (list != null) {
- for (TrainPractitionerLicense lic : list) {
- Long uid = lic.getUserId();
- Integer c = map.get(uid);
- map.put(uid, c == null ? 1 : c + 1);
- }
- }
- return map;
- }
- /** 批量取学时账户余额(adminList 用,避免 N+1) */
- private Map<Long, Integer> batchCreditTotals(List<Long> userIds) {
- Map<Long, Integer> map = new HashMap<>();
- if (userIds == null || userIds.isEmpty()) {
- return map;
- }
- List<TrainCreditAccount> accounts = trainCreditAccountMapper.selectList(
- new LambdaQueryWrapper<TrainCreditAccount>()
- .in(TrainCreditAccount::getUserId, userIds));
- if (accounts != null) {
- for (TrainCreditAccount a : accounts) {
- map.put(a.getUserId(), a.getEffectiveHours() == null ? 0 : a.getEffectiveHours());
- }
- }
- return map;
- }
- /** 姓名脱敏:张*三(幂等,对已脱敏串再脱敏结果不变) */
- private String maskName(String name) {
- if (name == null || name.trim().isEmpty()) {
- return name;
- }
- name = name.trim();
- int len = name.length();
- if (len == 1) {
- return "*";
- }
- if (len == 2) {
- return name.substring(0, 1) + "*";
- }
- return name.substring(0, 1) + "*" + name.substring(len - 1);
- }
- /** 电话脱敏:138****1234 */
- private String maskPhone(String phone) {
- if (phone == null || phone.trim().isEmpty()) {
- return phone;
- }
- phone = phone.trim();
- if (phone.length() < 7) {
- return phone.substring(0, 1) + "****";
- }
- return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4);
- }
- /**
- * 地址截断脱敏(保留前 12 字 + …)。
- * M1 基线 schema 无个人地址列(train_user 无 address),地址来源为 M2 工单/机构,
- * 本方法为统一脱敏工具预留,接入后统一调用。
- */
- private String maskAddress(String address) {
- if (address == null || address.trim().isEmpty()) {
- return address;
- }
- address = address.trim();
- return address.length() <= 12 ? address : address.substring(0, 12) + "…";
- }
- private String fmt(Date d) {
- return d == null ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm").format(d);
- }
- private String str(Object v) {
- return v == null ? null : v.toString();
- }
- private Long toLong(Object v) {
- if (v == null) {
- return null;
- }
- try {
- return Long.valueOf(v.toString().trim());
- } catch (NumberFormatException e) {
- return null;
- }
- }
- private int toInt(Object v, int def) {
- if (v == null) {
- return def;
- }
- try {
- return Integer.parseInt(v.toString().trim());
- } catch (NumberFormatException e) {
- return def;
- }
- }
- }
|