Revert "支持角色父子继承,允许子角色单独调整自己有的权限"

This commit is contained in:
陈博文
2025-06-23 09:35:03 +08:00
parent 6b4979dab0
commit 40863d00d2
19 changed files with 21 additions and 700 deletions

View File

@@ -1,32 +0,0 @@
-- 用户-租户关系表
create table "RUOYI-VUE-PRO".SYSTEM_USER_TENANT
(
ID BIGINT not null,
USER_ID BIGINT not null,
TENANT_ID BIGINT not null,
CREATOR VARCHAR(256) default '',
CREATE_TIME TIMESTAMP default CURRENT_TIMESTAMP not null,
UPDATER VARCHAR(256) default '',
UPDATE_TIME TIMESTAMP default CURRENT_TIMESTAMP not null,
DELETED TINYINT default 0 not null
);
comment on table "RUOYI-VUE-PRO".SYSTEM_USER_TENANT is '用户-租户关系表';
comment on column "RUOYI-VUE-PRO".SYSTEM_USER_TENANT.ID is '主键ID';
comment on column "RUOYI-VUE-PRO".SYSTEM_USER_TENANT.USER_ID is '用户ID';
comment on column "RUOYI-VUE-PRO".SYSTEM_USER_TENANT.TENANT_ID is '租户ID';
comment on column "RUOYI-VUE-PRO".SYSTEM_USER_TENANT.CREATOR is '创建者';
comment on column "RUOYI-VUE-PRO".SYSTEM_USER_TENANT.CREATE_TIME is '创建时间';
comment on column "RUOYI-VUE-PRO".SYSTEM_USER_TENANT.UPDATER is '更新者';
comment on column "RUOYI-VUE-PRO".SYSTEM_USER_TENANT.UPDATE_TIME is '更新时间';
comment on column "RUOYI-VUE-PRO".SYSTEM_USER_TENANT.DELETED is '是否删除';
create unique index "RUOYI-VUE-PRO".IDX_SYSTEM_USER_TENANT_ID
on "RUOYI-VUE-PRO".SYSTEM_USER_TENANT (ID);
create unique index "RUOYI-VUE-PRO".IDX_SYSTEM_USER_TENANT_UNIQUE
on "RUOYI-VUE-PRO".SYSTEM_USER_TENANT (USER_ID, TENANT_ID);
alter table "RUOYI-VUE-PRO".SYSTEM_USER_TENANT
add constraint PK_SYSTEM_USER_TENANT_ID
primary key (ID);

View File

@@ -1,6 +0,0 @@
alter table "RUOYI-VUE-PRO".SYSTEM_DEPT
add IS_TENANT TINYINT default false not null;
comment
on column "RUOYI-VUE-PRO".SYSTEM_DEPT.IS_TENANT is '组织机构是否为租户';

View File

@@ -34,3 +34,6 @@ alter table "RUOYI-VUE-PRO".SYSTEM_ROLE_MENU_EXCLUSION
alter table "RUOYI-VUE-PRO".SYSTEM_ROLE
add PARENT_ID BIGINT default 0 not null;
alter table "RUOYI-VUE-PRO".SYSTEM_ROLE
add PARENT_ID BIGINT default 0 not null;

View File

@@ -8,6 +8,9 @@ import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
/**
* @author chenbowen
*/
@Schema(description = "管理后台 - 登录 Response VO")
@Data
@NoArgsConstructor
@@ -27,4 +30,6 @@ public class AuthLoginRespVO {
@Schema(description = "过期时间", requiredMode = Schema.RequiredMode.REQUIRED)
private LocalDateTime expiresTime;
@Schema(description = "租户编号", requiredMode = Schema.RequiredMode.REQUIRED)
private Long tenantId;
}

View File

@@ -39,9 +39,6 @@ public class DeptRespVO {
@Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED, example = "时间戳格式")
private LocalDateTime createTime;
@Schema(description = "组织机构是否租户", example = "true")
private Boolean isTenant = false;
@Schema(description = "租户编号", example = "1024")
private Long tenantId;

