You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

203 lines
8.4 KiB
Java

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.sztzjy.blockchainsmartclaim.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sztzjy.blockchainsmartclaim.entity.scenario.ScenarioGroup;
import com.sztzjy.blockchainsmartclaim.entity.scenario.ScenarioGroupMember;
import com.sztzjy.blockchainsmartclaim.mapper.ScenarioGroupMapper;
import com.sztzjy.blockchainsmartclaim.mapper.ScenarioGroupMemberMapper;
import com.sztzjy.blockchainsmartclaim.service.ScenarioGroupProvisionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* 一用户全角色开通逻辑。隔离键仍是 group_id:一个账号一个小组,
* 小组内该账号同时持有全部业务角色(scenario_group_member 一角色一行)。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class ScenarioGroupProvisionServiceImpl implements ScenarioGroupProvisionService {
private final ScenarioGroupMapper scenarioGroupMapper;
private final ScenarioGroupMemberMapper scenarioGroupMemberMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public String ensureUserScenarioGroup(String userId, String displayName) {
if (!StringUtils.hasText(userId)) {
return null;
}
Map<String, Set<String>> rolesByGroup = loadRolesByGroup(userId);
for (Map.Entry<String, Set<String>> entry : rolesByGroup.entrySet()) {
if (entry.getValue().containsAll(ALL_SCENARIO_ROLES)) {
return entry.getKey();
}
}
String groupId = resolveProvisionTarget(userId, rolesByGroup);
if (groupId == null) {
groupId = createPersonalGroup(userId, displayName).getId();
}
// 新建组与复用组统一补齐:新建组无持有记录,此处写入全部角色。
topUpMissingRoles(groupId, userId, rolesByGroup.get(groupId));
removeMembershipFromOtherGroups(userId, groupId, rolesByGroup);
refreshGroupStatus(groupId);
return groupId;
}
@Override
public List<String> currentUserRoleCodes(String userId) {
if (!StringUtils.hasText(userId)) {
return new ArrayList<>();
}
Set<String> roleCodes = new LinkedHashSet<>();
for (ScenarioGroupMember member : listMembersByUser(userId)) {
if (StringUtils.hasText(member.getRoleCode())) {
roleCodes.add(member.getRoleCode());
}
}
return new ArrayList<>(roleCodes);
}
/**
* 目标小组优先级:账号已独占的小组(补齐缺失角色)&gt; 新建专属小组。
* 与他人共用的小组不补角色,避免与组内其他账号争抢角色唯一键。
*/
private String resolveProvisionTarget(String userId, Map<String, Set<String>> rolesByGroup) {
if (rolesByGroup.size() != 1) {
return null;
}
String groupId = rolesByGroup.keySet().iterator().next();
long otherMembers = scenarioGroupMemberMapper.selectCount(new LambdaQueryWrapper<ScenarioGroupMember>()
.eq(ScenarioGroupMember::getGroupId, groupId)
.ne(ScenarioGroupMember::getUserId, userId));
return otherMembers == 0 ? groupId : null;
}
private void topUpMissingRoles(String groupId, String userId, Set<String> heldRoles) {
for (String roleCode : ALL_SCENARIO_ROLES) {
if (heldRoles != null && heldRoles.contains(roleCode)) {
continue;
}
insertMember(groupId, userId, roleCode);
}
}
private ScenarioGroup createPersonalGroup(String userId, String displayName) {
String groupName = StringUtils.hasText(displayName) ? displayName.trim() : userId;
String groupCode = normalizeGroupCode(groupName, userId);
ScenarioGroup group = new ScenarioGroup();
group.setGroupName(truncate(groupName, 128));
group.setGroupCode(groupCode);
group.setStatus("DRAFT");
group.setCreatorUserId(userId);
group.setCreateTime(new Date());
group.setUpdateTime(new Date());
try {
scenarioGroupMapper.insert(group);
} catch (DataIntegrityViolationException e) {
// 并发登录或历史同名小组导致 group_code 冲突:回查复用,仍冲突则追加用户号后缀重建。
ScenarioGroup existing = scenarioGroupMapper.selectOne(new LambdaQueryWrapper<ScenarioGroup>()
.eq(ScenarioGroup::getGroupCode, groupCode)
.last("limit 1"));
if (existing != null) {
return existing;
}
group.setGroupCode(truncate(groupCode, 48) + "-" + userId.substring(0, Math.min(8, userId.length())).toUpperCase(Locale.ROOT));
group.setId(null);
scenarioGroupMapper.insert(group);
}
return group;
}
private void removeMembershipFromOtherGroups(String userId, String keepGroupId, Map<String, Set<String>> rolesByGroup) {
List<String> staleGroupIds = new ArrayList<>();
for (String groupId : rolesByGroup.keySet()) {
if (!groupId.equals(keepGroupId)) {
staleGroupIds.add(groupId);
}
}
if (staleGroupIds.isEmpty()) {
return;
}
scenarioGroupMemberMapper.delete(new LambdaQueryWrapper<ScenarioGroupMember>()
.eq(ScenarioGroupMember::getUserId, userId)
.in(ScenarioGroupMember::getGroupId, staleGroupIds));
staleGroupIds.forEach(this::refreshGroupStatus);
}
private void refreshGroupStatus(String groupId) {
ScenarioGroup group = scenarioGroupMapper.selectById(groupId);
if (group == null) {
return;
}
Set<String> roleCodes = new LinkedHashSet<>();
for (ScenarioGroupMember member : scenarioGroupMemberMapper.selectList(new LambdaQueryWrapper<ScenarioGroupMember>()
.eq(ScenarioGroupMember::getGroupId, groupId))) {
if (StringUtils.hasText(member.getRoleCode())) {
roleCodes.add(member.getRoleCode());
}
}
group.setStatus(roleCodes.size() == ALL_SCENARIO_ROLES.size() && roleCodes.containsAll(ALL_SCENARIO_ROLES)
? "ACTIVE" : "DRAFT");
group.setUpdateTime(new Date());
scenarioGroupMapper.updateById(group);
}
private void insertMember(String groupId, String userId, String roleCode) {
ScenarioGroupMember member = new ScenarioGroupMember();
member.setGroupId(groupId);
member.setUserId(userId);
member.setRoleCode(roleCode);
// 冲突和写入失败必须向外抛出,避免事务提交不完整的角色集合。
scenarioGroupMemberMapper.insert(member);
}
private Map<String, Set<String>> loadRolesByGroup(String userId) {
Map<String, Set<String>> rolesByGroup = new LinkedHashMap<>();
for (ScenarioGroupMember member : listMembersByUser(userId)) {
if (!StringUtils.hasText(member.getGroupId())) {
continue;
}
rolesByGroup.computeIfAbsent(member.getGroupId(), key -> new LinkedHashSet<>());
if (StringUtils.hasText(member.getRoleCode())) {
rolesByGroup.get(member.getGroupId()).add(member.getRoleCode());
}
}
return rolesByGroup;
}
private List<ScenarioGroupMember> listMembersByUser(String userId) {
return scenarioGroupMemberMapper.selectList(new LambdaQueryWrapper<ScenarioGroupMember>()
.eq(ScenarioGroupMember::getUserId, userId));
}
private String normalizeGroupCode(String groupName, String userId) {
String code = groupName.replaceAll("\\s+", "");
if (!StringUtils.hasText(code)) {
code = userId;
}
return truncate(code, 64);
}
private String truncate(String value, int maxLength) {
if (value == null) {
return null;
}
return value.length() <= maxLength ? value : value.substring(0, maxLength);
}
}