fix: 优化钉钉部门匹配逻辑,优先匹配子部门

This commit is contained in:
Your Name 2026-01-07 10:40:44 +08:00
parent 11c9fcc7e6
commit eab4b6ba2a

View File

@ -1317,15 +1317,44 @@ public class UserService {
}
}
// 2. 通过部门名称模糊匹配
// 2. 优先通过部门名称完全相等匹配
if (matched == null && dingDeptName != null) {
matched = systemDepts.stream()
.filter(d -> d.getDeptName().contains(dingDeptName) ||
dingDeptName.contains(d.getDeptName()))
.filter(d -> d.getDeptName().equals(dingDeptName))
.findFirst()
.orElse(null);
if (matched != null) {
log.info("通过部门名称模糊匹配: {} -> {}", dingDeptName, matched.getDeptName());
log.info("通过部门名称精确匹配: {} -> {}", dingDeptName, matched.getDeptName());
}
}
// 3. 通过部门名称模糊匹配,优先选择层级更深的部门(有parentId的)
if (matched == null && dingDeptName != null) {
List<Department> fuzzyMatched = systemDepts.stream()
.filter(d -> d.getDeptName().contains(dingDeptName) ||
dingDeptName.contains(d.getDeptName()))
.collect(Collectors.toList());
if (!fuzzyMatched.isEmpty()) {
// 优先选择层级更深的部门(有parentId的优先,然后按名称相似度排序)
matched = fuzzyMatched.stream()
.sorted((a, b) -> {
// 1. 优先选择有parentId的(子部门)
int levelCompare = Boolean.compare(a.getParentId() == null, b.getParentId() == null);
if (levelCompare != 0) return levelCompare;
// 2. 如果都有或都没有parentId,按名称长度差异排序(越接近越好)
int diffA = Math.abs(a.getDeptName().length() - dingDeptName.length());
int diffB = Math.abs(b.getDeptName().length() - dingDeptName.length());
return Integer.compare(diffA, diffB);
})
.findFirst()
.orElse(null);
if (matched != null) {
log.info("通过部门名称模糊匹配: {} -> {} (候选数: {})",
dingDeptName, matched.getDeptName(), fuzzyMatched.size());
}
}
}
@ -1334,6 +1363,18 @@ public class UserService {
}
}
// 对匹配结果进行排序:优先返回层级更深的部门
if (matchedDeptIds.size() > 1) {
matchedDeptIds.sort((id1, id2) -> {
Department d1 = systemDepts.stream().filter(d -> d.getId().equals(id1)).findFirst().orElse(null);
Department d2 = systemDepts.stream().filter(d -> d.getId().equals(id2)).findFirst().orElse(null);
if (d1 == null || d2 == null) return 0;
// 有parentId的排前面
return Boolean.compare(d1.getParentId() == null, d2.getParentId() == null);
});
log.info("部门匹配结果排序后(优先子部门): {}", matchedDeptIds);
}
return matchedDeptIds;
}