View File

@@ -48,9 +48,6 @@ public class DeptSaveReqVO {
@InEnum(value = CommonStatusEnum.class, message = "修改状态必须是 {value}")
private Integer status;
@Schema(description = "组织机构是否租户", example = "true")
private Boolean isTenant = false;
@Schema(description = "租户编号", example = "1024")
private Long tenantId;

View File

@@ -10,6 +10,11 @@ import cn.iocoder.yudao.module.system.service.tenant.TenantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Set;

View File

@@ -1,160 +0,0 @@
package cn.iocoder.yudao.module.system.controller.admin.usertenant;
import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantRespVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserSimpleRespVO;
import cn.iocoder.yudao.module.system.controller.admin.usertenant.vo.UserTenantPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.usertenant.vo.UserTenantRespVO;
import cn.iocoder.yudao.module.system.controller.admin.usertenant.vo.UserTenantSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.usertenant.UserTenantDO;
import cn.iocoder.yudao.module.system.service.usertenant.UserTenantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
/**
* @author chenbowen
*/
@Tag(name = "管理后台 - 用户-租户关系")
@RestController
@RequestMapping("/system/user-tenant")
@Validated
public class UserTenantController {
@Resource
private UserTenantService userTenantService;
@PostMapping("/create")
@Operation(summary = "创建用户-租户关系")
@PreAuthorize("@ss.hasPermission('system:user-tenant:create')")
public CommonResult<Long> createUserTenant(@Valid @RequestBody UserTenantSaveReqVO createReqVO) {
return success(userTenantService.createUserTenant(createReqVO));
}
@PutMapping("/update")
@Operation(summary = "更新用户-租户关系")
@PreAuthorize("@ss.hasPermission('system:user-tenant:update')")
public CommonResult<Boolean> updateUserTenant(@Valid @RequestBody UserTenantSaveReqVO updateReqVO) {
userTenantService.updateUserTenant(updateReqVO);
return success(true);
}
@DeleteMapping("/delete")
@Operation(summary = "删除用户-租户关系")
@Parameter(name = "id", description = "编号", required = true)
@PreAuthorize("@ss.hasPermission('system:user-tenant:delete')")
public CommonResult<Boolean> deleteUserTenant(@RequestParam("id") Long id) {
userTenantService.deleteUserTenant(id);
return success(true);
}
@DeleteMapping("/delete-list")
@Parameter(name = "ids", description = "编号", required = true)
@Operation(summary = "批量删除用户-租户关系")
@PreAuthorize("@ss.hasPermission('system:user-tenant:delete')")
public CommonResult<Boolean> deleteUserTenantList(@RequestParam("ids") List<Long> ids) {
userTenantService.deleteUserTenantListByIds(ids);
return success(true);
}
@GetMapping("/get")
@Operation(summary = "获得用户-租户关系")
@Parameter(name = "id", description = "编号", required = true, example = "1024")
@PreAuthorize("@ss.hasPermission('system:user-tenant:query')")
public CommonResult<UserTenantRespVO> getUserTenant(@RequestParam("id") Long id) {
UserTenantDO userTenant = userTenantService.getUserTenant(id);
return success(BeanUtils.toBean(userTenant, UserTenantRespVO.class));
}
@GetMapping("/page")
@Operation(summary = "获得用户-租户关系分页")
@PreAuthorize("@ss.hasPermission('system:user-tenant:query')")
public CommonResult<PageResult<UserTenantRespVO>> getUserTenantPage(@Valid UserTenantPageReqVO pageReqVO) {
PageResult<UserTenantDO> pageResult = userTenantService.getUserTenantPage(pageReqVO);
return success(BeanUtils.toBean(pageResult, UserTenantRespVO.class));
}
/**
* 用户租户关系 simpleList 查询接口
*/
@GetMapping("/user-tenant-simple-list")
@Operation(summary = "获得用户-租户关系 simpleList 列表")
public CommonResult<List<UserTenantRespVO>> getUserTenantSimpleList(@Valid UserTenantPageReqVO pageReqVO) {
List<UserTenantDO> list = userTenantService.getUserTenantList(pageReqVO);
// 追加当前用户归属的租户信息
if (CollUtil.isNotEmpty(list)) {
list.add(new UserTenantDO()
.setUserId(getLoginUserId())
.setTenantId(TenantContextHolder.getTenantId()));
}
return success(BeanUtils.toBean(list, UserTenantRespVO.class));
}
@GetMapping("/export-excel")
@Operation(summary = "导出用户-租户关系 Excel")
@PreAuthorize("@ss.hasPermission('system:user-tenant:export')")
@ApiAccessLog(operateType = EXPORT)
public void exportUserTenantExcel(@Valid UserTenantPageReqVO pageReqVO,
HttpServletResponse response) throws IOException {
pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
List<UserTenantDO> list = userTenantService.getUserTenantPage(pageReqVO).getList();
// 导出 Excel
ExcelUtils.write(response, "用户-租户关系.xls", "数据", UserTenantRespVO.class,
BeanUtils.toBean(list, UserTenantRespVO.class));
}
/**
* 用户 simpleList 查询接口
*/
@GetMapping("/user-simple-list")
@Operation(summary = "获得用户 simpleList 列表")
// 不使用默认的租户查询方式,此处需要获取租户以及下属租户的相关数据,在 mapper 自行实现
@TenantIgnore
public CommonResult<List<UserSimpleRespVO>> getUserSimpleList() {
return success(userTenantService.getUserBelongSimpleList());
}
/**
* 租户 simpleList 查询接口
*/
@GetMapping("/tenant-simple-list")
@Operation(summary = "获得租户 simpleList 列表")
// 不使用默认的租户查询方式,此处需要获取租户以及下属租户的相关数据,在 mapper 自行实现
@TenantIgnore
public CommonResult<List<TenantRespVO>> getTenantSimpleList() {
return success(userTenantService.getTenantBelongSimpleList());
}
/**
* 未关联组织机构租户 simpleList 查询接口
*/
@GetMapping("/independent-tenant-simple-list")
@Operation(summary = "获得租户 simpleList 列表")
// 不使用默认的租户查询方式,此处需要获取租户以及下属租户的相关数据,在 mapper 自行实现
@TenantIgnore
public CommonResult<List<TenantRespVO>> getIndependentTenantSimpleList() {
return success(userTenantService.getIndependentTenantSimpleList());
}
}

View File

@@ -1,26 +0,0 @@
package cn.iocoder.yudao.module.system.controller.admin.usertenant.vo;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
@Schema(description = "管理后台 - 用户-租户关系分页 Request VO")
@Data
public class UserTenantPageReqVO extends PageParam {
@Schema(description = "用户ID", example = "32426")
private Long userId;
@Schema(description = "租户ID", example = "30027")
private Long tenantId;
@Schema(description = "创建时间")
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
private LocalDateTime[] createTime;
}

View File

@@ -1,27 +0,0 @@
package cn.iocoder.yudao.module.system.controller.admin.usertenant.vo;
import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;
import com.alibaba.excel.annotation.ExcelProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
@Schema(description = "管理后台 - 用户-租户关系 Response VO")
@Data
@ExcelIgnoreUnannotated
public class UserTenantRespVO {
@Schema(description = "主键ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "26967")
@ExcelProperty("主键ID")
private Long id;
@Schema(description = "用户ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "32426")
@ExcelProperty("用户ID")
private Long userId;
@Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED)
@ExcelProperty("创建时间")
private LocalDateTime createTime;
}

View File

@@ -1,22 +0,0 @@
package cn.iocoder.yudao.module.system.controller.admin.usertenant.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
@Schema(description = "管理后台 - 用户-租户关系新增/修改 Request VO")
@Data
public class UserTenantSaveReqVO {
@Schema(description = "主键ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "26967")
private Long id;
@Schema(description = "用户ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "32426")
@NotNull(message = "用户ID不能为空")
private Long userId;
@Schema(description = "租户ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "30027")
@NotNull(message = "租户ID不能为空")
private Long tenantId;
}

View File

@@ -62,10 +62,5 @@ public class DeptDO extends TenantBaseDO {
* 枚举 {@link CommonStatusEnum}
*/
private Integer status;
/**
* 组织机构是否为租户
*/
private Boolean isTenant;
}

View File

@@ -40,14 +40,12 @@ public interface DeptMapper extends BaseMapperX<DeptDO> {
default DeptDO selectByTenantIdAndIsTenant(Long tenantId) {
return selectOne(new LambdaQueryWrapperX<DeptDO>()
.eq(DeptDO::getTenantId, tenantId)
.eq(DeptDO::getIsTenant, true));
.eq(DeptDO::getTenantId, tenantId));
}
default DeptDO selectByTenantIdAndIsTenantExcludeId(Long tenantId, Long excludeId) {
return selectOne(new LambdaQueryWrapperX<DeptDO>()
.eq(DeptDO::getTenantId, tenantId)
.eq(DeptDO::getIsTenant, true)
.ne(DeptDO::getId, excludeId));
}

View File

@@ -1,26 +0,0 @@
package cn.iocoder.yudao.module.system.dal.mysql.usertenant;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.controller.admin.usertenant.vo.UserTenantPageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.usertenant.UserTenantDO;
import org.apache.ibatis.annotations.Mapper;
/**
* 用户-租户关系 Mapper
*
* @author 管理员
*/
@Mapper
public interface UserTenantMapper extends BaseMapperX<UserTenantDO> {
default PageResult<UserTenantDO> selectPage(UserTenantPageReqVO reqVO) {
return selectPage(reqVO, new LambdaQueryWrapperX<UserTenantDO>()
.eqIfPresent(UserTenantDO::getUserId, reqVO.getUserId())
.eqIfPresent(UserTenantDO::getTenantId, reqVO.getTenantId())
.betweenIfPresent(UserTenantDO::getCreateTime, reqVO.getCreateTime())
.orderByDesc(UserTenantDO::getId));
}
}

View File

@@ -49,20 +49,9 @@ public class DeptServiceImpl implements DeptService {
// 校验部门名的唯一性
validateDeptNameUnique(null, createReqVO.getParentId(), createReqVO.getName());
// 新建为主体公司时,校验租户唯一性(一个租户只能关联一个组织机构)
if (Boolean.TRUE.equals(createReqVO.getIsTenant())) {
DeptDO exist = deptMapper.selectByTenantIdAndIsTenant(createReqVO.getTenantId());
if (exist != null) {
throw exception(DEPT_TENANT_RELATION_EXISTS);
}
}
// 插入部门
DeptDO dept = BeanUtils.toBean(createReqVO, DeptDO.class);
if (Boolean.TRUE.equals(createReqVO.getIsTenant())) {
dept.setTenantId(createReqVO.getTenantId());
}
deptMapper.insert(dept);
return dept.getId();
}
@@ -80,33 +69,7 @@ public class DeptServiceImpl implements DeptService {
// 校验部门名的唯一性
validateDeptNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getName());
DeptDO oldDept = deptMapper.selectById(updateReqVO.getId());
boolean oldIsTenant = oldDept.getIsTenant();
boolean newIsTenant = updateReqVO.getIsTenant();
if (newIsTenant) {
// 1. 校验租户唯一性
DeptDO exist = deptMapper.selectByTenantIdAndIsTenantExcludeId(updateReqVO.getTenantId(), updateReqVO.getId());
if (exist != null) {
throw exception(DEPT_TENANT_RELATION_EXISTS);
}
// 2. 设置当前组织租户Id
oldDept.setTenantId(updateReqVO.getTenantId());
// 3. 递归设置所有下属非主体公司组织的租户Id为当前租户Id
updateChildrenTenantId(updateReqVO.getId(), updateReqVO.getTenantId());
} else if (oldIsTenant) {
// 获取父级组织机构的租户Id
Long parentTenantId = null;
if (oldDept.getParentId() != null && !DeptDO.PARENT_ID_ROOT.equals(oldDept.getParentId())) {
DeptDO parentDept = deptMapper.selectById(oldDept.getParentId());
if (parentDept != null) {
parentTenantId = parentDept.getTenantId();
}
}
// 递归设置所有下属非主体公司组织的租户Id为父级组织机构的租户Id
updateChildrenTenantId(updateReqVO.getId(), parentTenantId);
}
// 更新部门
DeptDO updateObj = BeanUtils.toBean(updateReqVO, DeptDO.class);
deptMapper.updateById(updateObj);
}
@@ -121,8 +84,7 @@ public class DeptServiceImpl implements DeptService {
if (deptMapper.selectCountByParentId(id) > 0) {
throw exception(DEPT_EXITS_CHILDREN);
}
DeptDO dept = deptMapper.selectById(id);
// 删除为主体公司时无需处理关系表,仅常规删除
// 删除部门
deptMapper.deleteById(id);
}
@@ -258,32 +220,4 @@ public class DeptServiceImpl implements DeptService {
});
}
/**
* 递归设置指定组织及其所有下属非主体公司组织的租户Id批量更新。
* 跳过所有租户组织及其下属组织(不包含自身)。
*/
private void updateChildrenTenantId(Long parentId, Long tenantId) {
List<Long> updateIds = new ArrayList<>();
Queue<DeptDO> queue = new LinkedList<>();
List<DeptDO> children = deptMapper.selectListByParentId(Collections.singleton(parentId));
if (children != null && !children.isEmpty()) {
queue.addAll(children);
}
while (!queue.isEmpty()) {
DeptDO current = queue.poll();
if (current.getIsTenant() != null && current.getIsTenant()) {
// 跳过当前租户组织及其所有下属
continue;
}
updateIds.add(current.getId());
List<DeptDO> subChildren = deptMapper.selectListByParentId(Collections.singleton(current.getId()));
if (subChildren != null && !subChildren.isEmpty()) {
queue.addAll(subChildren);
}
}
if (!updateIds.isEmpty()) {
deptMapper.updateTenantIdBatch(updateIds, tenantId);
}
}
}

View File

@@ -161,7 +161,7 @@ public class OAuth2TokenServiceImpl implements OAuth2TokenService {
Map<String, String> userInfo = buildUserInfo(refreshTokenDO.getUserId(), refreshTokenDO.getUserType());
OAuth2AccessTokenDO accessTokenDO = new OAuth2AccessTokenDO().setAccessToken(generateAccessToken())
.setUserId(refreshTokenDO.getUserId()).setUserType(refreshTokenDO.getUserType())
.setUserInfo(userInfo)
.setUserInfo(buildUserInfo(refreshTokenDO.getUserId(), refreshTokenDO.getUserType()))
.setClientId(clientDO.getClientId()).setScopes(refreshTokenDO.getScopes())
.setRefreshToken(refreshTokenDO.getRefreshToken())
.setExpiresTime(LocalDateTime.now().plusSeconds(clientDO.getAccessTokenValiditySeconds()));

View File

@@ -1,90 +0,0 @@
package cn.iocoder.yudao.module.system.service.usertenant;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantRespVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserSimpleRespVO;
import cn.iocoder.yudao.module.system.controller.admin.usertenant.vo.UserTenantPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.usertenant.vo.UserTenantSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.usertenant.UserTenantDO;
import jakarta.validation.Valid;
import java.util.List;
/**
* 用户-租户关系 Service 接口
*
* @author 管理员
*/
public interface UserTenantService {
/**
* 创建用户-租户关系
*
* @param createReqVO 创建信息
* @return 编号
*/
Long createUserTenant(@Valid UserTenantSaveReqVO createReqVO);
/**
* 更新用户-租户关系
*
* @param updateReqVO 更新信息
*/
void updateUserTenant(@Valid UserTenantSaveReqVO updateReqVO);
/**
* 删除用户-租户关系
*
* @param id 编号
*/
void deleteUserTenant(Long id);
/**
* 批量删除用户-租户关系
*
* @param ids 编号
*/
void deleteUserTenantListByIds(List<Long> ids);
/**
* 获得用户-租户关系
*
* @param id 编号
* @return 用户-租户关系
*/
UserTenantDO getUserTenant(Long id);
/**
* 获得用户-租户关系分页
*
* @param pageReqVO 分页查询
* @return 用户-租户关系分页
*/
PageResult<UserTenantDO> getUserTenantPage(UserTenantPageReqVO pageReqVO);
/**
* 获得用户-租户关系列表
*
* @param pageReqVO 列表查询
* @return 用户-租户关系列表
*/
List<UserTenantDO> getUserTenantList(UserTenantPageReqVO pageReqVO);
/**
* 获得用户 simpleList 列表 !!!注意,此方法查询的用户列表,包含了租户下属租户的所有用户
* @return 用户列表(只含 id、nickname
*/
List<UserSimpleRespVO> getUserBelongSimpleList();
/**
* 获得租户 simpleList 列表
* @return 租户列表(只含 id、name
*/
List<TenantRespVO> getTenantBelongSimpleList();
/**
* 未关联组织机构租户 simpleList 查询接口 列表
* @return 租户列表(只含 id、name
*/
List<TenantRespVO> getIndependentTenantSimpleList();
}

View File

@@ -1,224 +0,0 @@
package cn.iocoder.yudao.module.system.service.usertenant;
import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantRespVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserSimpleRespVO;
import cn.iocoder.yudao.module.system.controller.admin.usertenant.vo.UserTenantPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.usertenant.vo.UserTenantSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.dataobject.usertenant.UserTenantDO;
import cn.iocoder.yudao.module.system.dal.mysql.dept.DeptMapper;
import cn.iocoder.yudao.module.system.dal.mysql.tenant.TenantMapper;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import cn.iocoder.yudao.module.system.dal.mysql.usertenant.UserTenantMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import java.util.*;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
/**
* 用户-租户关系 Service 实现类
*
* @author 管理员
*/
@Service
@Validated
public class UserTenantServiceImpl implements UserTenantService {
@Resource
private UserTenantMapper userTenantMapper;
@Resource
private AdminUserMapper adminUserMapper;
@Resource
private TenantMapper tenantMapper;
@Resource
private DeptMapper deptMapper;
@Override
public Long createUserTenant(UserTenantSaveReqVO createReqVO) {
// 插入
UserTenantDO userTenant = BeanUtils.toBean(createReqVO, UserTenantDO.class);
userTenantMapper.insert(userTenant);
// 返回
return userTenant.getId();
}
@Override
public void updateUserTenant(UserTenantSaveReqVO updateReqVO) {
// 校验存在
validateUserTenantExists(updateReqVO.getId());
// 更新
UserTenantDO updateObj = BeanUtils.toBean(updateReqVO, UserTenantDO.class);
userTenantMapper.updateById(updateObj);
}
@Override
public void deleteUserTenant(Long id) {
// 校验存在
validateUserTenantExists(id);
// 删除
userTenantMapper.deleteById(id);
}
@Override
public void deleteUserTenantListByIds(List<Long> ids) {
// 校验存在
validateUserTenantExists(ids);
// 删除
userTenantMapper.deleteByIds(ids);
}
private void validateUserTenantExists(List<Long> ids) {
List<UserTenantDO> list = userTenantMapper.selectByIds(ids);
if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
throw exception(USER_TENANT_NOT_EXISTS);
}
}
private void validateUserTenantExists(Long id) {
if (userTenantMapper.selectById(id) == null) {
throw exception(USER_TENANT_NOT_EXISTS);
}
}
@Override
public UserTenantDO getUserTenant(Long id) {
return userTenantMapper.selectById(id);
}
@Override
public PageResult<UserTenantDO> getUserTenantPage(UserTenantPageReqVO pageReqVO) {
return userTenantMapper.selectPage(pageReqVO);
}
@Override
public List<UserTenantDO> getUserTenantList(UserTenantPageReqVO pageReqVO) {
return userTenantMapper.selectList(new LambdaQueryWrapper<UserTenantDO>()
.eq(pageReqVO.getUserId() != null, UserTenantDO::getUserId, pageReqVO.getUserId())
.eq(pageReqVO.getTenantId() != null, UserTenantDO::getTenantId, pageReqVO.getTenantId()));
}
/**
* 根据当前租户ID获取租户部门
*/
private DeptDO getTenantDeptOrThrow() {
LoginUser loginUser = getLoginUser();
if (loginUser == null) {
throw exception(USER_NOT_EXISTS);
}
Long tenantId = loginUser.getTenantId();
if (tenantId == null) {
throw exception(TENANT_NOT_EXISTS);
}
DeptDO deptDO = deptMapper.selectByTenantIdAndIsTenant(tenantId);
if (deptDO == null) {
throw exception(TENANT_NOT_EXISTS);
}
return deptDO;
}
/**
* 获取当前租户组织及其所有下属组织ID包含自身
*/
private List<Long> getTenantAndSubDeptIds(Long tenantDeptId) {
List<Long> deptIds = new ArrayList<>();
deptIds.add(tenantDeptId);
List<DeptDO> children = getAllSubDepts(tenantDeptId);
for (DeptDO child : children) {
deptIds.add(child.getId());
}
return deptIds;
}
/**
* 查询当前租户组织机构及其所有下属组织下的所有启用用户
*/
@Override
public List<UserSimpleRespVO> getUserBelongSimpleList() {
DeptDO tenantDept = getTenantDeptOrThrow();
List<Long> deptIds = getTenantAndSubDeptIds(tenantDept.getId());
// 查询这些组织下的所有用户
List<AdminUserDO> userList = adminUserMapper.selectListByDeptIds(deptIds);
List<UserSimpleRespVO> result = new ArrayList<>();
for (AdminUserDO user : userList) {
if (CommonStatusEnum.ENABLE.getStatus().equals(user.getStatus())) {
UserSimpleRespVO vo = new UserSimpleRespVO();
vo.setId(user.getId());
vo.setNickname(user.getNickname());
// vo.setUsername(user.getUsername());
result.add(vo);
}
}
return result;
}
/**
* 查询所有启用状态的组织机构(不限制 isTenant支持多层嵌套中间可有非租户组织
* 返回所有启用状态的组织及其 parentId便于前端递归组装树状结构。
*/
@Override
public List<TenantRespVO> getTenantBelongSimpleList() {
DeptDO tenantDept = getTenantDeptOrThrow();
List<DeptDO> children = getAllSubDepts(tenantDept.getId());
Set<Long> tenantIdsSets = convertSet(children, DeptDO::getTenantId, DeptDO::getIsTenant);
// 添加自身的租户ID
tenantIdsSets.add(tenantDept.getTenantId());
List<TenantDO> tenants = tenantMapper.selectByIds(tenantIdsSets);
return BeanUtils.toBean(tenants, TenantRespVO.class);
}
/**
* 未关联组织机构租户 simpleList 查询接口 列表
*
* @return 租户列表(只含 id、name
*/
@Override
public List<TenantRespVO> getIndependentTenantSimpleList() {
// 查询所有已关联组织的租户
List<DeptDO> bondDepts = deptMapper.selectList(DeptDO::getIsTenant, true);
Set<Long> tenantIdSet = convertSet(bondDepts,DeptDO::getTenantId);
// 查询 not in tenantIdSet 的租户信息
List<TenantDO> bondTenants = tenantMapper.selectList(new LambdaQueryWrapperX<TenantDO>().in(TenantDO::getId, tenantIdSet));
List<TenantDO> tenants = tenantMapper.selectList(new LambdaQueryWrapperX<TenantDO>().notIn(TenantDO::getId, tenantIdSet));
List<TenantRespVO> result = BeanUtils.toBean(tenants, TenantRespVO.class);
// 不可选择的下拉
List<TenantRespVO> notOptionalResult = BeanUtils.toBean(bondTenants, TenantRespVO.class);
notOptionalResult.forEach(notOptional -> notOptional.setOptional(false));
result.addAll(notOptionalResult);
return result;
}
/**
* 递归获取所有下属部门(不含自身)
*/
private List<DeptDO> getAllSubDepts(Long parentId) {
List<DeptDO> result = new ArrayList<>();
Queue<Long> queue = new LinkedList<>();
queue.add(parentId);
while (!queue.isEmpty()) {
Long pid = queue.poll();
List<DeptDO> children = deptMapper.selectListByParentId(Collections.singleton(pid));
if (CollUtil.isNotEmpty(children)) {
result.addAll(children);
for (DeptDO child : children) {
queue.add(child.getId());
}
}
}
return result;
}
}

View File

@@ -81,7 +81,7 @@ public class OAuth2TokenServiceImplTest extends BaseDbAndRedisUnitTest {
assertPojoEquals(accessTokenDO, dbAccessTokenDO, "expiresTime", "createTime", "updateTime", "deleted");
assertEquals(userId, accessTokenDO.getUserId());
assertEquals(userType, accessTokenDO.getUserType());
assertEquals(2, accessTokenDO.getUserInfo().size());
assertEquals(3, accessTokenDO.getUserInfo().size());
assertEquals(user.getNickname(), accessTokenDO.getUserInfo().get("nickname"));
assertEquals(user.getDeptId().toString(), accessTokenDO.getUserInfo().get("deptId"));
assertEquals(clientId, accessTokenDO.getClientId());
@@ -93,7 +93,7 @@ public class OAuth2TokenServiceImplTest extends BaseDbAndRedisUnitTest {
assertPojoEquals(accessTokenDO, redisAccessTokenDO, "expiresTime", "createTime", "updateTime", "deleted");
// 断言刷新令牌
OAuth2RefreshTokenDO refreshTokenDO = oauth2RefreshTokenMapper.selectList().get(0);
assertPojoEquals(accessTokenDO, refreshTokenDO, "id", "expiresTime", "createTime", "updateTime", "deleted");
assertPojoEquals(accessTokenDO, refreshTokenDO, "id", "expiresTime", "createTime", "updateTime", "deleted", "tenantId");
assertFalse(DateUtils.isExpired(refreshTokenDO.getExpiresTime()));
}
@@ -183,7 +183,7 @@ public class OAuth2TokenServiceImplTest extends BaseDbAndRedisUnitTest {
// TODO @芋艿expiresTime 被屏蔽,仅 win11 会复现,建议后续修复。
assertPojoEquals(newAccessTokenDO, dbAccessTokenDO, "expiresTime", "createTime", "updateTime", "deleted");
assertPojoEquals(newAccessTokenDO, refreshTokenDO, "id", "expiresTime", "createTime", "updateTime", "deleted",
"creator", "updater");
"creator", "updater", "tenantId");
assertFalse(DateUtils.isExpired(newAccessTokenDO.getExpiresTime()));
// 断言,新的访问令牌的缓存
OAuth2AccessTokenDO redisAccessTokenDO = oauth2AccessTokenRedisDAO.get(newAccessTokenDO.getAccessToken());