多租户与景区关系
This commit is contained in:
@@ -4,6 +4,7 @@
|
|||||||
- 所有交互回答必须使用中文(简体),包括解释、建议与错误信息。
|
- 所有交互回答必须使用中文(简体),包括解释、建议与错误信息。
|
||||||
- 代码片段中的注释、日志消息、文档内容与示例说明均应为中文;编程语言关键字与三方 API 标识符保持原文。
|
- 代码片段中的注释、日志消息、文档内容与示例说明均应为中文;编程语言关键字与三方 API 标识符保持原文。
|
||||||
- 提交信息(commit)、合并请求(PR)描述与 Issue 标题/内容默认使用中文;涉及外部专有名词可保留英文缩写。
|
- 提交信息(commit)、合并请求(PR)描述与 Issue 标题/内容默认使用中文;涉及外部专有名词可保留英文缩写。
|
||||||
|
- 所有中文都使用utf-8
|
||||||
|
|
||||||
## 权限与执行策略
|
## 权限与执行策略
|
||||||
- 默认权限:Codex 在本仓库内可直接读取与编辑文件,无需额外审批。
|
- 默认权限:Codex 在本仓库内可直接读取与编辑文件,无需额外审批。
|
||||||
|
|||||||
+145
-83
@@ -1,83 +1,145 @@
|
|||||||
package com.central.user.service.impl;
|
package com.central.user.service.impl;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
import com.central.common.context.LoginUserContextHolder;
|
import com.central.common.context.LoginUserContextHolder;
|
||||||
import com.central.common.lock.DistributedLock;
|
import com.central.common.lock.DistributedLock;
|
||||||
import com.central.common.model.PageResult;
|
import com.central.common.model.PageResult;
|
||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
import com.central.common.model.SysRole;
|
import com.central.common.model.SysRole;
|
||||||
import com.central.common.service.impl.SuperServiceImpl;
|
import com.central.common.service.impl.SuperServiceImpl;
|
||||||
import com.central.user.mapper.SysRoleMapper;
|
import com.central.user.mapper.SysRoleMapper;
|
||||||
import com.central.user.mapper.SysRoleMenuMapper;
|
import com.central.user.mapper.SysRoleMenuMapper;
|
||||||
import com.central.user.mapper.SysUserRoleMapper;
|
import com.central.user.mapper.SysUserRoleMapper;
|
||||||
import com.central.user.service.ISysRoleService;
|
import com.central.user.service.ISysRoleService;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import com.central.common.service.ITenantHierarchyService;
|
||||||
import org.apache.commons.collections4.MapUtils;
|
import com.central.common.datascope.annotation.IgnoreTenantScope;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Service;
|
import org.apache.commons.collections4.MapUtils;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
import javax.annotation.Resource;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import java.util.List;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import java.util.Map;
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
/**
|
import java.util.List;
|
||||||
* @author 作者 owen E-mail: 624191343@qq.com
|
import java.util.Map;
|
||||||
*/
|
|
||||||
@Slf4j
|
/**
|
||||||
@Service
|
* @author 作者 owen E-mail: 624191343@qq.com
|
||||||
public class SysRoleServiceImpl extends SuperServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
|
*/
|
||||||
private final static String LOCK_KEY_ROLECODE = "rolecode:";
|
@Slf4j
|
||||||
|
@Service
|
||||||
@Resource
|
public class SysRoleServiceImpl extends SuperServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
|
||||||
private SysUserRoleMapper userRoleMapper;
|
private final static String LOCK_KEY_ROLECODE = "rolecode:";
|
||||||
|
|
||||||
@Resource
|
@Resource
|
||||||
private SysRoleMenuMapper roleMenuMapper;
|
private SysUserRoleMapper userRoleMapper;
|
||||||
|
|
||||||
@Autowired
|
@Resource
|
||||||
private DistributedLock lock;
|
private SysRoleMenuMapper roleMenuMapper;
|
||||||
|
|
||||||
@Transactional(rollbackFor = Exception.class)
|
@Autowired
|
||||||
@Override
|
private DistributedLock lock;
|
||||||
public void saveRole(SysRole sysRole) throws Exception {
|
|
||||||
String roleCode = sysRole.getCode();
|
@Resource
|
||||||
super.saveIdempotency(sysRole, lock
|
private ITenantHierarchyService tenantHierarchyService;
|
||||||
, LOCK_KEY_ROLECODE+roleCode, new QueryWrapper<SysRole>().eq("code", roleCode), "角色code已存在");
|
|
||||||
}
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
@Override
|
||||||
@Transactional(rollbackFor = Exception.class)
|
public void saveRole(SysRole sysRole) throws Exception {
|
||||||
@Override
|
String roleCode = sysRole.getCode();
|
||||||
public void deleteRole(Long id) {
|
super.saveIdempotency(sysRole, lock
|
||||||
baseMapper.deleteById(id);
|
, LOCK_KEY_ROLECODE+roleCode, new QueryWrapper<SysRole>().eq("code", roleCode), "角色code已存在");
|
||||||
roleMenuMapper.delete(id, null);
|
}
|
||||||
userRoleMapper.deleteUserRole(null, id);
|
|
||||||
}
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
@Override
|
||||||
@Override
|
public void deleteRole(Long id) {
|
||||||
public PageResult<SysRole> findRoles(Map<String, Object> params) {
|
baseMapper.deleteById(id);
|
||||||
Integer curPage = MapUtils.getInteger(params, "page");
|
roleMenuMapper.delete(id, null);
|
||||||
Integer limit = MapUtils.getInteger(params, "limit");
|
userRoleMapper.deleteUserRole(null, id);
|
||||||
Page<SysRole> page = new Page<>(curPage == null ? 0 : curPage, limit == null ? -1 : limit);
|
}
|
||||||
List<SysRole> list = baseMapper.findList(page, params);
|
|
||||||
return PageResult.<SysRole>builder().data(list).resp_code(0).count(page.getTotal()).build();
|
@Override
|
||||||
}
|
@IgnoreTenantScope
|
||||||
|
public PageResult<SysRole> findRoles(Map<String, Object> params) {
|
||||||
@Override
|
Integer curPage = MapUtils.getInteger(params, "page");
|
||||||
@Transactional
|
Integer limit = MapUtils.getInteger(params, "limit");
|
||||||
public Result saveOrUpdateRole(SysRole sysRole) throws Exception {
|
// 以租户为主:支持按租户及其子租户过滤
|
||||||
if (sysRole.getId() == null) {
|
String tenantId = MapUtils.getString(params, "tenantId");
|
||||||
sysRole.setCreatorId(LoginUserContextHolder.getUser().getId());
|
Object incRaw = params.get("includeChildren");
|
||||||
this.saveRole(sysRole);
|
boolean includeChildren = true;
|
||||||
} else {
|
if (incRaw != null) {
|
||||||
baseMapper.updateById(sysRole);
|
try {
|
||||||
}
|
if (incRaw instanceof Boolean) {
|
||||||
return Result.succeed("操作成功");
|
includeChildren = (Boolean) incRaw;
|
||||||
}
|
} else if (incRaw instanceof Number) {
|
||||||
|
includeChildren = ((Number) incRaw).intValue() != 0;
|
||||||
@Override
|
} else if (incRaw instanceof CharSequence) {
|
||||||
public List<SysRole> findAll() {
|
String s = incRaw.toString().trim();
|
||||||
return baseMapper.findAll();
|
includeChildren = ("true".equalsIgnoreCase(s) || "1".equals(s) || "yes".equalsIgnoreCase(s));
|
||||||
}
|
}
|
||||||
}
|
} catch (Exception ignored) { /* 使用默认 true */ }
|
||||||
|
}
|
||||||
|
java.util.List<String> tenantIds = null;
|
||||||
|
if (StringUtils.isNotBlank(tenantId)) {
|
||||||
|
try {
|
||||||
|
if (includeChildren) {
|
||||||
|
// 展开包含所有子级(确保包含自身)
|
||||||
|
tenantIds = tenantHierarchyService.getAllSubTenantIds(tenantId);
|
||||||
|
if (tenantIds == null || tenantIds.isEmpty()) {
|
||||||
|
tenantIds = new java.util.ArrayList<>();
|
||||||
|
}
|
||||||
|
if (!tenantIds.contains(tenantId)) {
|
||||||
|
tenantIds = new java.util.ArrayList<>(tenantIds);
|
||||||
|
tenantIds.add(0, tenantId);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tenantIds = java.util.Collections.singletonList(tenantId);
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) { tenantIds = java.util.Collections.singletonList(tenantId); }
|
||||||
|
|
||||||
|
// 与当前用户可访问租户集求交集,避免越权和误查全量
|
||||||
|
// 与用户可访问租户不再做强制求交集,保持与用户列表查询一致的行为,
|
||||||
|
// 以显式传入的 tenantId/includeChildren 为准,由接口鉴权控制访问边界。
|
||||||
|
|
||||||
|
if (tenantIds == null || tenantIds.isEmpty()) {
|
||||||
|
// 无可访问租户,直接返回空结果
|
||||||
|
Page<SysRole> empty = new Page<>(curPage == null ? 0 : curPage, limit == null ? -1 : limit);
|
||||||
|
return PageResult.<SysRole>builder().data(java.util.Collections.emptyList()).resp_code(0).count(0L).build();
|
||||||
|
}
|
||||||
|
params.put("tenantIds", tenantIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
Page<SysRole> page = new Page<>(curPage == null ? 0 : curPage, limit == null ? -1 : limit);
|
||||||
|
List<SysRole> list = baseMapper.findList(page, params);
|
||||||
|
return PageResult.<SysRole>builder().data(list).resp_code(0).count(page.getTotal()).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public Result saveOrUpdateRole(SysRole sysRole) throws Exception {
|
||||||
|
if (sysRole.getId() == null) {
|
||||||
|
// 新增时补齐租户ID(以当前上下文或表单传参为准)
|
||||||
|
if (StringUtils.isBlank(sysRole.getTenantId())) {
|
||||||
|
try {
|
||||||
|
String ctxTenant = com.central.common.context.TenantContextHolder.getTenant();
|
||||||
|
if (StringUtils.isNotBlank(ctxTenant)) {
|
||||||
|
sysRole.setTenantId(ctxTenant);
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) { /* no-op */ }
|
||||||
|
}
|
||||||
|
sysRole.setCreatorId(LoginUserContextHolder.getUser().getId());
|
||||||
|
this.saveRole(sysRole);
|
||||||
|
} else {
|
||||||
|
baseMapper.updateById(sysRole);
|
||||||
|
}
|
||||||
|
return Result.succeed("操作成功");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<SysRole> findAll() {
|
||||||
|
return baseMapper.findAll();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+40
-7
@@ -16,7 +16,9 @@ import com.central.common.model.UserType;
|
|||||||
import com.central.common.model.SuperEntity;
|
import com.central.common.model.SuperEntity;
|
||||||
import com.central.common.model.SysMenu;
|
import com.central.common.model.SysMenu;
|
||||||
import com.central.common.service.impl.SuperServiceImpl;
|
import com.central.common.service.impl.SuperServiceImpl;
|
||||||
import com.central.user.feign.DeviceCenterService;
|
import com.central.user.feign.DeviceCenterService;
|
||||||
|
import com.central.common.service.ITenantHierarchyService;
|
||||||
|
import com.central.common.context.LoginUserContextHolder;
|
||||||
import com.central.user.feign.OrderCenterService;
|
import com.central.user.feign.OrderCenterService;
|
||||||
import com.central.user.mapper.SysRoleMenuMapper;
|
import com.central.user.mapper.SysRoleMenuMapper;
|
||||||
import com.central.user.mapper.SysUserMapper;
|
import com.central.user.mapper.SysUserMapper;
|
||||||
@@ -62,8 +64,11 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
@Resource
|
@Resource
|
||||||
private OrderCenterService orderCenterService;
|
private OrderCenterService orderCenterService;
|
||||||
|
|
||||||
@Resource
|
@Resource
|
||||||
private DeviceCenterService deviceCenterService;
|
private DeviceCenterService deviceCenterService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private ITenantHierarchyService tenantHierarchyService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public SysUser findByUsername(String username) {
|
public SysUser findByUsername(String username) {
|
||||||
@@ -225,10 +230,38 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
return Result.succeed("修改成功");
|
return Result.succeed("修改成功");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PageResult<SysUser> findUsers(Map<String, Object> params) {
|
public PageResult<SysUser> findUsers(Map<String, Object> params) {
|
||||||
Page<SysUser> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
|
Page<SysUser> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
|
||||||
List<SysUser> list = baseMapper.findList(page, params);
|
// 组装租户过滤:有传tenantId则以其为锚点(可选包含子级);未传则按当前登录用户及其子租户
|
||||||
|
String tenantId = MapUtils.getString(params, "tenantId");
|
||||||
|
Boolean includeChildren = MapUtils.getBoolean(params, "includeChildren", Boolean.TRUE);
|
||||||
|
List<String> tenantIds = null;
|
||||||
|
if (StrUtil.isNotBlank(tenantId)) {
|
||||||
|
try {
|
||||||
|
if (Boolean.TRUE.equals(includeChildren)) {
|
||||||
|
tenantIds = tenantHierarchyService.getAllSubTenantIds(tenantId);
|
||||||
|
} else {
|
||||||
|
tenantIds = java.util.Collections.singletonList(tenantId);
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) { tenantIds = java.util.Collections.singletonList(tenantId); }
|
||||||
|
} else {
|
||||||
|
// 未显式指定,则按当前登录用户所属租户及其子租户
|
||||||
|
try {
|
||||||
|
String anchor = LoginUserContextHolder.getCurrentTenantId();
|
||||||
|
if (StringUtils.isNotBlank(anchor)) {
|
||||||
|
try {
|
||||||
|
tenantIds = tenantHierarchyService.getAllSubTenantIds(anchor);
|
||||||
|
} catch (Exception e) {
|
||||||
|
tenantIds = java.util.Collections.singletonList(anchor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) { /* no-op */ }
|
||||||
|
}
|
||||||
|
if (tenantIds != null && !tenantIds.isEmpty()) {
|
||||||
|
params.put("tenantIds", tenantIds);
|
||||||
|
}
|
||||||
|
List<SysUser> list = baseMapper.findList(page, params);
|
||||||
long total = page.getTotal();
|
long total = page.getTotal();
|
||||||
if (total > 0) {
|
if (total > 0) {
|
||||||
List<Long> userIds = list.stream().map(SysUser::getId).collect(Collectors.toList());
|
List<Long> userIds = list.stream().map(SysUser::getId).collect(Collectors.toList());
|
||||||
|
|||||||
+34
-6
@@ -44,6 +44,33 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
List<String> subTenantIds = tenantHierarchyMapper.selectSubTenantIds(parentTenantId);
|
List<String> subTenantIds = tenantHierarchyMapper.selectSubTenantIds(parentTenantId);
|
||||||
|
if (subTenantIds == null) {
|
||||||
|
subTenantIds = new ArrayList<>();
|
||||||
|
}
|
||||||
|
// 确保包含自身
|
||||||
|
if (!subTenantIds.contains(parentTenantId)) {
|
||||||
|
subTenantIds.add(0, parentTenantId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果基于 tenant_path 的查询结果过少,回退为按 parent_tenant_id 递归遍历
|
||||||
|
if (subTenantIds.size() <= 1) {
|
||||||
|
Deque<String> queue = new ArrayDeque<>();
|
||||||
|
queue.add(parentTenantId);
|
||||||
|
while (!queue.isEmpty()) {
|
||||||
|
String pid = queue.poll();
|
||||||
|
List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(pid);
|
||||||
|
if (children != null) {
|
||||||
|
for (Tenant t : children) {
|
||||||
|
String tid = t.getTenantId();
|
||||||
|
if (!subTenantIds.contains(tid)) {
|
||||||
|
subTenantIds.add(tid);
|
||||||
|
queue.add(tid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
log.debug("查询租户 {} 的所有子租户,数量: {}", parentTenantId, subTenantIds.size());
|
log.debug("查询租户 {} 的所有子租户,数量: {}", parentTenantId, subTenantIds.size());
|
||||||
return subTenantIds;
|
return subTenantIds;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -167,7 +194,7 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
|||||||
@CacheEvict(value = "tenant:hierarchy", allEntries = true)
|
@CacheEvict(value = "tenant:hierarchy", allEntries = true)
|
||||||
public Result<Tenant> createTenant(Tenant tenant) {
|
public Result<Tenant> createTenant(Tenant tenant) {
|
||||||
try {
|
try {
|
||||||
// 验证必填字段
|
// 校验必填字段
|
||||||
if (!StringUtils.hasText(tenant.getTenantId())) {
|
if (!StringUtils.hasText(tenant.getTenantId())) {
|
||||||
return Result.failed("租户ID不能为空");
|
return Result.failed("租户ID不能为空");
|
||||||
}
|
}
|
||||||
@@ -180,7 +207,7 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
|||||||
return Result.failed("租户ID已存在");
|
return Result.failed("租户ID已存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 验证父租户关系
|
// 验证父子租户关系
|
||||||
if (StringUtils.hasText(tenant.getParentTenantId())) {
|
if (StringUtils.hasText(tenant.getParentTenantId())) {
|
||||||
if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
|
if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
|
||||||
return Result.failed("无效的父子租户关系");
|
return Result.failed("无效的父子租户关系");
|
||||||
@@ -242,14 +269,14 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
|||||||
return Result.failed("租户不存在");
|
return Result.failed("租户不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 验证父租户关系变更
|
// 验证父子关系变更
|
||||||
if (!Objects.equals(existingTenant.getParentTenantId(), tenant.getParentTenantId())) {
|
if (!Objects.equals(existingTenant.getParentTenantId(), tenant.getParentTenantId())) {
|
||||||
if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
|
if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
|
||||||
return Result.failed("无效的父子租户关系");
|
return Result.failed("无效的父子租户关系");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用主键ID执行更新,避免未传ID导致返回0
|
// 使用主键ID执行更新,避免未传ID导致更新不到
|
||||||
tenant.setId(existingTenant.getId());
|
tenant.setId(existingTenant.getId());
|
||||||
int result = tenantHierarchyMapper.updateById(tenant);
|
int result = tenantHierarchyMapper.updateById(tenant);
|
||||||
if (result > 0) {
|
if (result > 0) {
|
||||||
@@ -314,7 +341,7 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
|||||||
.map(this::convertToTenantInfo)
|
.map(this::convertToTenantInfo)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
log.debug("查询租户列表完成,总数: {}, 当前页: {}", total, tenantInfos.size());
|
log.debug("查询租户列表完成,总数: {},当前页数量: {}", total, tenantInfos.size());
|
||||||
return Result.succeed(tenantInfos);
|
return Result.succeed(tenantInfos);
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -367,7 +394,7 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 转换为TenantInfo
|
* 转换为 TenantInfo
|
||||||
*/
|
*/
|
||||||
private TenantInfo convertToTenantInfo(Tenant tenant) {
|
private TenantInfo convertToTenantInfo(Tenant tenant) {
|
||||||
if (tenant == null) {
|
if (tenant == null) {
|
||||||
@@ -398,3 +425,4 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,17 +12,28 @@
|
|||||||
data_scope
|
data_scope
|
||||||
</sql>
|
</sql>
|
||||||
|
|
||||||
<sql id="where">
|
<sql id="where">
|
||||||
<where>
|
<where>
|
||||||
<if test="r.name != null and r.name != ''">
|
<if test="r.name != null and r.name != ''">
|
||||||
and t.name like concat('%', #{r.name}, '%')
|
and t.name like concat('%', #{r.name}, '%')
|
||||||
</if>
|
</if>
|
||||||
|
|
||||||
<if test="r.searchKey != null and r.searchKey != '' and r.searchKey=='name'">
|
<if test="r.searchKey != null and r.searchKey != '' and r.searchKey=='name'">
|
||||||
and t.name like concat('%', #{r.searchValue}, '%')
|
and t.name like concat('%', #{r.searchValue}, '%')
|
||||||
</if>
|
</if>
|
||||||
</where>
|
|
||||||
</sql>
|
<!-- 按租户过滤(以租户为主):优先使用租户ID集合,其次使用单个租户ID -->
|
||||||
|
<if test="r.tenantIds != null and r.tenantIds.size > 0">
|
||||||
|
and t.tenant_id in
|
||||||
|
<foreach collection="r.tenantIds" item="tid" open="(" separator="," close=")">
|
||||||
|
#{tid}
|
||||||
|
</foreach>
|
||||||
|
</if>
|
||||||
|
<if test="(r.tenantIds == null or r.tenantIds.size == 0) and r.tenantId != null and r.tenantId != ''">
|
||||||
|
and t.tenant_id = #{r.tenantId}
|
||||||
|
</if>
|
||||||
|
</where>
|
||||||
|
</sql>
|
||||||
|
|
||||||
<select id="findList" resultType="com.central.common.model.SysRole">
|
<select id="findList" resultType="com.central.common.model.SysRole">
|
||||||
select <include refid="Column_List"/>
|
select <include refid="Column_List"/>
|
||||||
@@ -36,4 +47,4 @@
|
|||||||
from sys_role
|
from sys_role
|
||||||
order by create_time desc
|
order by create_time desc
|
||||||
</select>
|
</select>
|
||||||
</mapper>
|
</mapper>
|
||||||
|
|||||||
@@ -2,12 +2,18 @@
|
|||||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||||
<mapper namespace="com.central.user.mapper.SysUserMapper">
|
<mapper namespace="com.central.user.mapper.SysUserMapper">
|
||||||
<sql id="where">
|
<sql id="where">
|
||||||
<where>
|
<where>
|
||||||
t.is_del=0
|
t.is_del=0
|
||||||
<if test="u.id != null and u.id != ''">
|
<if test="u.tenantIds != null and u.tenantIds.size > 0">
|
||||||
and t.id like concat('%', #{u.id}, '%')
|
and t.company in
|
||||||
</if>
|
<foreach collection="u.tenantIds" item="tid" open="(" separator="," close=")">
|
||||||
|
#{tid}
|
||||||
|
</foreach>
|
||||||
|
</if>
|
||||||
|
<if test="u.id != null and u.id != ''">
|
||||||
|
and t.id like concat('%', #{u.id}, '%')
|
||||||
|
</if>
|
||||||
<if test="u.username != null and u.username != ''">
|
<if test="u.username != null and u.username != ''">
|
||||||
and t.username like concat('%', #{u.username}, '%')
|
and t.username like concat('%', #{u.username}, '%')
|
||||||
</if>
|
</if>
|
||||||
@@ -40,4 +46,4 @@
|
|||||||
<include refid="where" />
|
<include refid="where" />
|
||||||
order by t.id desc
|
order by t.id desc
|
||||||
</select>
|
</select>
|
||||||
</mapper>
|
</mapper>
|
||||||
|
|||||||
@@ -24,4 +24,9 @@ public class SysRole extends SuperEntity {
|
|||||||
*/
|
*/
|
||||||
private DataScope dataScope;
|
private DataScope dataScope;
|
||||||
private Long creatorId;
|
private Long creatorId;
|
||||||
|
/**
|
||||||
|
* 所属租户
|
||||||
|
*/
|
||||||
|
@TableField("tenant_id")
|
||||||
|
private String tenantId;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -133,7 +133,6 @@ public class LoginUserUtils {
|
|||||||
if (sysRoles != null) {
|
if (sysRoles != null) {
|
||||||
sysRoles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getCode())));
|
sysRoles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getCode())));
|
||||||
}
|
}
|
||||||
log.info("获取到的user是:{}",sysUser);
|
|
||||||
// 兼容 enabled 可能为 null 的场景,默认视为启用
|
// 兼容 enabled 可能为 null 的场景,默认视为启用
|
||||||
boolean enabled = Optional.ofNullable(sysUser.getEnabled()).orElse(true);
|
boolean enabled = Optional.ofNullable(sysUser.getEnabled()).orElse(true);
|
||||||
LoginAppUser user = new LoginAppUser(sysUser.getId()
|
LoginAppUser user = new LoginAppUser(sysUser.getId()
|
||||||
|
|||||||
+2
-1
@@ -9,6 +9,7 @@ import jakarta.servlet.ServletException;
|
|||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
|
import org.springframework.core.Ordered;
|
||||||
import org.springframework.core.annotation.Order;
|
import org.springframework.core.annotation.Order;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
@@ -27,7 +28,7 @@ import java.io.IOException;
|
|||||||
* Github: https://github.com/zlt2000
|
* Github: https://github.com/zlt2000
|
||||||
*/
|
*/
|
||||||
@ConditionalOnClass(Filter.class)
|
@ConditionalOnClass(Filter.class)
|
||||||
@Order
|
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
|
||||||
public class LoginUserFilter extends OncePerRequestFilter {
|
public class LoginUserFilter extends OncePerRequestFilter {
|
||||||
@Override
|
@Override
|
||||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||||
|
|||||||
+48
@@ -0,0 +1,48 @@
|
|||||||
|
package com.central.common.filter;
|
||||||
|
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
import com.central.common.context.TenantQueryOverrideContext;
|
||||||
|
import jakarta.servlet.Filter;
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
|
import org.springframework.core.Ordered;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 基于前端参数的租户覆盖过滤器
|
||||||
|
* 规则:
|
||||||
|
* - 如果请求参数中携带 tenantId,则以其作为本次请求的查询锚点;
|
||||||
|
* - 如果未携带,则不处理(沿用登录上下文中的默认租户)。
|
||||||
|
*
|
||||||
|
* 注意:仅对当前请求生效,通过 TenantQueryOverrideContext 传递给后续数据范围处理。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@ConditionalOnClass(Filter.class)
|
||||||
|
@Order(Ordered.HIGHEST_PRECEDENCE + 19)
|
||||||
|
public class TenantParamOverrideFilter extends OncePerRequestFilter {
|
||||||
|
private static final String PARAM_TENANT_ID = "tenantId";
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||||
|
FilterChain filterChain) throws IOException, ServletException {
|
||||||
|
try {
|
||||||
|
String overrideTenant = request.getParameter(PARAM_TENANT_ID);
|
||||||
|
if (StrUtil.isNotBlank(overrideTenant)) {
|
||||||
|
// 前端传了租户ID:按该ID作为本次查询锚点(后续数据范围会包含其子租户)
|
||||||
|
TenantQueryOverrideContext.setTenantId(overrideTenant);
|
||||||
|
log.debug("本次请求使用前端参数覆盖租户ID: {}", overrideTenant);
|
||||||
|
}
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
} finally {
|
||||||
|
TenantQueryOverrideContext.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
+9
-7
@@ -11,6 +11,7 @@ import jakarta.servlet.http.HttpServletRequest;
|
|||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
|
import org.springframework.core.Ordered;
|
||||||
import org.springframework.core.annotation.Order;
|
import org.springframework.core.annotation.Order;
|
||||||
import org.springframework.web.filter.OncePerRequestFilter;
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
@@ -18,14 +19,14 @@ import java.io.IOException;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 读取可选的 tenantId 查询参数,作为本次请求的租户范围覆盖锚点。
|
* 读取可选的 tenantId 查询参数,作为本次请求的租户范围覆盖锚点�?
|
||||||
* 规则:
|
* 规则�?
|
||||||
* - APP 用户忽略该参数(记录warn)。
|
* - APP 用户忽略该参数(记录warn)�?
|
||||||
* - BACKEND 用户仅在参数属于“可访问租户集”时生效;否则忽略并warn。
|
* - BACKEND 用户仅在参数属于“可访问租户集”时生效;否则忽略并warn�?
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@ConditionalOnClass(Filter.class)
|
@ConditionalOnClass(Filter.class)
|
||||||
@Order
|
@Order(Ordered.HIGHEST_PRECEDENCE + 20)
|
||||||
public class TenantQueryOverrideFilter extends OncePerRequestFilter {
|
public class TenantQueryOverrideFilter extends OncePerRequestFilter {
|
||||||
private static final String PARAM_TENANT_ID = "tenantId";
|
private static final String PARAM_TENANT_ID = "tenantId";
|
||||||
|
|
||||||
@@ -38,7 +39,7 @@ public class TenantQueryOverrideFilter extends OncePerRequestFilter {
|
|||||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||||
if (user == null) {
|
if (user == null) {
|
||||||
// 未登录,忽略参数
|
// 未登录,忽略参数
|
||||||
log.debug("忽略tenantId参数(未登录): {}", overrideTenant);
|
log.debug("忽略tenantId参数(未登录?: {}", overrideTenant);
|
||||||
} else {
|
} else {
|
||||||
String userType = (String) user.getAttributes().getOrDefault("type", "BACKEND");
|
String userType = (String) user.getAttributes().getOrDefault("type", "BACKEND");
|
||||||
if ("APP".equals(userType)) {
|
if ("APP".equals(userType)) {
|
||||||
@@ -49,7 +50,7 @@ public class TenantQueryOverrideFilter extends OncePerRequestFilter {
|
|||||||
TenantQueryOverrideContext.setTenantId(overrideTenant);
|
TenantQueryOverrideContext.setTenantId(overrideTenant);
|
||||||
log.debug("本次请求使用覆盖租户ID: {}", overrideTenant);
|
log.debug("本次请求使用覆盖租户ID: {}", overrideTenant);
|
||||||
} else {
|
} else {
|
||||||
log.warn("覆盖tenantId不在可访问范围, user={}, tenantId={}", user.getUsername(), overrideTenant);
|
log.warn("覆盖tenantId不在可访问范围? user={}, tenantId={}", user.getUsername(), overrideTenant);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -61,3 +62,4 @@ public class TenantQueryOverrideFilter extends OncePerRequestFilter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+1
@@ -1,4 +1,5 @@
|
|||||||
com.central.common.filter.TenantFilter
|
com.central.common.filter.TenantFilter
|
||||||
com.central.common.filter.LoginUserFilter
|
com.central.common.filter.LoginUserFilter
|
||||||
|
com.central.common.filter.TenantParamOverrideFilter
|
||||||
com.central.common.filter.TenantQueryOverrideFilter
|
com.central.common.filter.TenantQueryOverrideFilter
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { Space, Button, TreeSelect, Checkbox, message } from 'antd';
|
import { Space, Button, TreeSelect, Checkbox, message } from 'antd';
|
||||||
import { tenantApi, TenantTreeNode } from '@/services/tenant';
|
import { tenantApi, TenantTreeNode } from '@/services/tenant';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
// 当租户或“包含子租户”变更后回调
|
// 租户或“包含下级”变化后的回调(外部将 tenantId/includeChildren 透传到请求参数)
|
||||||
onChanged?: (tenantId: string, includeChildren: boolean) => void;
|
onChanged?: (tenantId: string, includeChildren: boolean) => void;
|
||||||
|
// 可选:是否调用后端切换查询上下文(默认 false,不建议启用)
|
||||||
|
useSwitchTenant?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const TenantScopeFilter: React.FC<Props> = ({ onChanged }) => {
|
const TenantScopeFilter: React.FC<Props> = ({ onChanged, useSwitchTenant = false }) => {
|
||||||
const [tree, setTree] = useState<TenantTreeNode[]>([]);
|
const [tree, setTree] = useState<TenantTreeNode[]>([]);
|
||||||
const [tenantId, setTenantId] = useState<string | undefined>();
|
const [tenantId, setTenantId] = useState<string | undefined>();
|
||||||
const [includeChildren, setIncludeChildren] = useState(true);
|
const [includeChildren, setIncludeChildren] = useState(true);
|
||||||
@@ -21,8 +23,8 @@ const TenantScopeFilter: React.FC<Props> = ({ onChanged }) => {
|
|||||||
tenantApi.getAccessibleTenants(),
|
tenantApi.getAccessibleTenants(),
|
||||||
tenantApi.getCurrentTenant(),
|
tenantApi.getCurrentTenant(),
|
||||||
]);
|
]);
|
||||||
if (treeRes.success) setTree(treeRes.data || []);
|
if ((treeRes as any)?.success) setTree((treeRes as any).data || []);
|
||||||
if (currentRes.success) setTenantId(currentRes.data?.tenantId);
|
if ((currentRes as any)?.success) setTenantId((currentRes as any).data?.tenantId);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -40,15 +42,14 @@ const TenantScopeFilter: React.FC<Props> = ({ onChanged }) => {
|
|||||||
const handleApply = async () => {
|
const handleApply = async () => {
|
||||||
if (!tenantId) return;
|
if (!tenantId) return;
|
||||||
try {
|
try {
|
||||||
const res = await tenantApi.switchTenant(tenantId);
|
if (useSwitchTenant) {
|
||||||
if (res.success) {
|
const res = await tenantApi.switchTenant(tenantId);
|
||||||
message.success('租户范围已更新');
|
if ((res as any)?.success) message.success('租户范围已更新');
|
||||||
onChanged?.(tenantId, includeChildren);
|
else { message.error((res as any)?.msg || '切换失败'); return; }
|
||||||
} else {
|
|
||||||
message.error((res as any).msg || '切换失败');
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
onChanged?.(tenantId, includeChildren);
|
||||||
message.error('切换失败');
|
} catch {
|
||||||
|
message.error('操作失败');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -70,4 +71,5 @@ const TenantScopeFilter: React.FC<Props> = ({ onChanged }) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default TenantScopeFilter;
|
export default TenantScopeFilter;
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ export interface SearchBarPlusProps {
|
|||||||
onTenantChanged?: (tenantId: string, includeChildren: boolean) => void;
|
onTenantChanged?: (tenantId: string, includeChildren: boolean) => void;
|
||||||
// 租户筛选放置位置:start 放在最前,end 放在最后(默认 start)
|
// 租户筛选放置位置:start 放在最前,end 放在最后(默认 start)
|
||||||
tenantPosition?: 'start' | 'end';
|
tenantPosition?: 'start' | 'end';
|
||||||
|
// 是否调用后端“切换查询租户”接口(默认不调用,避免跨页面副作用)
|
||||||
|
useSwitchTenant?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const SearchBarPlus: React.FC<SearchBarPlusProps> = ({
|
const SearchBarPlus: React.FC<SearchBarPlusProps> = ({
|
||||||
@@ -30,13 +32,14 @@ const SearchBarPlus: React.FC<SearchBarPlusProps> = ({
|
|||||||
showTenant = true,
|
showTenant = true,
|
||||||
onTenantChanged,
|
onTenantChanged,
|
||||||
tenantPosition = 'start',
|
tenantPosition = 'start',
|
||||||
|
useSwitchTenant = false,
|
||||||
}) => {
|
}) => {
|
||||||
const handleFinish = async (values: Record<string, any>) => {
|
const handleFinish = async (values: Record<string, any>) => {
|
||||||
try {
|
try {
|
||||||
if (showTenant && values && values.tenantId) {
|
if (useSwitchTenant && showTenant && values && (values as any).tenantId) {
|
||||||
await tenantApi.switchTenant(values.tenantId);
|
await tenantApi.switchTenant((values as any).tenantId);
|
||||||
}
|
}
|
||||||
onTenantChanged?.(values?.tenantId, !!values?.includeChildren);
|
onTenantChanged?.((values as any)?.tenantId, !!(values as any)?.includeChildren);
|
||||||
} finally {
|
} finally {
|
||||||
await onFinish?.(values);
|
await onFinish?.(values);
|
||||||
}
|
}
|
||||||
@@ -58,3 +61,4 @@ const SearchBarPlus: React.FC<SearchBarPlusProps> = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default SearchBarPlus;
|
export default SearchBarPlus;
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ export interface TenantSelectorProps {
|
|||||||
labelIncludeChildren?: React.ReactNode;
|
labelIncludeChildren?: React.ReactNode;
|
||||||
// 是否隐藏“包含下级”复选框(用于仅需要选择租户的场景,如用户表单)
|
// 是否隐藏“包含下级”复选框(用于仅需要选择租户的场景,如用户表单)
|
||||||
hideIncludeChildren?: boolean;
|
hideIncludeChildren?: boolean;
|
||||||
|
// 透传给租户选择项的校验规则(用于必填等)
|
||||||
|
rulesTenant?: any[];
|
||||||
}
|
}
|
||||||
|
|
||||||
const toTreeData = (nodes?: TenantTreeNode[] | any): any[] => {
|
const toTreeData = (nodes?: TenantTreeNode[] | any): any[] => {
|
||||||
@@ -27,6 +29,7 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
|
|||||||
labelTenant = '租户',
|
labelTenant = '租户',
|
||||||
labelIncludeChildren = '包含下级',
|
labelIncludeChildren = '包含下级',
|
||||||
hideIncludeChildren = false,
|
hideIncludeChildren = false,
|
||||||
|
rulesTenant,
|
||||||
}) => {
|
}) => {
|
||||||
const form = Form.useFormInstance?.();
|
const form = Form.useFormInstance?.();
|
||||||
const [tree, setTree] = useState<TenantTreeNode[]>([]);
|
const [tree, setTree] = useState<TenantTreeNode[]>([]);
|
||||||
@@ -89,7 +92,7 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Form.Item name={nameTenant} label={labelTenant}>
|
<Form.Item name={nameTenant} label={labelTenant} rules={rulesTenant as any}>
|
||||||
<TreeSelect
|
<TreeSelect
|
||||||
style={{ minWidth: 260 }}
|
style={{ minWidth: 260 }}
|
||||||
treeDefaultExpandAll
|
treeDefaultExpandAll
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ const Welcome: React.FC = () => {
|
|||||||
</Space>
|
</Space>
|
||||||
</Col>
|
</Col>
|
||||||
<Col>
|
<Col>
|
||||||
<TenantScopeFilter />
|
<TenantScopeFilter useSwitchTenant onChanged={() => { /* 切换后由后端上下文生效 */ }} />
|
||||||
</Col>
|
</Col>
|
||||||
</Row>
|
</Row>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -122,4 +122,4 @@ const Welcome: React.FC = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default Welcome;
|
export default Welcome;
|
||||||
|
|||||||
@@ -27,10 +27,10 @@ const AuditLogPage: React.FC = () => {
|
|||||||
span={8}
|
span={8}
|
||||||
onTenantChanged={() => actionRef.current?.reload?.()}
|
onTenantChanged={() => actionRef.current?.reload?.()}
|
||||||
onFinish={async (values) => {
|
onFinish={async (values) => {
|
||||||
const { searchKey, searchValue } = values as any;
|
const { searchKey, searchValue, ...rest } = values as any;
|
||||||
let queryStr = '';
|
let queryStr = '';
|
||||||
if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`;
|
if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`;
|
||||||
setParams({ ...params, queryStr });
|
setParams({ ...rest, queryStr });
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<ProFormSelect
|
<ProFormSelect
|
||||||
|
|||||||
@@ -26,10 +26,10 @@ const SlowSqlLogPage: React.FC = () => {
|
|||||||
span={8}
|
span={8}
|
||||||
onTenantChanged={() => actionRef.current?.reload?.()}
|
onTenantChanged={() => actionRef.current?.reload?.()}
|
||||||
onFinish={async (values) => {
|
onFinish={async (values) => {
|
||||||
const { searchKey, searchValue } = values as any;
|
const { searchKey, searchValue, ...rest } = values as any;
|
||||||
let queryStr = '';
|
let queryStr = '';
|
||||||
if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`;
|
if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`;
|
||||||
setParams({ ...params, queryStr });
|
setParams({ ...rest, queryStr });
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<ProFormSelect name="searchKey" label="检索" valueEnum={{ none: '全文检索', query_str: '查询语句' }} />
|
<ProFormSelect name="searchKey" label="检索" valueEnum={{ none: '全文检索', query_str: '查询语句' }} />
|
||||||
|
|||||||
@@ -42,10 +42,10 @@ const SysLogPage: React.FC = () => {
|
|||||||
span={8}
|
span={8}
|
||||||
onTenantChanged={() => actionRef.current?.reload?.()}
|
onTenantChanged={() => actionRef.current?.reload?.()}
|
||||||
onFinish={async (values) => {
|
onFinish={async (values) => {
|
||||||
const { searchKey, searchValue } = values as any;
|
const { searchKey, searchValue, ...rest } = values as any;
|
||||||
let queryStr = '';
|
let queryStr = '';
|
||||||
if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`;
|
if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`;
|
||||||
setParams({ ...params, queryStr });
|
setParams({ ...rest, queryStr });
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<ProFormSelect name="searchKey" label="检索" valueEnum={{ none: '全文检索', message: '日志信息', logLevel: '日志级别', appName: '应用名', classname: '类名', traceId: '链路追踪ID' }} />
|
<ProFormSelect name="searchKey" label="检索" valueEnum={{ none: '全文检索', message: '日志信息', logLevel: '日志级别', appName: '应用名', classname: '类名', traceId: '链路追踪ID' }} />
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ const MESSAGE_STATUS: Record<number, { text: string; color: string }> = {
|
|||||||
const MessageList: React.FC = () => {
|
const MessageList: React.FC = () => {
|
||||||
const actionRef = useRef<ActionType>();
|
const actionRef = useRef<ActionType>();
|
||||||
const [selectedRows, setSelectedRows] = useState<MessageItem[]>([]);
|
const [selectedRows, setSelectedRows] = useState<MessageItem[]>([]);
|
||||||
|
const [params, setParams] = useState<Record<string, any>>({});
|
||||||
|
|
||||||
const handleMessageClick = async (record: MessageItem) => {
|
const handleMessageClick = async (record: MessageItem) => {
|
||||||
if (record.status === 0) {
|
if (record.status === 0) {
|
||||||
@@ -97,6 +98,7 @@ const MessageList: React.FC = () => {
|
|||||||
split
|
split
|
||||||
span={8}
|
span={8}
|
||||||
onTenantChanged={() => actionRef.current?.reload()}
|
onTenantChanged={() => actionRef.current?.reload()}
|
||||||
|
onFinish={async (values) => setParams(values)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<ActionBar right={<GradientButton size="middle" key="markAllRead" onClick={handleMarkAllRead}>全部标记已读</GradientButton>} />
|
<ActionBar right={<GradientButton size="middle" key="markAllRead" onClick={handleMarkAllRead}>全部标记已读</GradientButton>} />
|
||||||
@@ -107,7 +109,7 @@ const MessageList: React.FC = () => {
|
|||||||
rowKey="id"
|
rowKey="id"
|
||||||
search={{ labelWidth: 120 }}
|
search={{ labelWidth: 120 }}
|
||||||
toolBarRender={false}
|
toolBarRender={false}
|
||||||
request={(p) => messageApi.list(p)}
|
request={(p) => messageApi.list({ ...(p as any), ...params })}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
rowSelection={{ onChange: (_, rows) => setSelectedRows(rows) }}
|
rowSelection={{ onChange: (_, rows) => setSelectedRows(rows) }}
|
||||||
pagination={{ showQuickJumper: true, showSizeChanger: true }}
|
pagination={{ showQuickJumper: true, showSizeChanger: true }}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ const HomeCarouselPage: React.FC = () => {
|
|||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
const [editOpen, setEditOpen] = useState(false);
|
const [editOpen, setEditOpen] = useState(false);
|
||||||
const [current, setCurrent] = useState<HomeCarouselItem | undefined>(undefined);
|
const [current, setCurrent] = useState<HomeCarouselItem | undefined>(undefined);
|
||||||
|
const [params, setParams] = useState<Record<string, any>>({});
|
||||||
|
|
||||||
const columns: any[] = [
|
const columns: any[] = [
|
||||||
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
|
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
|
||||||
@@ -40,14 +41,20 @@ const HomeCarouselPage: React.FC = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<PageContainer header={{ title: '首页轮播' }}>
|
<PageContainer header={{ title: '首页轮播' }}>
|
||||||
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => { /* 切换后后端生效 */ }} />
|
<SearchBarPlus
|
||||||
|
defaultCollapsed
|
||||||
|
split
|
||||||
|
span={8}
|
||||||
|
onTenantChanged={() => { /* 仅触发表格刷新 */ }}
|
||||||
|
onFinish={async (values) => setParams(values)}
|
||||||
|
/>
|
||||||
|
|
||||||
<ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} />
|
<ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} />
|
||||||
|
|
||||||
<GlassCard>
|
<GlassCard>
|
||||||
<ProTable<HomeCarouselItem>
|
<ProTable<HomeCarouselItem>
|
||||||
rowKey="id"
|
rowKey="id"
|
||||||
request={(p) => ordersApi.homeCarouselList(p as any)}
|
request={(p) => ordersApi.homeCarouselList({ ...(p as any), ...params })}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
search={false}
|
search={false}
|
||||||
pagination={{ showSizeChanger: true, showQuickJumper: true }}
|
pagination={{ showSizeChanger: true, showQuickJumper: true }}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { PageContainer } from '@ant-design/pro-components';
|
import { PageContainer } from '@ant-design/pro-components';
|
||||||
import { Card, Col, Row, Statistic, message, Button } from 'antd';
|
import { Card, Col, Row, Statistic, message, Button } from 'antd';
|
||||||
import TenantScopeFilter from '@/components/TenantScopeFilter';
|
import TenantScopeFilter from '@/components/TenantScopeFilter';
|
||||||
@@ -8,22 +8,23 @@ import { ActionBar } from '@/components/ui';
|
|||||||
const ProfitSharingStatisticsPage: React.FC = () => {
|
const ProfitSharingStatisticsPage: React.FC = () => {
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [stat, setStat] = useState<any>({});
|
const [stat, setStat] = useState<any>({});
|
||||||
|
const [scope, setScope] = useState<{ tenantId?: string; includeChildren?: boolean }>({});
|
||||||
|
|
||||||
const load = async () => {
|
const load = async (p?: any) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await ordersApi.getProfitSharingStatistics();
|
const res = await ordersApi.getProfitSharingStatistics(p);
|
||||||
setStat(res?.data || res);
|
setStat(res?.data || res);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
message.error('加载统计失败');
|
message.error('加载统计失败');
|
||||||
} finally { setLoading(false); }
|
} finally { setLoading(false); }
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => { load(); }, []);
|
useEffect(() => { load(scope); }, [scope]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageContainer header={{ title: '分账统计' }} extra={<TenantScopeFilter onChanged={() => load()} /> }>
|
<PageContainer header={{ title: '分账统计' }} extra={<TenantScopeFilter useSwitchTenant onChanged={(tid, inc) => setScope({ tenantId: tid, includeChildren: inc })} /> }>
|
||||||
<ActionBar right={<Button size="middle" onClick={() => load()}>刷新</Button>} />
|
<ActionBar right={<Button size="middle" onClick={() => load(scope)}>刷新</Button>} />
|
||||||
<Row gutter={16}>
|
<Row gutter={16}>
|
||||||
<Col span={6}><Card loading={loading}><Statistic title="总分账额" value={stat?.totalSharingAmount || 0} precision={2} /></Card></Col>
|
<Col span={6}><Card loading={loading}><Statistic title="总分账额" value={stat?.totalSharingAmount || 0} precision={2} /></Card></Col>
|
||||||
<Col span={6}><Card loading={loading}><Statistic title="分账笔数" value={stat?.sharingCount || 0} /></Card></Col>
|
<Col span={6}><Card loading={loading}><Statistic title="分账笔数" value={stat?.sharingCount || 0} /></Card></Col>
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ const QrcodePage: React.FC = () => {
|
|||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
const [editOpen, setEditOpen] = useState(false);
|
const [editOpen, setEditOpen] = useState(false);
|
||||||
const [current, setCurrent] = useState<QrcodeItem | undefined>(undefined);
|
const [current, setCurrent] = useState<QrcodeItem | undefined>(undefined);
|
||||||
|
const [params, setParams] = useState<Record<string, any>>({});
|
||||||
|
|
||||||
const columns: any[] = [
|
const columns: any[] = [
|
||||||
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
|
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
|
||||||
@@ -40,12 +41,18 @@ const QrcodePage: React.FC = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<PageContainer header={{ title: '二维码管理' }}>
|
<PageContainer header={{ title: '二维码管理' }}>
|
||||||
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => { /* 租户切换 */ }} />
|
<SearchBarPlus
|
||||||
|
defaultCollapsed
|
||||||
|
split
|
||||||
|
span={8}
|
||||||
|
onTenantChanged={() => { /* 仅触发表格刷新 */ }}
|
||||||
|
onFinish={async (values) => setParams(values)}
|
||||||
|
/>
|
||||||
<ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} />
|
<ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} />
|
||||||
<GlassCard>
|
<GlassCard>
|
||||||
<ProTable<QrcodeItem>
|
<ProTable<QrcodeItem>
|
||||||
rowKey="id"
|
rowKey="id"
|
||||||
request={(p) => ordersApi.qrcodeList(p as any)}
|
request={(p) => ordersApi.qrcodeList({ ...(p as any), ...params })}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
search={false}
|
search={false}
|
||||||
pagination={{ showSizeChanger: true, showQuickJumper: true }}
|
pagination={{ showSizeChanger: true, showQuickJumper: true }}
|
||||||
|
|||||||
@@ -31,8 +31,15 @@ const StatisticsPage: React.FC = () => {
|
|||||||
span={8}
|
span={8}
|
||||||
onTenantChanged={() => load(range)}
|
onTenantChanged={() => load(range)}
|
||||||
onFinish={async (values) => {
|
onFinish={async (values) => {
|
||||||
const v = values?.timeRange;
|
const v = (values as any)?.timeRange;
|
||||||
const r = v && v.length === 2 ? { startTime: v[0]?.toISOString(), endTime: v[1]?.toISOString() } : undefined;
|
const base: any = {};
|
||||||
|
if (v && v.length === 2) {
|
||||||
|
base.startTime = v[0]?.toISOString();
|
||||||
|
base.endTime = v[1]?.toISOString();
|
||||||
|
}
|
||||||
|
// 合并租户筛选参数
|
||||||
|
const r = { ...values, ...base } as any;
|
||||||
|
delete r.timeRange;
|
||||||
setRange(r);
|
setRange(r);
|
||||||
await load(r);
|
await load(r);
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { ModalForm, ProForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
|
import { ModalForm, ProForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
|
||||||
|
import TenantSelector from '@/components/ui/TenantSelector';
|
||||||
|
|
||||||
export interface TourismItem {
|
export interface TourismItem {
|
||||||
id?: number;
|
id?: number;
|
||||||
|
tenantId?: string;
|
||||||
tourismName?: string;
|
tourismName?: string;
|
||||||
address?: string;
|
tourismAddress?: string;
|
||||||
contactPerson?: string;
|
tourismPhone?: string;
|
||||||
contactPhone?: string;
|
status?: number; // 1 启用,0 禁用
|
||||||
status?: number;
|
longitude?: string;
|
||||||
|
latitude?: string;
|
||||||
|
showInHomepage?: number; // 1 是,0 否
|
||||||
description?: string;
|
description?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,14 +33,41 @@ const TourismForm: React.FC<TourismFormProps> = ({ open, title, initialValues, o
|
|||||||
initialValues={initialValues}
|
initialValues={initialValues}
|
||||||
modalProps={{ destroyOnClose: true }}
|
modalProps={{ destroyOnClose: true }}
|
||||||
>
|
>
|
||||||
|
{/* 所属租户(必选) */}
|
||||||
|
<TenantSelector nameTenant="tenantId" labelTenant="所属租户" hideIncludeChildren rulesTenant={[{ required: true, message: '请选择租户' }]} />
|
||||||
|
|
||||||
<ProFormText name="tourismName" label="景区名称" rules={[{ required: true, message: '请输入景区名称' }]} />
|
<ProFormText name="tourismName" label="景区名称" rules={[{ required: true, message: '请输入景区名称' }]} />
|
||||||
<ProFormText name="address" label="地址" />
|
<ProFormText name="tourismAddress" label="地址" />
|
||||||
<ProFormText name="contactPerson" label="联系人" />
|
<ProFormText name="tourismPhone" label="联系电话" />
|
||||||
<ProFormText name="contactPhone" label="联系电话" />
|
|
||||||
<ProFormSelect name="status" label="状态" valueEnum={{ 1: '启用', 0: '禁用' }} initialValue={1} />
|
<ProForm.Group>
|
||||||
|
<ProFormText name="longitude" label="经度" placeholder="例如 116.397128" />
|
||||||
|
<ProFormText name="latitude" label="纬度" placeholder="例如 39.916527" />
|
||||||
|
</ProForm.Group>
|
||||||
|
|
||||||
|
{/* 下拉中文,不显示数字 */}
|
||||||
|
<ProFormSelect
|
||||||
|
name="showInHomepage"
|
||||||
|
label="首页展示"
|
||||||
|
options={[
|
||||||
|
{ label: '是', value: 1 },
|
||||||
|
{ label: '否', value: 0 },
|
||||||
|
]}
|
||||||
|
initialValue={0}
|
||||||
|
/>
|
||||||
|
<ProFormSelect
|
||||||
|
name="status"
|
||||||
|
label="状态"
|
||||||
|
options={[
|
||||||
|
{ label: '启用', value: 1 },
|
||||||
|
{ label: '禁用', value: 0 },
|
||||||
|
]}
|
||||||
|
initialValue={1}
|
||||||
|
/>
|
||||||
<ProFormTextArea name="description" label="描述" />
|
<ProFormTextArea name="description" label="描述" />
|
||||||
</ModalForm>
|
</ModalForm>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default TourismForm;
|
export default TourismForm;
|
||||||
|
|
||||||
|
|||||||
@@ -1,56 +1,113 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { PageContainer, ProTable } from '@ant-design/pro-components';
|
import { PageContainer, ProFormText, ProTable } from '@ant-design/pro-components';
|
||||||
import { Popconfirm, Space, Tag, message } from 'antd';
|
import { Popconfirm, Space, Tag, message } from 'antd';
|
||||||
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
|
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
|
||||||
import { PlusOutlined } from '@ant-design/icons';
|
import { PlusOutlined } from '@ant-design/icons';
|
||||||
import { ordersApi } from '@/services/orders';
|
import { ordersApi } from '@/services/orders';
|
||||||
import TourismForm, { TourismItem } from './components/TourismForm';
|
import TourismForm, { TourismItem } from './components/TourismForm';
|
||||||
|
import { tenantApi } from '@/services/tenant';
|
||||||
|
|
||||||
const TourismPage: React.FC = () => {
|
const TourismPage: React.FC = () => {
|
||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
const [editOpen, setEditOpen] = useState(false);
|
const [editOpen, setEditOpen] = useState(false);
|
||||||
const [current, setCurrent] = useState<TourismItem | undefined>(undefined);
|
const [current, setCurrent] = useState<TourismItem | undefined>(undefined);
|
||||||
|
const [params, setParams] = useState<Record<string, any>>({});
|
||||||
|
|
||||||
|
// 首次进入时,默认按“当前租户 + 包含下级租户”查询,避免全量数据
|
||||||
|
useEffect(() => {
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
let tenantId: string | undefined;
|
||||||
|
const cur: any = await tenantApi.getCurrentTenant();
|
||||||
|
tenantId = cur?.data?.tenantId ?? cur?.tenantId;
|
||||||
|
if (!tenantId) {
|
||||||
|
const stats: any = await tenantApi.getScopeStats();
|
||||||
|
tenantId = stats?.data?.currentTenantId ?? stats?.currentTenantId;
|
||||||
|
}
|
||||||
|
if (tenantId) setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren: true }));
|
||||||
|
} catch {
|
||||||
|
// 忽略错误,保留手动查询能力
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}, []);
|
||||||
|
|
||||||
const columns: any[] = [
|
const columns: any[] = [
|
||||||
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
|
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
|
||||||
{ title: '旅游项目', dataIndex: 'tourismName' },
|
{ title: '旅游项目', dataIndex: 'tourismName' },
|
||||||
{ title: '地址', dataIndex: 'address' },
|
{ title: '地址', dataIndex: 'tourismAddress' },
|
||||||
{ title: '联系人', dataIndex: 'contactPerson' },
|
{ title: '经度', dataIndex: 'longitude' },
|
||||||
{ title: '联系电话', dataIndex: 'contactPhone' },
|
{ title: '纬度', dataIndex: 'latitude' },
|
||||||
{ title: '状态', dataIndex: 'status', render: (v: number) => <Tag color={v === 1 ? 'green' : 'default'}>{v === 1 ? '启用' : '禁用'}</Tag> },
|
|
||||||
{
|
{
|
||||||
title: '操作', key: 'action',
|
title: '首页展示',
|
||||||
|
dataIndex: 'showInHomepage',
|
||||||
|
render: (v: number) => <Tag color={v === 1 ? 'green' : 'default'}>{v === 1 ? '是' : '否'}</Tag>,
|
||||||
|
},
|
||||||
|
{ title: '联系电话', dataIndex: 'tourismPhone' },
|
||||||
|
{ title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime' },
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'status',
|
||||||
|
render: (v: number) => <Tag color={v === 1 ? 'green' : 'default'}>{v === 1 ? '启用' : '禁用'}</Tag>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
key: 'action',
|
||||||
render: (_: any, record: TourismItem) => (
|
render: (_: any, record: TourismItem) => (
|
||||||
<Space>
|
<Space>
|
||||||
<a onClick={() => { setCurrent(record); setEditOpen(true); }}>编辑</a>
|
<a onClick={() => { setCurrent(record); setEditOpen(true); }}>编辑</a>
|
||||||
<Popconfirm title={`确认删除项目[${record.tourismName}]?`} onConfirm={async () => {
|
<Popconfirm
|
||||||
const hide = message.loading('删除中...');
|
title={`确认删除项目[${record.tourismName}]?`}
|
||||||
try {
|
onConfirm={async () => {
|
||||||
await ordersApi.deleteTourism(record.id!);
|
const hide = message.loading('正在删除...');
|
||||||
message.success('删除成功');
|
try {
|
||||||
} catch (e) {
|
await ordersApi.deleteTourism(record.id!);
|
||||||
message.error('删除失败');
|
message.success('删除成功');
|
||||||
} finally { hide(); }
|
} catch {
|
||||||
}}>
|
message.error('删除失败');
|
||||||
|
} finally { hide(); }
|
||||||
|
}}
|
||||||
|
>
|
||||||
<a style={{ color: '#1677ff' }}>删除</a>
|
<a style={{ color: '#1677ff' }}>删除</a>
|
||||||
</Popconfirm>
|
</Popconfirm>
|
||||||
</Space>
|
</Space>
|
||||||
)
|
),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageContainer header={{ title: '旅游项目' }}>
|
<PageContainer header={{ title: '旅游项目' }}>
|
||||||
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => { /* 租户切换 */ }} />
|
<SearchBarPlus
|
||||||
<ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} />
|
defaultCollapsed
|
||||||
|
split
|
||||||
|
span={8}
|
||||||
|
onTenantChanged={(tenantId, includeChildren) => {
|
||||||
|
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren }));
|
||||||
|
}}
|
||||||
|
onFinish={async (values) => setParams(values)}
|
||||||
|
>
|
||||||
|
<ProFormText name="tourismName" label="景区名称" placeholder="请输入景区名称" />
|
||||||
|
</SearchBarPlus>
|
||||||
|
|
||||||
|
<ActionBar
|
||||||
|
left={
|
||||||
|
<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>
|
||||||
|
新增
|
||||||
|
</GradientButton>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
<GlassCard>
|
<GlassCard>
|
||||||
<ProTable<TourismItem>
|
{params?.tenantId ? (
|
||||||
rowKey="id"
|
<ProTable<TourismItem>
|
||||||
request={(p) => ordersApi.tourism(p as any)}
|
rowKey="id"
|
||||||
columns={columns}
|
params={params}
|
||||||
search={false}
|
request={(p) => ordersApi.tourism({ ...(p as any), ...params })}
|
||||||
pagination={{ showSizeChanger: true, showQuickJumper: true }}
|
columns={columns}
|
||||||
/>
|
search={false}
|
||||||
|
pagination={{ showSizeChanger: true, showQuickJumper: true }}
|
||||||
|
toolBarRender={false}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
</GlassCard>
|
</GlassCard>
|
||||||
|
|
||||||
<TourismForm
|
<TourismForm
|
||||||
@@ -63,8 +120,8 @@ const TourismPage: React.FC = () => {
|
|||||||
await ordersApi.saveOrUpdateTourism(values);
|
await ordersApi.saveOrUpdateTourism(values);
|
||||||
message.success('新增成功');
|
message.success('新增成功');
|
||||||
return true;
|
return true;
|
||||||
} catch (e) {
|
} catch {
|
||||||
message.error('保存失败');
|
message.error('新增失败');
|
||||||
return false;
|
return false;
|
||||||
} finally { hide(); }
|
} finally { hide(); }
|
||||||
}}
|
}}
|
||||||
@@ -81,7 +138,7 @@ const TourismPage: React.FC = () => {
|
|||||||
await ordersApi.saveOrUpdateTourism({ ...(current as any), ...values });
|
await ordersApi.saveOrUpdateTourism({ ...(current as any), ...values });
|
||||||
message.success('修改成功');
|
message.success('修改成功');
|
||||||
return true;
|
return true;
|
||||||
} catch (e) {
|
} catch {
|
||||||
message.error('修改失败');
|
message.error('修改失败');
|
||||||
return false;
|
return false;
|
||||||
} finally { hide(); }
|
} finally { hide(); }
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { useCallback, useEffect, useState } from 'react';
|
import React, { useCallback, useEffect, useState } from 'react';
|
||||||
import { PageContainer, ProFormText, ProFormSelect } from '@ant-design/pro-components';
|
import { PageContainer } from '@ant-design/pro-components';
|
||||||
import { Space, message } from 'antd';
|
import { Space, message } from 'antd';
|
||||||
import { ActionBar, GradientButton, GlassCard, SearchBarPlus } from '@/components/ui';
|
import { ActionBar, GradientButton, GlassCard } from '@/components/ui';
|
||||||
import { PlusOutlined } from '@ant-design/icons';
|
import { PlusOutlined } from '@ant-design/icons';
|
||||||
import MenuTree from './components/MenuTree';
|
import MenuTree from './components/MenuTree';
|
||||||
import MenuForm from './components/MenuForm';
|
import MenuForm from './components/MenuForm';
|
||||||
@@ -10,19 +10,17 @@ import { roleApi } from '@/services/role';
|
|||||||
import { buildTree } from '@/utils/tree';
|
import { buildTree } from '@/utils/tree';
|
||||||
|
|
||||||
const MenuPage: React.FC = () => {
|
const MenuPage: React.FC = () => {
|
||||||
const [apps, setApps] = useState<any[]>([]);
|
const [keyword] = useState<string | undefined>(undefined);
|
||||||
const [tenantId, setTenantId] = useState<string | undefined>();
|
|
||||||
const [keyword, setKeyword] = useState<string | undefined>();
|
|
||||||
const [data, setData] = useState<MenuItem[]>([]);
|
const [data, setData] = useState<MenuItem[]>([]);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
const [editOpen, setEditOpen] = useState(false);
|
const [editOpen, setEditOpen] = useState(false);
|
||||||
const [current, setCurrent] = useState<MenuItem | undefined>(undefined);
|
const [current, setCurrent] = useState<MenuItem | undefined>(undefined);
|
||||||
|
|
||||||
const fetchMenu = useCallback(async (clientId: string) => {
|
const fetchMenu = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const menus = await menuApi.list(clientId);
|
const menus = await menuApi.list();
|
||||||
const list: any[] = menus || [];
|
const list: any[] = menus || [];
|
||||||
const hasSubMenus = list.some((m) => Array.isArray(m?.subMenus));
|
const hasSubMenus = list.some((m) => Array.isArray(m?.subMenus));
|
||||||
if (hasSubMenus) {
|
if (hasSubMenus) {
|
||||||
@@ -57,24 +55,14 @@ const MenuPage: React.FC = () => {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => { fetchMenu(); }, [fetchMenu]);
|
||||||
(async () => {
|
|
||||||
const list = await roleApi.apps();
|
|
||||||
setApps(list || []);
|
|
||||||
if (list?.length) {
|
|
||||||
const id = list[0].clientId;
|
|
||||||
setTenantId(id);
|
|
||||||
fetchMenu(id);
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
}, [fetchMenu]);
|
|
||||||
|
|
||||||
const handleDelete = async (record: MenuItem) => {
|
const handleDelete = async (record: MenuItem) => {
|
||||||
const hide = message.loading('删除中...');
|
const hide = message.loading('鍒犻櫎涓?..');
|
||||||
try {
|
try {
|
||||||
await menuApi.delete(record.id!);
|
await menuApi.delete(record.id!);
|
||||||
message.success('鍒犻櫎鑿滃崟鎴愬姛');
|
message.success('鍒犻櫎鑿滃崟鎴愬姛');
|
||||||
if (tenantId) fetchMenu(tenantId);
|
fetchMenu();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
message.error('鍒犻櫎鑿滃崟澶辫触');
|
message.error('鍒犻櫎鑿滃崟澶辫触');
|
||||||
} finally { hide(); }
|
} finally { hide(); }
|
||||||
@@ -82,16 +70,7 @@ const MenuPage: React.FC = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<PageContainer header={{ title: '鑿滃崟绠$悊' }}>
|
<PageContainer header={{ title: '鑿滃崟绠$悊' }}>
|
||||||
<SearchBarPlus
|
{/* 去掉查询条件(租户/所属应用),默认查询当前登录人所属租户 */}
|
||||||
defaultCollapsed
|
|
||||||
split
|
|
||||||
span={8}
|
|
||||||
onTenantChanged={() => tenantId && fetchMenu(tenantId)}
|
|
||||||
onFinish={async (values: any) => { setTenantId(values.tenantId); fetchMenu(values.tenantId); setKeyword(values.keyword); }}
|
|
||||||
>
|
|
||||||
<ProFormSelect name="tenantId" label="所属应用" allowClear={false} options={(apps || []).map((i) => ({ label: i.clientId, value: i.clientId }))} />
|
|
||||||
<ProFormText name="keyword" label="关键字" placeholder="菜单名称关键字" />
|
|
||||||
</SearchBarPlus>
|
|
||||||
|
|
||||||
<ActionBar
|
<ActionBar
|
||||||
left={
|
left={
|
||||||
@@ -116,11 +95,11 @@ const MenuPage: React.FC = () => {
|
|||||||
open={createOpen}
|
open={createOpen}
|
||||||
onOpenChange={setCreateOpen}
|
onOpenChange={setCreateOpen}
|
||||||
onFinish={async (values) => {
|
onFinish={async (values) => {
|
||||||
const hide = message.loading('保存中...');
|
const hide = message.loading('淇濆瓨涓?..');
|
||||||
try {
|
try {
|
||||||
await menuApi.saveOrUpdate(values);
|
await menuApi.saveOrUpdate(values);
|
||||||
message.success('鏂板�鑿滃崟鎴愬姛');
|
message.success('鏂板�鑿滃崟鎴愬姛');
|
||||||
tenantId && fetchMenu(tenantId);
|
fetchMenu();
|
||||||
return true;
|
return true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
message.error('鏂板�鑿滃崟澶辫触');
|
message.error('鏂板�鑿滃崟澶辫触');
|
||||||
@@ -135,11 +114,11 @@ const MenuPage: React.FC = () => {
|
|||||||
initialValues={current}
|
initialValues={current}
|
||||||
onOpenChange={setEditOpen}
|
onOpenChange={setEditOpen}
|
||||||
onFinish={async (values) => {
|
onFinish={async (values) => {
|
||||||
const hide = message.loading('保存中...');
|
const hide = message.loading('淇濆瓨涓?..');
|
||||||
try {
|
try {
|
||||||
await menuApi.saveOrUpdate({ ...current, ...values });
|
await menuApi.saveOrUpdate({ ...current, ...values });
|
||||||
message.success('淇�敼鑿滃崟鎴愬姛');
|
message.success('淇�敼鑿滃崟鎴愬姛');
|
||||||
tenantId && fetchMenu(tenantId);
|
fetchMenu();
|
||||||
return true;
|
return true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
message.error('淇�敼鑿滃崟澶辫触');
|
message.error('淇�敼鑿滃崟澶辫触');
|
||||||
@@ -153,3 +132,5 @@ const MenuPage: React.FC = () => {
|
|||||||
|
|
||||||
export default MenuPage;
|
export default MenuPage;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { ModalForm, ProForm, ProFormRadio, ProFormText } from '@ant-design/pro-components';
|
import { ModalForm, ProForm, ProFormRadio, ProFormText } from '@ant-design/pro-components';
|
||||||
|
import TenantSelector from '@/components/ui/TenantSelector';
|
||||||
import { RoleItem } from '@/services/role';
|
import { RoleItem } from '@/services/role';
|
||||||
|
|
||||||
export interface RoleFormProps {
|
export interface RoleFormProps {
|
||||||
@@ -22,13 +23,14 @@ const RoleForm: React.FC<RoleFormProps> = ({ open, title, initialValues, onOpenC
|
|||||||
width={500}
|
width={500}
|
||||||
>
|
>
|
||||||
<ProForm.Group>
|
<ProForm.Group>
|
||||||
|
<TenantSelector hideIncludeChildren rulesTenant={[{ required: true, message: '请选择所属租户' }]} />
|
||||||
<ProFormText name="name" label="角色名称" rules={[{ required: true, message: '角色名不能为空' }]} width="lg" />
|
<ProFormText name="name" label="角色名称" rules={[{ required: true, message: '角色名不能为空' }]} width="lg" />
|
||||||
<ProFormText name="code" label="编码" rules={[{ required: true, message: '编码不能为空' }]} width="lg" />
|
<ProFormText name="code" label="编码" rules={[{ required: true, message: '编码不能为空' }]} width="lg" />
|
||||||
<ProFormRadio.Group
|
<ProFormRadio.Group
|
||||||
name="dataScope"
|
name="dataScope"
|
||||||
label="数据权限"
|
label="数据权限"
|
||||||
width="lg"
|
width="lg"
|
||||||
options={[{ label: '全部', value: 'ALL' }, { label: '本人', value: 'CREATOR' }]}
|
options={[{ label: '全部', value: 'ALL' }, { label: '自定义', value: 'CREATOR' }]}
|
||||||
/>
|
/>
|
||||||
</ProForm.Group>
|
</ProForm.Group>
|
||||||
</ModalForm>
|
</ModalForm>
|
||||||
@@ -36,3 +38,4 @@ const RoleForm: React.FC<RoleFormProps> = ({ open, title, initialValues, onOpenC
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default RoleForm;
|
export default RoleForm;
|
||||||
|
|
||||||
|
|||||||
@@ -4,30 +4,22 @@ import { Popconfirm, Space, message } from 'antd';
|
|||||||
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
|
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
|
||||||
import { PlusOutlined } from '@ant-design/icons';
|
import { PlusOutlined } from '@ant-design/icons';
|
||||||
import { roleApi, RoleItem } from '@/services/role';
|
import { roleApi, RoleItem } from '@/services/role';
|
||||||
|
import { tenantApi } from '@/services/tenant';
|
||||||
import RoleForm from './components/RoleForm';
|
import RoleForm from './components/RoleForm';
|
||||||
import AssignAuth from './components/AssignAuth';
|
import AssignAuth from './components/AssignAuth';
|
||||||
|
|
||||||
const RolePage: React.FC = () => {
|
const RolePage: React.FC = () => {
|
||||||
const [apps, setApps] = useState<any[]>([]);
|
const [params, setParams] = useState<{ tenantId?: string; includeChildren?: boolean; searchKey?: string; searchValue?: string }>({});
|
||||||
const [params, setParams] = useState<{ tenantId?: string; searchKey?: string; searchValue?: string }>({});
|
|
||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
const [editOpen, setEditOpen] = useState(false);
|
const [editOpen, setEditOpen] = useState(false);
|
||||||
const [assignOpen, setAssignOpen] = useState(false);
|
const [assignOpen, setAssignOpen] = useState(false);
|
||||||
const [current, setCurrent] = useState<RoleItem | undefined>(undefined);
|
const [current, setCurrent] = useState<RoleItem | undefined>(undefined);
|
||||||
|
|
||||||
useEffect(() => {
|
// 以租户为主:通过 SearchBarPlus 内置租户选择器
|
||||||
(async () => {
|
|
||||||
const list = await roleApi.apps();
|
|
||||||
setApps(list || []);
|
|
||||||
if (list?.length) {
|
|
||||||
const tenantId = list[0].clientId;
|
|
||||||
setParams((p) => ({ ...p, tenantId }));
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const columns = [
|
const columns = [
|
||||||
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
|
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
|
||||||
|
{ title: '租户', dataIndex: 'tenantId', width: 160, search: false, render: (_: any, r: RoleItem) => (r as any)?.tenantName || (r as any)?.tenantId || '-' },
|
||||||
{ title: 'ID', dataIndex: 'id' },
|
{ title: 'ID', dataIndex: 'id' },
|
||||||
{ title: '角色名称', dataIndex: 'name' },
|
{ title: '角色名称', dataIndex: 'name' },
|
||||||
{ title: '编码', dataIndex: 'code' },
|
{ title: '编码', dataIndex: 'code' },
|
||||||
@@ -54,16 +46,37 @@ const RolePage: React.FC = () => {
|
|||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// 页面初次进入时,自动获取当前租户并触发表格请求
|
||||||
|
useEffect(() => {
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
let tenantId: string | undefined;
|
||||||
|
const cur: any = await tenantApi.getCurrentTenant();
|
||||||
|
tenantId = cur?.data?.tenantId ?? cur?.tenantId;
|
||||||
|
if (!tenantId) {
|
||||||
|
const stats: any = await tenantApi.getScopeStats();
|
||||||
|
tenantId = stats?.data?.currentTenantId ?? stats?.currentTenantId;
|
||||||
|
}
|
||||||
|
if (tenantId) {
|
||||||
|
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren: true }));
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// 忽略错误,保持手动查询可用
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageContainer header={{ title: '角色管理' }}>
|
<PageContainer header={{ title: '角色管理' }}>
|
||||||
<SearchBarPlus
|
<SearchBarPlus
|
||||||
defaultCollapsed={false}
|
defaultCollapsed={false}
|
||||||
split
|
split
|
||||||
span={6}
|
span={6}
|
||||||
onTenantChanged={() => { /* 切换租户后服务端上下文生效 */ }}
|
onTenantChanged={(tenantId, includeChildren) => {
|
||||||
|
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren }));
|
||||||
|
}}
|
||||||
onFinish={async (values) => setParams(values)}
|
onFinish={async (values) => setParams(values)}
|
||||||
>
|
>
|
||||||
<ProFormSelect name="tenantId" label="所属应用" allowClear={false} options={(apps || []).map((i) => ({ label: i.clientId, value: i.clientId }))} />
|
|
||||||
<ProFormSelect name="searchKey" label="搜索" valueEnum={{ name: '角色名称' }} />
|
<ProFormSelect name="searchKey" label="搜索" valueEnum={{ name: '角色名称' }} />
|
||||||
<ProFormText name="searchValue" placeholder="请输入关键字" />
|
<ProFormText name="searchValue" placeholder="请输入关键字" />
|
||||||
</SearchBarPlus>
|
</SearchBarPlus>
|
||||||
@@ -80,6 +93,7 @@ const RolePage: React.FC = () => {
|
|||||||
<ProTable<RoleItem>
|
<ProTable<RoleItem>
|
||||||
rowKey="id"
|
rowKey="id"
|
||||||
headerTitle="角色列表"
|
headerTitle="角色列表"
|
||||||
|
params={params}
|
||||||
request={async (p) => roleApi.page({ ...p, ...params })}
|
request={async (p) => roleApi.page({ ...p, ...params })}
|
||||||
columns={columns as any}
|
columns={columns as any}
|
||||||
search={false}
|
search={false}
|
||||||
@@ -134,4 +148,3 @@ const RolePage: React.FC = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default RolePage;
|
export default RolePage;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import React, { useEffect, useMemo, useState } from 'react';
|
||||||
|
import { ModalForm, ProForm, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
|
||||||
|
import { Select, Switch, TreeSelect } from 'antd';
|
||||||
|
import type { TenantInfo, TenantTreeNode } from '@/services/tenant';
|
||||||
|
import { tenantApi } from '@/services/tenant';
|
||||||
|
|
||||||
|
type UITenantFormValues = Partial<TenantInfo> & { status?: boolean | number };
|
||||||
|
|
||||||
|
export interface TenantFormProps {
|
||||||
|
visible: boolean;
|
||||||
|
title: string;
|
||||||
|
initialValues?: UITenantFormValues;
|
||||||
|
tree: TenantTreeNode[];
|
||||||
|
onVisibleChange: (v: boolean) => void;
|
||||||
|
onFinish: (values: TenantInfo) => Promise<boolean>;
|
||||||
|
form?: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
const toTreeData = (nodes?: TenantTreeNode[] | any): any[] => {
|
||||||
|
const arr: TenantTreeNode[] = Array.isArray(nodes) ? nodes : [];
|
||||||
|
return arr.map((n) => ({
|
||||||
|
title: n.tenantName,
|
||||||
|
value: n.tenantId,
|
||||||
|
key: n.tenantId,
|
||||||
|
children: Array.isArray((n as any).children) && (n as any).children!.length ? toTreeData((n as any).children) : undefined,
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const TenantForm: React.FC<TenantFormProps> = ({ visible, title, initialValues, tree, onVisibleChange, onFinish, form }) => {
|
||||||
|
const editing = !!initialValues?.tenantId;
|
||||||
|
const [allowedTypes, setAllowedTypes] = useState<string[] | undefined>(undefined);
|
||||||
|
|
||||||
|
const typeOrder = useMemo(() => ['PLATFORM', 'GROUP', 'COMPANY', 'DEPARTMENT'], []);
|
||||||
|
const allTypeOptions = useMemo(() => ([
|
||||||
|
{ value: 'PLATFORM', label: '平台' },
|
||||||
|
{ value: 'GROUP', label: '集团' },
|
||||||
|
{ value: 'COMPANY', label: '公司' },
|
||||||
|
{ value: 'DEPARTMENT', label: '部门' },
|
||||||
|
]), []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
(async () => {
|
||||||
|
if (!editing && initialValues?.parentTenantId) {
|
||||||
|
try {
|
||||||
|
const pd = await tenantApi.getTenantDetailStd(initialValues.parentTenantId);
|
||||||
|
const pType = pd?.data?.tenantType as string | undefined;
|
||||||
|
if (pType) {
|
||||||
|
const idx = typeOrder.indexOf(pType);
|
||||||
|
const allowed = idx >= 0 ? typeOrder.slice(idx + 1) : typeOrder;
|
||||||
|
setAllowedTypes(allowed);
|
||||||
|
const cur = form?.getFieldValue?.('tenantType');
|
||||||
|
if (!cur && allowed.length) form?.setFieldsValue?.({ tenantType: allowed[0] });
|
||||||
|
} else {
|
||||||
|
setAllowedTypes(typeOrder);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setAllowedTypes(typeOrder);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
setAllowedTypes(typeOrder);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [visible, editing, initialValues?.parentTenantId]);
|
||||||
|
|
||||||
|
const safeInitialValues = useMemo(() => {
|
||||||
|
const iv: any = initialValues || {};
|
||||||
|
const s = iv.status;
|
||||||
|
const statusNum = typeof s === 'boolean' ? (s ? 1 : 0) : s;
|
||||||
|
return { ...iv, status: statusNum };
|
||||||
|
}, [initialValues]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ModalForm<TenantInfo>
|
||||||
|
title={title}
|
||||||
|
visible={visible}
|
||||||
|
onVisibleChange={onVisibleChange}
|
||||||
|
onFinish={onFinish}
|
||||||
|
initialValues={safeInitialValues}
|
||||||
|
form={form}
|
||||||
|
width={640}
|
||||||
|
modalProps={{ destroyOnClose: true, maskClosable: false }}
|
||||||
|
>
|
||||||
|
<ProForm.Group>
|
||||||
|
<ProFormText name='tenantId' label='租户ID' placeholder='唯一标识,创建后不可修改' rules={[{ required: true, message: '请输入租户ID' }]} disabled={editing} />
|
||||||
|
<ProFormText name='tenantName' label='租户名称' rules={[{ required: true, message: '请输入租户名称' }]} />
|
||||||
|
</ProForm.Group>
|
||||||
|
<ProForm.Group>
|
||||||
|
<ProForm.Item name='parentTenantId' label='上级租户'>
|
||||||
|
<TreeSelect style={{ width: 260 }} allowClear dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} treeDefaultExpandAll treeData={toTreeData(tree)} placeholder='选择上级租户' disabled={editing} />
|
||||||
|
</ProForm.Item>
|
||||||
|
<ProForm.Item name='tenantType' label='类型' rules={[{ required: true, message: '请选择类型' }]}>
|
||||||
|
<Select style={{ width: 260 }} placeholder='选择类型' disabled={editing && !initialValues?.parentTenantId}>
|
||||||
|
{(allowedTypes || typeOrder).map((t) => (
|
||||||
|
<Select.Option key={t} value={t}>{(allTypeOptions.find((x) => x.value === t)?.label) || t}</Select.Option>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</ProForm.Item>
|
||||||
|
</ProForm.Group>
|
||||||
|
<ProForm.Group>
|
||||||
|
<ProFormText name='tenantCode' label='编码' />
|
||||||
|
<ProForm.Item name='status' label='状态' valuePropName='checked' tooltip='启用/停用'>
|
||||||
|
<Switch checkedChildren='启用' unCheckedChildren='停用' />
|
||||||
|
</ProForm.Item>
|
||||||
|
</ProForm.Group>
|
||||||
|
<ProForm.Group>
|
||||||
|
<ProFormText name='contactPerson' label='联系人' />
|
||||||
|
<ProFormText name='contactPhone' label='联系电话' />
|
||||||
|
</ProForm.Group>
|
||||||
|
<ProFormText name='address' label='地址' />
|
||||||
|
<ProFormTextArea name='description' label='描述' />
|
||||||
|
</ModalForm>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default TenantForm;
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import type { ActionType, ProColumns } from '@ant-design/pro-components';
|
||||||
|
import { ProTable } from '@ant-design/pro-components';
|
||||||
|
import { message, Popconfirm, Space } from 'antd';
|
||||||
|
import type { TenantInfo } from '@/services/tenant';
|
||||||
|
import { tenantApi } from '@/services/tenant';
|
||||||
|
|
||||||
|
export interface TenantTableProps {
|
||||||
|
parentTenantId?: string;
|
||||||
|
actionRef?: React.MutableRefObject<ActionType | undefined>;
|
||||||
|
onEdit: (record: TenantInfo) => Promise<void> | void;
|
||||||
|
onDeleted?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TenantTable: React.FC<TenantTableProps> = ({ parentTenantId, actionRef, onEdit, onDeleted }) => {
|
||||||
|
const columns: ProColumns<TenantInfo>[] = [
|
||||||
|
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
|
||||||
|
{ title: '租户ID', dataIndex: 'tenantId', copyable: true, ellipsis: true, width: 160 },
|
||||||
|
{ title: '租户名称', dataIndex: 'tenantName' },
|
||||||
|
{ title: '类型', dataIndex: 'tenantType', valueType: 'select', valueEnum: { PLATFORM: { text: '平台' }, GROUP: { text: '集团' }, COMPANY: { text: '公司' }, DEPARTMENT: { text: '部门' } } },
|
||||||
|
{ title: '父租户ID', dataIndex: 'parentTenantId', hideInSearch: true, width: 160 },
|
||||||
|
{ title: '层级', dataIndex: 'tenantLevel', hideInSearch: true, width: 80 },
|
||||||
|
{ title: '编码', dataIndex: 'tenantCode', hideInSearch: true },
|
||||||
|
{ title: '状态', dataIndex: 'status', valueType: 'select', valueEnum: { 1: { text: '启用' }, 0: { text: '停用' } } },
|
||||||
|
{ title: '联系人', dataIndex: 'contactPerson', hideInSearch: true },
|
||||||
|
{ title: '联系电话', dataIndex: 'contactPhone', hideInSearch: true },
|
||||||
|
{
|
||||||
|
title: '操作', valueType: 'option', width: 200,
|
||||||
|
render: (_, record) => (
|
||||||
|
<Space>
|
||||||
|
<a onClick={() => onEdit(record)}>编辑</a>
|
||||||
|
<Popconfirm title={`确认删除租户[${record.tenantName}]?`} onConfirm={async () => {
|
||||||
|
const hide = message.loading('删除中...');
|
||||||
|
try {
|
||||||
|
const r = await tenantApi.deleteTenant(record.tenantId);
|
||||||
|
if ((r as any)?.success) {
|
||||||
|
message.success('删除成功');
|
||||||
|
actionRef?.current?.reload?.();
|
||||||
|
onDeleted?.();
|
||||||
|
} else {
|
||||||
|
message.error(((r as any)?.msg) || '删除失败');
|
||||||
|
}
|
||||||
|
} finally { hide(); }
|
||||||
|
}}>
|
||||||
|
<a style={{ color: '#ff4d4f' }}>删除</a>
|
||||||
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ProTable<TenantInfo>
|
||||||
|
actionRef={actionRef as any}
|
||||||
|
rowKey="tenantId"
|
||||||
|
columns={columns}
|
||||||
|
toolBarRender={false}
|
||||||
|
request={async (p) => {
|
||||||
|
const res = await tenantApi.getTenantList({ parentTenantId, tenantName: (p as any).tenantName, status: (p as any).status as any, current: (p as any).current, pageSize: (p as any).pageSize });
|
||||||
|
const list = (res as any)?.data?.data || [];
|
||||||
|
const total = (res as any)?.data?.total || list.length;
|
||||||
|
return { data: list, total, success: true };
|
||||||
|
}}
|
||||||
|
pagination={{ pageSize: 10 }}
|
||||||
|
search={{ labelWidth: 'auto' }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default TenantTable;
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import React, { useMemo, useState } from 'react';
|
||||||
|
import { Button, Card, Input, Space, Tree } from 'antd';
|
||||||
|
import type { DataNode } from 'antd/es/tree';
|
||||||
|
import { ReloadOutlined } from '@ant-design/icons';
|
||||||
|
import type { TenantTreeNode } from '@/services/tenant';
|
||||||
|
|
||||||
|
export interface TenantTreeProps {
|
||||||
|
title?: React.ReactNode;
|
||||||
|
loading?: boolean;
|
||||||
|
tree: TenantTreeNode[];
|
||||||
|
value?: string;
|
||||||
|
onChange?: (tenantId?: string) => void;
|
||||||
|
onReload?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const toTreeData = (nodes?: TenantTreeNode[] | any): DataNode[] => {
|
||||||
|
const arr: TenantTreeNode[] = Array.isArray(nodes) ? nodes : [];
|
||||||
|
return arr.map((n) => ({
|
||||||
|
title: n.tenantName,
|
||||||
|
key: n.tenantId,
|
||||||
|
value: n.tenantId,
|
||||||
|
children: Array.isArray((n as any).children) && (n as any).children!.length ? toTreeData((n as any).children) : undefined,
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const filterTree = (nodes?: TenantTreeNode[] | any, keyword: string = ''): TenantTreeNode[] => {
|
||||||
|
const arr: TenantTreeNode[] = Array.isArray(nodes) ? nodes : [];
|
||||||
|
if (!keyword) return arr;
|
||||||
|
const kw = keyword.trim().toLowerCase();
|
||||||
|
const loop = (arr: TenantTreeNode[]): TenantTreeNode[] =>
|
||||||
|
arr.map((n) => ({ ...n, children: n.children ? loop(n.children) : undefined }))
|
||||||
|
.filter((n) => {
|
||||||
|
const selfHit = String(n.tenantName || '').toLowerCase().includes(kw);
|
||||||
|
const childHit = (n.children || []).length > 0;
|
||||||
|
return selfHit || childHit;
|
||||||
|
});
|
||||||
|
return loop(arr);
|
||||||
|
};
|
||||||
|
|
||||||
|
const TenantTree: React.FC<TenantTreeProps> = ({ title = '组织', loading, tree, onChange, onReload }) => {
|
||||||
|
const [keyword, setKeyword] = useState('');
|
||||||
|
const displayTree = useMemo(() => filterTree(tree, keyword), [tree, keyword]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card
|
||||||
|
size="small"
|
||||||
|
title={title}
|
||||||
|
extra={(
|
||||||
|
<Space size={8}>
|
||||||
|
<Input.Search
|
||||||
|
allowClear
|
||||||
|
placeholder="搜索租户"
|
||||||
|
size="small"
|
||||||
|
style={{ width: 160 }}
|
||||||
|
value={keyword}
|
||||||
|
onChange={(e) => setKeyword(e.target.value)}
|
||||||
|
/>
|
||||||
|
<Button size="small" icon={<ReloadOutlined />} loading={!!loading} onClick={onReload}>刷新</Button>
|
||||||
|
</Space>
|
||||||
|
)}
|
||||||
|
bodyStyle={{ height: 'calc(70vh - 24px)', overflow: 'auto' }}
|
||||||
|
>
|
||||||
|
<Tree
|
||||||
|
treeData={toTreeData(displayTree)}
|
||||||
|
defaultExpandAll
|
||||||
|
onSelect={(keys) => onChange?.((keys?.[0] as string) || undefined)}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default TenantTree;
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import React, { useEffect, useMemo, useState } from 'react';
|
||||||
|
import { Table, Space, Popconfirm, Tag } from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import type { TenantTreeNode } from '@/services/tenant';
|
||||||
|
|
||||||
|
export interface TenantTreeTableProps {
|
||||||
|
data: TenantTreeNode[];
|
||||||
|
loading?: boolean;
|
||||||
|
onAddChild?: (record: TenantTreeNode) => void;
|
||||||
|
onEdit?: (record: TenantTreeNode) => void;
|
||||||
|
onDelete?: (record: TenantTreeNode) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TenantTreeTable: React.FC<TenantTreeTableProps> = ({ data, loading, onAddChild, onEdit, onDelete }) => {
|
||||||
|
const normalize = (nodes?: any[]): any[] => {
|
||||||
|
if (!Array.isArray(nodes)) return [];
|
||||||
|
return nodes.map((n: any) => ({
|
||||||
|
...n,
|
||||||
|
children: Array.isArray(n?.children) && n.children.length ? normalize(n.children) : undefined,
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
const safeData = useMemo(() => normalize(data as any), [data]);
|
||||||
|
|
||||||
|
// 计算并控制展开行,保证“默认展开”在异步数据加载后仍生效
|
||||||
|
const allExpandableKeys = useMemo(() => {
|
||||||
|
const keys: React.Key[] = [];
|
||||||
|
const walk = (arr?: any[]) => {
|
||||||
|
if (!Array.isArray(arr)) return;
|
||||||
|
for (const n of arr) {
|
||||||
|
const hasChildren = Array.isArray(n?.children) && n.children.length > 0;
|
||||||
|
if (hasChildren) keys.push(n.tenantId);
|
||||||
|
if (hasChildren) walk(n.children);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(safeData);
|
||||||
|
return keys;
|
||||||
|
}, [safeData]);
|
||||||
|
|
||||||
|
const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]);
|
||||||
|
useEffect(() => {
|
||||||
|
// 仅当列表 keys 实际发生变化时才更新,避免无意义的重复 setState
|
||||||
|
setExpandedRowKeys((prev) => {
|
||||||
|
const a = allExpandableKeys;
|
||||||
|
if (prev.length === a.length && prev.every((v, i) => v === a[i])) return prev;
|
||||||
|
return a;
|
||||||
|
});
|
||||||
|
}, [allExpandableKeys]);
|
||||||
|
|
||||||
|
const columns: ColumnsType<TenantTreeNode> = [
|
||||||
|
{
|
||||||
|
title: '租户名称',
|
||||||
|
dataIndex: 'tenantName',
|
||||||
|
render: (_: any, record: TenantTreeNode) => <span>{record.tenantName}</span>,
|
||||||
|
},
|
||||||
|
{ title: '租户ID', dataIndex: 'tenantId', width: 180, ellipsis: true },
|
||||||
|
{
|
||||||
|
title: '类型', dataIndex: 'tenantType', width: 120,
|
||||||
|
render: (v: any) => {
|
||||||
|
const map: Record<string, { color: string; text: string }> = {
|
||||||
|
PLATFORM: { color: 'purple', text: '平台' },
|
||||||
|
GROUP: { color: 'cyan', text: '集团' },
|
||||||
|
COMPANY: { color: 'blue', text: '公司' },
|
||||||
|
DEPARTMENT: { color: 'geekblue', text: '部门' },
|
||||||
|
};
|
||||||
|
const m = map[String(v)] || { color: 'default', text: String(v || '-') } as any;
|
||||||
|
return <Tag color={m.color}>{m.text}</Tag>;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '状态', dataIndex: 'status', width: 100,
|
||||||
|
render: (v: any, record: TenantTreeNode) => {
|
||||||
|
const enabled = typeof v === 'boolean' ? v : (v === 1 || v === '1' || (record as any)?.enabled === true || v == null);
|
||||||
|
return enabled ? <Tag color='green'>启用</Tag> : <Tag color='red'>停用</Tag>;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ title: '联系人', dataIndex: 'contactPerson', width: 120 },
|
||||||
|
{ title: '联系电话', dataIndex: 'contactPhone', width: 140 },
|
||||||
|
{
|
||||||
|
title: '操作', key: 'action', width: 220,
|
||||||
|
render: (_: any, rec: TenantTreeNode | undefined) => {
|
||||||
|
const record = (rec || ({} as TenantTreeNode));
|
||||||
|
const hasId = !!(record as any)?.tenantId;
|
||||||
|
return (
|
||||||
|
<Space>
|
||||||
|
<a onClick={() => hasId && onEdit?.(record)}>编辑</a>
|
||||||
|
{onAddChild ? <a onClick={() => hasId && onAddChild?.(record)}>新增下级</a> : null}
|
||||||
|
<Popconfirm title={`确认删除租户[${record?.tenantName ?? ''}]?`} onConfirm={() => hasId && onDelete?.(record)}>
|
||||||
|
<a style={{ color: '#1677ff' }}>删除</a>
|
||||||
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Table
|
||||||
|
rowKey='tenantId'
|
||||||
|
columns={columns}
|
||||||
|
dataSource={safeData as any}
|
||||||
|
loading={loading}
|
||||||
|
pagination={false}
|
||||||
|
expandable={{
|
||||||
|
expandedRowKeys,
|
||||||
|
onExpand: (expanded, record: any) => {
|
||||||
|
setExpandedRowKeys((prev) => {
|
||||||
|
const key = record?.tenantId;
|
||||||
|
if (key == null) return prev;
|
||||||
|
const set = new Set(prev);
|
||||||
|
if (expanded) set.add(key);
|
||||||
|
else set.delete(key);
|
||||||
|
return Array.from(set);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
size='middle'
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default TenantTreeTable;
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { forwardRef, useImperativeHandle, useRef } from 'react';
|
import React, { forwardRef, useImperativeHandle, useRef } from 'react';
|
||||||
import type { ActionType, ProColumns } from '@ant-design/pro-components';
|
import type { ActionType, ProColumns } from '@ant-design/pro-components';
|
||||||
import { ProTable } from '@ant-design/pro-components';
|
import { ProTable } from '@ant-design/pro-components';
|
||||||
import { Space, Switch, Popconfirm } from 'antd';
|
import { Space, Switch, Popconfirm } from 'antd';
|
||||||
@@ -12,7 +12,7 @@ export interface UserTableProps {
|
|||||||
onEdit: (record: UserItem) => void;
|
onEdit: (record: UserItem) => void;
|
||||||
onResetPassword: (record: UserItem) => void;
|
onResetPassword: (record: UserItem) => void;
|
||||||
onDelete: (record: UserItem) => void;
|
onDelete: (record: UserItem) => void;
|
||||||
// 额外查询参数(由外层统一查询栏传入)
|
// 额外查询参数(由外部查询条件统一注入)
|
||||||
extraParams?: Record<string, any>;
|
extraParams?: Record<string, any>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,6 +30,7 @@ const UserTable = forwardRef<UserTableRef, UserTableProps>(({ onEdit, onResetPas
|
|||||||
|
|
||||||
const columns: ProColumns<UserItem>[] = [
|
const columns: ProColumns<UserItem>[] = [
|
||||||
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
|
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
|
||||||
|
{ title: '所属租户', dataIndex: 'company', width: 160, search: false, render: (_, r) => (r as any)?.company || (r as any)?.tenantId || '-' },
|
||||||
{ title: '用户ID', dataIndex: 'id', width: 100, search: false },
|
{ title: '用户ID', dataIndex: 'id', width: 100, search: false },
|
||||||
{ title: '用户名', dataIndex: 'username' },
|
{ title: '用户名', dataIndex: 'username' },
|
||||||
{ title: '用户昵称', dataIndex: 'nickname' },
|
{ title: '用户昵称', dataIndex: 'nickname' },
|
||||||
@@ -61,16 +62,18 @@ const UserTable = forwardRef<UserTableRef, UserTableProps>(({ onEdit, onResetPas
|
|||||||
actionRef={actionRef}
|
actionRef={actionRef}
|
||||||
rowKey="id"
|
rowKey="id"
|
||||||
columns={columns}
|
columns={columns}
|
||||||
|
// 当外部查询参数变更时,自动触发请求
|
||||||
|
params={extraParams}
|
||||||
request={async (p) => {
|
request={async (p) => {
|
||||||
const { data, total } = await systemApi.users({ ...(p as any), ...(extraParams || {}) } as any);
|
const { data, total } = await systemApi.users({ ...(p as any), ...(extraParams || {}) } as any);
|
||||||
return { data, total, success: true };
|
return { data, total, success: true };
|
||||||
}}
|
}}
|
||||||
pagination={{ pageSize: 10 }}
|
pagination={{ pageSize: 10 }}
|
||||||
// 统一:关闭 ProTable 自带搜索,由外层 SearchBarPlus 统一承载
|
// 统一关闭 ProTable 自带搜索,由 SearchBarPlus 统一驱动
|
||||||
search={false}
|
search={false}
|
||||||
toolBarRender={false}
|
toolBarRender={false}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
export default UserTable;
|
export default UserTable;
|
||||||
|
|||||||
@@ -70,6 +70,8 @@ const UsersPage: React.FC = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const isAppType = params?.type === 'APP';
|
const isAppType = params?.type === 'APP';
|
||||||
|
const { tenantId, includeChildren, ...restParams } = params || {};
|
||||||
|
const listParams = isAppType ? restParams : params;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageContainer header={{ title: '用户管理' }}>
|
<PageContainer header={{ title: '用户管理' }}>
|
||||||
@@ -79,10 +81,15 @@ const UsersPage: React.FC = () => {
|
|||||||
defaultCollapsed={false}
|
defaultCollapsed={false}
|
||||||
split
|
split
|
||||||
span={6}
|
span={6}
|
||||||
onTenantChanged={() => tableRef.current?.reload()}
|
showTenant={!isAppType}
|
||||||
|
onTenantChanged={(tenantId, includeChildren) => {
|
||||||
|
// 租户切换时,直接更新查询参数,ProTable 会因 params 变更自动请求
|
||||||
|
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren }));
|
||||||
|
}}
|
||||||
onFinish={async (values) => {
|
onFinish={async (values) => {
|
||||||
setParams(values);
|
const v: any = { ...(values || {}) };
|
||||||
tableRef.current?.reload();
|
if (v?.type === 'APP') { delete v.tenantId; delete v.includeChildren; }
|
||||||
|
setParams(v); // 交由 ProTable(params) 触发请求
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<ProFormSelect name="type" label="用户类型" valueEnum={{ BACKEND: '系统用户', APP: 'C端用户' }} initialValue="BACKEND" />
|
<ProFormSelect name="type" label="用户类型" valueEnum={{ BACKEND: '系统用户', APP: 'C端用户' }} initialValue="BACKEND" />
|
||||||
@@ -96,7 +103,7 @@ const UsersPage: React.FC = () => {
|
|||||||
onEdit={(r) => { setCurrentRow(r); setEditVisible(true); }}
|
onEdit={(r) => { setCurrentRow(r); setEditVisible(true); }}
|
||||||
onResetPassword={(r) => resetPwd(r)}
|
onResetPassword={(r) => resetPwd(r)}
|
||||||
onDelete={(r) => delUser(r)}
|
onDelete={(r) => delUser(r)}
|
||||||
extraParams={params}
|
extraParams={listParams}
|
||||||
/>
|
/>
|
||||||
</GlassCard>
|
</GlassCard>
|
||||||
|
|
||||||
@@ -110,4 +117,3 @@ const UsersPage: React.FC = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default UsersPage;
|
export default UsersPage;
|
||||||
|
|
||||||
|
|||||||
@@ -16,8 +16,9 @@ export interface MenuItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const menuApi = {
|
export const menuApi = {
|
||||||
list: async (tenantId: string) => {
|
list: async (tenantId?: string) => {
|
||||||
const res = await request('/api-user/menus/findAlls', { method: 'GET', params: { tenantId } });
|
const params = tenantId ? { tenantId } : undefined;
|
||||||
|
const res = await request('/api-user/menus/findAlls', { method: 'GET', params });
|
||||||
return (res as any).data || res;
|
return (res as any).data || res;
|
||||||
},
|
},
|
||||||
simpleList: async () => {
|
simpleList: async () => {
|
||||||
|
|||||||
@@ -5,36 +5,62 @@ export interface RoleItem {
|
|||||||
name: string;
|
name: string;
|
||||||
code: string;
|
code: string;
|
||||||
dataScope?: 'ALL' | 'CREATOR';
|
dataScope?: 'ALL' | 'CREATOR';
|
||||||
|
// 所属租户ID
|
||||||
|
tenantId?: string;
|
||||||
|
// 所属租户名称(如果后端返回)
|
||||||
|
tenantName?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const roleApi = {
|
export const roleApi = {
|
||||||
page: async (params: { current?: number; pageSize?: number; tenantId?: string; searchKey?: string; searchValue?: string }) => {
|
// 角色分页(按租户/包含子级)
|
||||||
|
page: async (params: { current?: number; pageSize?: number; tenantId?: string; includeChildren?: boolean; searchKey?: string; searchValue?: string }) => {
|
||||||
if (!params?.tenantId) return { data: [], total: 0 };
|
if (!params?.tenantId) return { data: [], total: 0 };
|
||||||
const res = await request('/api-user/roles', {
|
const res = await request('/api-user/roles', {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
params: { page: params.current, limit: params.pageSize, tenantId: params.tenantId, searchKey: params.searchKey, searchValue: params.searchValue },
|
params: {
|
||||||
|
page: params.current,
|
||||||
|
limit: params.pageSize,
|
||||||
|
tenantId: params.tenantId,
|
||||||
|
includeChildren: params.includeChildren,
|
||||||
|
searchKey: params.searchKey,
|
||||||
|
searchValue: params.searchValue,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
const data = (res as any).data;
|
const data = (res as any).data;
|
||||||
const total = (res as any).count ?? data?.length ?? 0;
|
const total = (res as any).count ?? data?.length ?? 0;
|
||||||
return { data, total } as { data: RoleItem[]; total: number };
|
return { data, total } as { data: RoleItem[]; total: number };
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// 新增/修改角色(传入所属租户)
|
||||||
saveOrUpdate: async (data: RoleItem) => {
|
saveOrUpdate: async (data: RoleItem) => {
|
||||||
const res = await request('/api-user/roles/saveOrUpdate', { method: 'POST', data });
|
const res = await request('/api-user/roles/saveOrUpdate', {
|
||||||
|
method: 'POST',
|
||||||
|
data,
|
||||||
|
params: { tenantId: (data as any)?.tenantId },
|
||||||
|
});
|
||||||
return (res as any).data || res;
|
return (res as any).data || res;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// 删除角色
|
||||||
delete: async (id: number) => {
|
delete: async (id: number) => {
|
||||||
const res = await request(`/api-user/roles/${id}`, { method: 'DELETE' });
|
const res = await request(`/api-user/roles/${id}`, { method: 'DELETE' });
|
||||||
return (res as any).data || res;
|
return (res as any).data || res;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// 所有应用(授权用)
|
||||||
apps: async () => {
|
apps: async () => {
|
||||||
const res = await request('/api-uaa/clients/all', { method: 'GET' });
|
const res = await request('/api-uaa/clients/all', { method: 'GET' });
|
||||||
return (res as any).data || [];
|
return (res as any).data || [];
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// 某角色的菜单(按租户)
|
||||||
menuForAuth: async (roleId: number, tenantId: string) => {
|
menuForAuth: async (roleId: number, tenantId: string) => {
|
||||||
const res = await request(`/api-user/menus/${roleId}/menus`, { method: 'GET', params: { tenantId } });
|
const res = await request(`/api-user/menus/${roleId}/menus`, { method: 'GET', params: { tenantId } });
|
||||||
return res as any[];
|
return res as any[];
|
||||||
},
|
},
|
||||||
assignMenu: async (payload: { roleId: number; menuIds: (string|number)[] }) => {
|
|
||||||
|
// 分配菜单权限
|
||||||
|
assignMenu: async (payload: { roleId: number; menuIds: (string | number)[] }) => {
|
||||||
const res = await request('/api-user/menus/granted', { method: 'POST', data: payload });
|
const res = await request('/api-user/menus/granted', { method: 'POST', data: payload });
|
||||||
return (res as any).data || res;
|
return (res as any).data || res;
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user