Compare commits

...
2 Commits
Author SHA1 Message Date
wanghu cfe0b0c4f0 userid
build / build-push (push) Successful in 54s
2026-09-20 16:24:33 +08:00
wanghu 988e5ca7f4 userid 2026-09-20 11:32:07 +08:00
6 changed files with 119 additions and 45 deletions
@@ -1,8 +1,8 @@
package com.yunhai.campusnotice.common.listener;
import com.yunhai.campusnotice.entity.BaseEntity;
import com.yunhai.platform.auth.LoginUser;
import com.yunhai.platform.auth.UserContextHolder;
import com.yunhai.platform.auth.spring.CurrentBoaUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.persistence.PrePersist;
@@ -10,38 +10,53 @@ import javax.persistence.PreUpdate;
import java.time.LocalDateTime;
/**
* JPA 审计监听器:在实体持久化/更新前自动填充创建人/更新人(平台当前登录人)与时间戳。
* JPA 审计监听器:在实体持久化/更新前自动填充创建人/更新人与时间戳。
* 对应 {@link BaseEntity} 的 createBy / updateBy / createTime / updateTime 字段。
* 当前登录人取自基础平台 {@link UserContextHolder}。
* 创建人/更新人存用户中心数字用户ID({@link BoaUser#getId()},经 {@link CurrentBoaUser#getUserId()}),
* 不存登录账号;无登录态(定时任务等)或未匹配到用户表时留空,不做账号兜底,
* 避免同列混存两种口径。
* <p>注意:平台 CAS 登录的 {@code LoginUser.userId} 实际填的是登录账号(非数字),
* 故此处不能取 UserContextHolder,必须走 {@link CurrentBoaUser}。
*/
@Component
public class NoticeAuditListener {
@Autowired
private CurrentBoaUser currentBoaUser;
@PrePersist
public void prePersist(BaseEntity entity) {
LocalDateTime now = LocalDateTime.now();
entity.setCreateTime(now);
entity.setUpdateTime(now);
String account = currentAccount();
if (account != null) {
Integer userId = currentUserId();
if (userId != null) {
if (entity.getCreateBy() == null) {
entity.setCreateBy(account);
entity.setCreateBy(userId);
}
entity.setUpdateBy(account);
entity.setUpdateBy(userId);
}
}
@PreUpdate
public void preUpdate(BaseEntity entity) {
entity.setUpdateTime(LocalDateTime.now());
String account = currentAccount();
if (account != null) {
entity.setUpdateBy(account);
Integer userId = currentUserId();
if (userId != null) {
entity.setUpdateBy(userId);
}
}
private String currentAccount() {
LoginUser user = UserContextHolder.get();
return user == null ? null : user.getLoginName();
/** 当前登录人数字用户ID(用户中心 BoaUser.id;无登录态/未匹配用户时为 null) */
private Integer currentUserId() {
if (currentBoaUser == null) {
return null;
}
try {
return currentBoaUser.getUserId();
} catch (Exception e) {
// 无请求上下文(定时任务/启动期)时 ThreadLocal 链路可能不可用,审计留空
return null;
}
}
}
@@ -24,10 +24,10 @@ public abstract class BaseEntity implements Serializable {
private Integer id;
/**
* 创建人登录账号
* 创建人用户ID(用户中心 BoaUser.id;历史存量数据为登录账号字符串,迁移见 sql/audit_by_user_id.sql)
*/
@Column(name = "create_by", updatable = false)
private String createBy;
private Integer createBy;
/**
* 创建时间
@@ -36,10 +36,10 @@ public abstract class BaseEntity implements Serializable {
private LocalDateTime createTime;
/**
* 更新人登录账号
* 更新人用户ID(用户中心 BoaUser.id;历史存量数据为登录账号字符串)
*/
@Column(name = "update_by")
private String updateBy;
private Integer updateBy;
/**
* 更新时间
@@ -18,6 +18,10 @@ import javax.persistence.Table;
@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = false)
public class SysDict extends BaseEntity {
/** 学校ID(多租户隔离:添加时从 BoaUser.currentRole.schId 填充,查询按校过滤;存量数据见 sql/sys_dict_add_sch_id.sql 回填说明) */
@Column(name = "sch_id")
private Integer schId;
/** 字典类型(如 "dept"=所属分类) */
@Column(name = "dict_type", length = 50)
private String dictType;
@@ -84,9 +84,11 @@ public class NoticeVo {
/** 附件ID串("1,2,3",列表页下载入口使用;对齐旧 .NET UpFile 字段) */
private String UpFile;
private String createBy;
/** 创建人用户ID(用户中心数字ID;历史存量数据为登录账号字符串) */
private Integer createBy;
private LocalDateTime createTime;
private String updateBy;
/** 更新人用户ID(用户中心数字ID;历史存量数据为登录账号字符串) */
private Integer updateBy;
private LocalDateTime updateTime;
/**
@@ -7,9 +7,20 @@ import java.util.List;
import java.util.Optional;
public interface SysDictRepository extends JpaRepository<SysDict, Integer> {
/* 旧方法(未按校过滤):仅作为无登录态上下文的兜底保留 */
List<SysDict> findByDictTypeOrderBySortOrderAsc(String dictType);
List<SysDict> findByDictTypeAndEnableFlagOrderBySortOrderAsc(String dictType, Integer enableFlag);
/** 按类型+key 取单条字典(发文部门名称解析用) */
Optional<SysDict> findByDictTypeAndDictKey(String dictType, String dictKey);
/* 按校过滤(多租户隔离):字典业务主链路使用 */
List<SysDict> findBySchIdAndDictTypeOrderBySortOrderAsc(Integer schId, String dictType);
List<SysDict> findBySchIdAndDictTypeAndEnableFlagOrderBySortOrderAsc(Integer schId, String dictType, Integer enableFlag);
/** 按校+类型+key 取单条字典(发文部门名称解析用) */
Optional<SysDict> findBySchIdAndDictTypeAndDictKey(Integer schId, String dictType, String dictKey);
}
@@ -21,6 +21,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.stream.Collectors;
@@ -74,7 +75,7 @@ public class DictService implements IDictService {
if (dictType == null) {
throw new BizException(ErrorCode.PARAM_ERROR, "参数错误");
}
List<SysDict> list = sysDictRepository.findByDictTypeAndEnableFlagOrderBySortOrderAsc(dictType, 1);
List<SysDict> list = currentSchoolDict(dictType, 1);
if (list.isEmpty()) {
throw new BizException(ErrorCode.FORBIDDEN, "尚未添加发文部门,请联系管理员添加!");
}
@@ -100,7 +101,7 @@ public class DictService implements IDictService {
// 非 DEPT 类型需超管权限,本系统暂只支持 DEPT
throw new BizException(ErrorCode.FORBIDDEN, "非超管不得操作!");
}
List<SysDict> list = sysDictRepository.findByDictTypeOrderBySortOrderAsc(dictType);
List<SysDict> list = currentSchoolDict(dictType, null);
return list.stream()
.sorted(Comparator.comparingInt(d -> d.getSortOrder() == null ? 999 : d.getSortOrder()))
.map(d -> {
@@ -123,21 +124,23 @@ public class DictService implements IDictService {
if (!StringUtils.hasText(name)) {
throw new BizException(ErrorCode.PARAM_ERROR, "输入字符串格式不正确!");
}
// 校验重名
List<SysDict> existing = sysDictRepository.findByDictTypeOrderBySortOrderAsc(DICT_TYPE_DEPT);
Integer schId = currentSchId();
// 校验重名(本校范围)
List<SysDict> existing = currentSchoolDict(DICT_TYPE_DEPT, null);
boolean duplicate = existing.stream().anyMatch(d ->
DICT_TYPE_DEPT.equals(d.getDictType()) && name.equals(d.getDictValue()) && d.getEnableFlag() != 3);
if (duplicate) {
throw new BizException(ErrorCode.FORBIDDEN, "已存在该分类,请重新填写!");
}
// 计算 sortOrder = max + 1
// 计算 sortOrder = max + 1(本校范围)
int maxSort = existing.stream()
.filter(d -> d.getEnableFlag() != 3)
.mapToInt(d -> d.getSortOrder() != null ? d.getSortOrder() : 0)
.max().orElse(0);
SysDict dict = new SysDict();
dict.setSchId(schId);
dict.setDictType(DICT_TYPE_DEPT);
dict.setDictValue(name);
dict.setSortOrder(maxSort + 1);
@@ -154,16 +157,16 @@ public class DictService implements IDictService {
if (serID == null) {
throw new BizException(ErrorCode.PARAM_ERROR, "参数错误!");
}
// 校验重名(排除自身)
List<SysDict> existing = sysDictRepository.findByDictTypeOrderBySortOrderAsc(DICT_TYPE_DEPT);
Integer schId = currentSchId();
SysDict dict = requireOwnDict(schId, serID);
// 校验重名(本校范围,排除自身)
List<SysDict> existing = currentSchoolDict(DICT_TYPE_DEPT, null);
boolean duplicate = existing.stream().anyMatch(d ->
!d.getId().equals(serID) && name.equals(d.getDictValue()) && d.getEnableFlag() != 3);
!d.getId().equals(serID) && name != null && name.equals(d.getDictValue()) && d.getEnableFlag() != 3);
if (duplicate) {
throw new BizException(ErrorCode.FORBIDDEN, "已存在该分类,请重新填写!");
}
SysDict dict = sysDictRepository.findById(serID)
.orElseThrow(() -> new BizException(ErrorCode.FORBIDDEN, "字典记录不存在"));
if (StringUtils.hasText(name)) {
dict.setDictValue(name);
}
@@ -178,13 +181,19 @@ public class DictService implements IDictService {
@Override
@Transactional
public void delDept(Integer serID) {
SysDict dict = sysDictRepository.findById(serID)
.orElseThrow(() -> new BizException(ErrorCode.FORBIDDEN, "字典记录不存在"));
// 校验是否被通知引用(按 deptId = dictKey 匹配)
Integer schId = currentSchId();
SysDict dict = requireOwnDict(schId, serID);
// 校验是否被通知引用(本校范围,按 deptId = dictKey 匹配)
// C# 中检查 Notify_Message.DeptID == dict.CodeID
// Java 中 Notice.deptId 存的是 dictKey
List<Notice> referenced = noticeRepository.findAll((root, query, cb) ->
cb.equal(root.get("deptId"), dict.getDictKey()));
List<Notice> referenced = noticeRepository.findAll((root, query, cb) -> {
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(root.get("deptId"), dict.getDictKey()));
if (schId != null) {
predicates.add(cb.equal(root.get("schId"), schId));
}
return cb.and(predicates.toArray(new Predicate[0]));
});
if (!referenced.isEmpty()) {
throw new BizException(ErrorCode.FORBIDDEN, "已引用该部门,无法删除!");
}
@@ -199,7 +208,8 @@ public class DictService implements IDictService {
if (!StringUtils.hasText(ids)) {
throw new BizException(ErrorCode.PARAM_ERROR, "参数错误");
}
List<SysDict> list = sysDictRepository.findByDictTypeOrderBySortOrderAsc(DICT_TYPE_DEPT);
Integer schId = currentSchId();
List<SysDict> list = currentSchoolDict(DICT_TYPE_DEPT, null);
if (list.isEmpty()) {
throw new BizException(ErrorCode.FORBIDDEN, "字典类型错误,未找到该字典类型");
}
@@ -218,10 +228,12 @@ public class DictService implements IDictService {
// lambda 中不能修改局部变量,用数组包装
final int[] indexOrd = { maxSort };
// 逆序遍历,从最大序号递减
// 逆序遍历,从最大序号递减(仅本校记录参与排序,跨校 ID 跳过)
for (int i = idArr.length - 1; i >= 0; i--) {
int id = idArr[i];
sysDictRepository.findById(id).ifPresent(dict -> {
sysDictRepository.findById(id)
.filter(dict -> schId == null || schId.equals(dict.getSchId()))
.ifPresent(dict -> {
dict.setSortOrder(indexOrd[0]);
sysDictRepository.save(dict);
indexOrd[0]--;
@@ -245,17 +257,47 @@ public class DictService implements IDictService {
// ============================ 辅助方法 ============================
/**
* 取当前学校的字典列表(enableFlag 传 null 不过滤启用态)。
* 无学校身份时退回全表查询(对齐 Notice 多租户口径:schId 为空不过滤)。
*/
private List<SysDict> currentSchoolDict(String dictType, Integer enableFlag) {
Integer schId = currentSchId();
if (schId == null) {
return enableFlag == null
? sysDictRepository.findByDictTypeOrderBySortOrderAsc(dictType)
: sysDictRepository.findByDictTypeAndEnableFlagOrderBySortOrderAsc(dictType, enableFlag);
}
return enableFlag == null
? sysDictRepository.findBySchIdAndDictTypeOrderBySortOrderAsc(schId, dictType)
: sysDictRepository.findBySchIdAndDictTypeAndEnableFlagOrderBySortOrderAsc(schId, dictType, enableFlag);
}
/** 定位本校字典记录(跨校/存量未归属 sch_id 的记录一律视为不存在,存量回填见 sql/sys_dict_add_sch_id.sql) */
private SysDict requireOwnDict(Integer schId, Integer id) {
if (id == null) {
throw new BizException(ErrorCode.PARAM_ERROR, "参数错误");
}
return sysDictRepository.findById(id)
.filter(d -> schId != null && schId.equals(d.getSchId()))
.orElseThrow(() -> new BizException(ErrorCode.FORBIDDEN, "字典记录不存在"));
}
/**
* 按发文部门字典 key 解析部门名称(对应 C# GetDeptName)。
* 有学校身份时按校过滤(各校 dict_key 可能重名),无登录态时退回全表兜底。
*/
@Override
public String resolveDeptName(String deptId) {
if (!StringUtils.hasText(deptId)) {
return null;
}
return sysDictRepository.findByDictTypeAndDictKey(DICT_TYPE_DEPT, deptId.trim())
.map(SysDict::getDictValue)
.orElse(null);
String key = deptId.trim();
Integer schId = currentSchId();
Optional<SysDict> dict = schId != null
? sysDictRepository.findBySchIdAndDictTypeAndDictKey(schId, DICT_TYPE_DEPT, key)
: sysDictRepository.findByDictTypeAndDictKey(DICT_TYPE_DEPT, key);
return dict.map(SysDict::getDictValue).orElse(null);
}
/**