多租户与景区关系

This commit is contained in:
2025-09-29 19:29:41 +08:00
parent 4c154ec746
commit dbd4d4d198
37 changed files with 997 additions and 267 deletions
+1
View File
@@ -4,6 +4,7 @@
- 所有交互回答必须使用中文(简体),包括解释、建议与错误信息。
- 代码片段中的注释、日志消息、文档内容与示例说明均应为中文;编程语言关键字与三方 API 标识符保持原文。
- 提交信息(commit)、合并请求(PR)描述与 Issue 标题/内容默认使用中文;涉及外部专有名词可保留英文缩写。
- 所有中文都使用utf-8
## 权限与执行策略
- 默认权限:Codex 在本仓库内可直接读取与编辑文件,无需额外审批。
@@ -1,83 +1,145 @@
package com.central.user.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.lock.DistributedLock;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.model.SysRole;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.user.mapper.SysRoleMapper;
import com.central.user.mapper.SysRoleMenuMapper;
import com.central.user.mapper.SysUserRoleMapper;
import com.central.user.service.ISysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* @author 作者 owen E-mail: 624191343@qq.com
*/
@Slf4j
@Service
public class SysRoleServiceImpl extends SuperServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
private final static String LOCK_KEY_ROLECODE = "rolecode:";
@Resource
private SysUserRoleMapper userRoleMapper;
@Resource
private SysRoleMenuMapper roleMenuMapper;
@Autowired
private DistributedLock lock;
@Transactional(rollbackFor = Exception.class)
@Override
public void saveRole(SysRole sysRole) throws Exception {
String roleCode = sysRole.getCode();
super.saveIdempotency(sysRole, lock
, LOCK_KEY_ROLECODE+roleCode, new QueryWrapper<SysRole>().eq("code", roleCode), "角色code已存在");
}
@Transactional(rollbackFor = Exception.class)
@Override
public void deleteRole(Long id) {
baseMapper.deleteById(id);
roleMenuMapper.delete(id, null);
userRoleMapper.deleteUserRole(null, id);
}
@Override
public PageResult<SysRole> findRoles(Map<String, Object> params) {
Integer curPage = MapUtils.getInteger(params, "page");
Integer limit = MapUtils.getInteger(params, "limit");
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) {
sysRole.setCreatorId(LoginUserContextHolder.getUser().getId());
this.saveRole(sysRole);
} else {
baseMapper.updateById(sysRole);
}
return Result.succeed("操作成功");
}
@Override
public List<SysRole> findAll() {
return baseMapper.findAll();
}
}
package com.central.user.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.lock.DistributedLock;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.model.SysRole;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.user.mapper.SysRoleMapper;
import com.central.user.mapper.SysRoleMenuMapper;
import com.central.user.mapper.SysUserRoleMapper;
import com.central.user.service.ISysRoleService;
import com.central.common.service.ITenantHierarchyService;
import com.central.common.datascope.annotation.IgnoreTenantScope;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* @author 作者 owen E-mail: 624191343@qq.com
*/
@Slf4j
@Service
public class SysRoleServiceImpl extends SuperServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
private final static String LOCK_KEY_ROLECODE = "rolecode:";
@Resource
private SysUserRoleMapper userRoleMapper;
@Resource
private SysRoleMenuMapper roleMenuMapper;
@Autowired
private DistributedLock lock;
@Resource
private ITenantHierarchyService tenantHierarchyService;
@Transactional(rollbackFor = Exception.class)
@Override
public void saveRole(SysRole sysRole) throws Exception {
String roleCode = sysRole.getCode();
super.saveIdempotency(sysRole, lock
, LOCK_KEY_ROLECODE+roleCode, new QueryWrapper<SysRole>().eq("code", roleCode), "角色code已存在");
}
@Transactional(rollbackFor = Exception.class)
@Override
public void deleteRole(Long id) {
baseMapper.deleteById(id);
roleMenuMapper.delete(id, null);
userRoleMapper.deleteUserRole(null, id);
}
@Override
@IgnoreTenantScope
public PageResult<SysRole> findRoles(Map<String, Object> params) {
Integer curPage = MapUtils.getInteger(params, "page");
Integer limit = MapUtils.getInteger(params, "limit");
// 以租户为主:支持按租户及其子租户过滤
String tenantId = MapUtils.getString(params, "tenantId");
Object incRaw = params.get("includeChildren");
boolean includeChildren = true;
if (incRaw != null) {
try {
if (incRaw instanceof Boolean) {
includeChildren = (Boolean) incRaw;
} else if (incRaw instanceof Number) {
includeChildren = ((Number) incRaw).intValue() != 0;
} else if (incRaw instanceof CharSequence) {
String s = incRaw.toString().trim();
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();
}
}
@@ -16,7 +16,9 @@ import com.central.common.model.UserType;
import com.central.common.model.SuperEntity;
import com.central.common.model.SysMenu;
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.mapper.SysRoleMenuMapper;
import com.central.user.mapper.SysUserMapper;
@@ -62,8 +64,11 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
@Resource
private OrderCenterService orderCenterService;
@Resource
private DeviceCenterService deviceCenterService;
@Resource
private DeviceCenterService deviceCenterService;
@Resource
private ITenantHierarchyService tenantHierarchyService;
@Override
public SysUser findByUsername(String username) {
@@ -225,10 +230,38 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
return Result.succeed("修改成功");
}
@Override
public PageResult<SysUser> findUsers(Map<String, Object> params) {
Page<SysUser> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
List<SysUser> list = baseMapper.findList(page, params);
@Override
public PageResult<SysUser> findUsers(Map<String, Object> params) {
Page<SysUser> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
// 组装租户过滤:有传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();
if (total > 0) {
List<Long> userIds = list.stream().map(SysUser::getId).collect(Collectors.toList());
@@ -44,6 +44,33 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
try {
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());
return subTenantIds;
} catch (Exception e) {
@@ -167,7 +194,7 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
@CacheEvict(value = "tenant:hierarchy", allEntries = true)
public Result<Tenant> createTenant(Tenant tenant) {
try {
// 验证必填字段
// 校验必填字段
if (!StringUtils.hasText(tenant.getTenantId())) {
return Result.failed("租户ID不能为空");
}
@@ -180,7 +207,7 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
return Result.failed("租户ID已存在");
}
// 验证父租户关系
// 验证父子租户关系
if (StringUtils.hasText(tenant.getParentTenantId())) {
if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
return Result.failed("无效的父子租户关系");
@@ -242,14 +269,14 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
return Result.failed("租户不存在");
}
// 验证父租户关系变更
// 验证父子关系变更
if (!Objects.equals(existingTenant.getParentTenantId(), tenant.getParentTenantId())) {
if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
return Result.failed("无效的父子租户关系");
}
}
// 使用主键ID执行更新,避免未传ID导致返回0
// 使用主键ID执行更新,避免未传ID导致更新不到
tenant.setId(existingTenant.getId());
int result = tenantHierarchyMapper.updateById(tenant);
if (result > 0) {
@@ -314,7 +341,7 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
.map(this::convertToTenantInfo)
.collect(Collectors.toList());
log.debug("查询租户列表完成,总数: {}, 当前页: {}", total, tenantInfos.size());
log.debug("查询租户列表完成,总数: {},当前页数量: {}", total, tenantInfos.size());
return Result.succeed(tenantInfos);
} catch (Exception e) {
@@ -367,7 +394,7 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
}
/**
* 转换为TenantInfo
* 转换为 TenantInfo
*/
private TenantInfo convertToTenantInfo(Tenant tenant) {
if (tenant == null) {
@@ -398,3 +425,4 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
.build();
}
}
@@ -12,17 +12,28 @@
data_scope
</sql>
<sql id="where">
<where>
<if test="r.name != null and r.name != ''">
and t.name like concat('%', #{r.name}, '%')
</if>
<if test="r.searchKey != null and r.searchKey != '' and r.searchKey=='name'">
and t.name like concat('%', #{r.searchValue}, '%')
</if>
</where>
</sql>
<sql id="where">
<where>
<if test="r.name != null and r.name != ''">
and t.name like concat('%', #{r.name}, '%')
</if>
<if test="r.searchKey != null and r.searchKey != '' and r.searchKey=='name'">
and t.name like concat('%', #{r.searchValue}, '%')
</if>
<!-- 按租户过滤(以租户为主):优先使用租户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 <include refid="Column_List"/>
@@ -36,4 +47,4 @@
from sys_role
order by create_time desc
</select>
</mapper>
</mapper>
@@ -2,12 +2,18 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.user.mapper.SysUserMapper">
<sql id="where">
<where>
t.is_del=0
<if test="u.id != null and u.id != ''">
and t.id like concat('%', #{u.id}, '%')
</if>
<sql id="where">
<where>
t.is_del=0
<if test="u.tenantIds != null and u.tenantIds.size > 0">
and t.company in
<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 != ''">
and t.username like concat('%', #{u.username}, '%')
</if>
@@ -40,4 +46,4 @@
<include refid="where" />
order by t.id desc
</select>
</mapper>
</mapper>
@@ -24,4 +24,9 @@ public class SysRole extends SuperEntity {
*/
private DataScope dataScope;
private Long creatorId;
/**
* 所属租户
*/
@TableField("tenant_id")
private String tenantId;
}
@@ -133,7 +133,6 @@ public class LoginUserUtils {
if (sysRoles != null) {
sysRoles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getCode())));
}
log.info("获取到的user是:{}",sysUser);
// 兼容 enabled 可能为 null 的场景,默认视为启用
boolean enabled = Optional.ofNullable(sysUser.getEnabled()).orElse(true);
LoginAppUser user = new LoginAppUser(sysUser.getId()
@@ -9,6 +9,7 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
@@ -27,7 +28,7 @@ import java.io.IOException;
* Github: https://github.com/zlt2000
*/
@ConditionalOnClass(Filter.class)
@Order
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
public class LoginUserFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
@@ -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();
}
}
}
@@ -11,6 +11,7 @@ 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;
@@ -18,14 +19,14 @@ import java.io.IOException;
import java.util.List;
/**
* 读取可选的 tenantId 查询参数,作为本次请求的租户范围覆盖锚点。
* 规则:
* - APP 用户忽略该参数(记录warn)。
* - BACKEND 用户仅在参数属于“可访问租户集”时生效;否则忽略并warn。
* 读取可选的 tenantId 查询参数,作为本次请求的租户范围覆盖锚点�?
* 规则�?
* - APP 用户忽略该参数(记录warn)�?
* - BACKEND 用户仅在参数属于“可访问租户集”时生效;否则忽略并warn�?
*/
@Slf4j
@ConditionalOnClass(Filter.class)
@Order
@Order(Ordered.HIGHEST_PRECEDENCE + 20)
public class TenantQueryOverrideFilter extends OncePerRequestFilter {
private static final String PARAM_TENANT_ID = "tenantId";
@@ -38,7 +39,7 @@ public class TenantQueryOverrideFilter extends OncePerRequestFilter {
LoginAppUser user = LoginUserContextHolder.getUser();
if (user == null) {
// 未登录,忽略参数
log.debug("忽略tenantId参数(未登录): {}", overrideTenant);
log.debug("忽略tenantId参数(未登录?: {}", overrideTenant);
} else {
String userType = (String) user.getAttributes().getOrDefault("type", "BACKEND");
if ("APP".equals(userType)) {
@@ -49,7 +50,7 @@ public class TenantQueryOverrideFilter extends OncePerRequestFilter {
TenantQueryOverrideContext.setTenantId(overrideTenant);
log.debug("本次请求使用覆盖租户ID: {}", overrideTenant);
} 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,4 +1,5 @@
com.central.common.filter.TenantFilter
com.central.common.filter.LoginUserFilter
com.central.common.filter.TenantParamOverrideFilter
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 { tenantApi, TenantTreeNode } from '@/services/tenant';
interface Props {
// 当租户或“包含子租户”变更后回调
// 租户或“包含下级”变化后的回调(外部将 tenantId/includeChildren 透传到请求参数)
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 [tenantId, setTenantId] = useState<string | undefined>();
const [includeChildren, setIncludeChildren] = useState(true);
@@ -21,8 +23,8 @@ const TenantScopeFilter: React.FC<Props> = ({ onChanged }) => {
tenantApi.getAccessibleTenants(),
tenantApi.getCurrentTenant(),
]);
if (treeRes.success) setTree(treeRes.data || []);
if (currentRes.success) setTenantId(currentRes.data?.tenantId);
if ((treeRes as any)?.success) setTree((treeRes as any).data || []);
if ((currentRes as any)?.success) setTenantId((currentRes as any).data?.tenantId);
} finally {
setLoading(false);
}
@@ -40,15 +42,14 @@ const TenantScopeFilter: React.FC<Props> = ({ onChanged }) => {
const handleApply = async () => {
if (!tenantId) return;
try {
const res = await tenantApi.switchTenant(tenantId);
if (res.success) {
message.success('租户范围已更新');
onChanged?.(tenantId, includeChildren);
} else {
message.error((res as any).msg || '切换失败');
if (useSwitchTenant) {
const res = await tenantApi.switchTenant(tenantId);
if ((res as any)?.success) message.success('租户范围已更新');
else { message.error((res as any)?.msg || '切换失败'); return; }
}
} catch (e) {
message.error('切换失败');
onChanged?.(tenantId, includeChildren);
} 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;
// 租户筛选放置位置:start 放在最前,end 放在最后(默认 start)
tenantPosition?: 'start' | 'end';
// 是否调用后端“切换查询租户”接口(默认不调用,避免跨页面副作用)
useSwitchTenant?: boolean;
}
const SearchBarPlus: React.FC<SearchBarPlusProps> = ({
@@ -30,13 +32,14 @@ const SearchBarPlus: React.FC<SearchBarPlusProps> = ({
showTenant = true,
onTenantChanged,
tenantPosition = 'start',
useSwitchTenant = false,
}) => {
const handleFinish = async (values: Record<string, any>) => {
try {
if (showTenant && values && values.tenantId) {
await tenantApi.switchTenant(values.tenantId);
if (useSwitchTenant && showTenant && values && (values as any).tenantId) {
await tenantApi.switchTenant((values as any).tenantId);
}
onTenantChanged?.(values?.tenantId, !!values?.includeChildren);
onTenantChanged?.((values as any)?.tenantId, !!(values as any)?.includeChildren);
} finally {
await onFinish?.(values);
}
@@ -58,3 +61,4 @@ const SearchBarPlus: React.FC<SearchBarPlusProps> = ({
};
export default SearchBarPlus;
@@ -9,6 +9,8 @@ export interface TenantSelectorProps {
labelIncludeChildren?: React.ReactNode;
// 是否隐藏“包含下级”复选框(用于仅需要选择租户的场景,如用户表单)
hideIncludeChildren?: boolean;
// 透传给租户选择项的校验规则(用于必填等)
rulesTenant?: any[];
}
const toTreeData = (nodes?: TenantTreeNode[] | any): any[] => {
@@ -27,6 +29,7 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
labelTenant = '租户',
labelIncludeChildren = '包含下级',
hideIncludeChildren = false,
rulesTenant,
}) => {
const form = Form.useFormInstance?.();
const [tree, setTree] = useState<TenantTreeNode[]>([]);
@@ -89,7 +92,7 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
return (
<>
<Form.Item name={nameTenant} label={labelTenant}>
<Form.Item name={nameTenant} label={labelTenant} rules={rulesTenant as any}>
<TreeSelect
style={{ minWidth: 260 }}
treeDefaultExpandAll
+2 -2
View File
@@ -41,7 +41,7 @@ const Welcome: React.FC = () => {
</Space>
</Col>
<Col>
<TenantScopeFilter />
<TenantScopeFilter useSwitchTenant onChanged={() => { /* 切换后由后端上下文生效 */ }} />
</Col>
</Row>
</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}
onTenantChanged={() => actionRef.current?.reload?.()}
onFinish={async (values) => {
const { searchKey, searchValue } = values as any;
const { searchKey, searchValue, ...rest } = values as any;
let queryStr = '';
if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`;
setParams({ ...params, queryStr });
setParams({ ...rest, queryStr });
}}
>
<ProFormSelect
@@ -26,10 +26,10 @@ const SlowSqlLogPage: React.FC = () => {
span={8}
onTenantChanged={() => actionRef.current?.reload?.()}
onFinish={async (values) => {
const { searchKey, searchValue } = values as any;
const { searchKey, searchValue, ...rest } = values as any;
let queryStr = '';
if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`;
setParams({ ...params, queryStr });
setParams({ ...rest, queryStr });
}}
>
<ProFormSelect name="searchKey" label="检索" valueEnum={{ none: '全文检索', query_str: '查询语句' }} />
@@ -42,10 +42,10 @@ const SysLogPage: React.FC = () => {
span={8}
onTenantChanged={() => actionRef.current?.reload?.()}
onFinish={async (values) => {
const { searchKey, searchValue } = values as any;
const { searchKey, searchValue, ...rest } = values as any;
let queryStr = '';
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' }} />
@@ -21,6 +21,7 @@ const MESSAGE_STATUS: Record<number, { text: string; color: string }> = {
const MessageList: React.FC = () => {
const actionRef = useRef<ActionType>();
const [selectedRows, setSelectedRows] = useState<MessageItem[]>([]);
const [params, setParams] = useState<Record<string, any>>({});
const handleMessageClick = async (record: MessageItem) => {
if (record.status === 0) {
@@ -97,6 +98,7 @@ const MessageList: React.FC = () => {
split
span={8}
onTenantChanged={() => actionRef.current?.reload()}
onFinish={async (values) => setParams(values)}
/>
<ActionBar right={<GradientButton size="middle" key="markAllRead" onClick={handleMarkAllRead}>全部标记已读</GradientButton>} />
@@ -107,7 +109,7 @@ const MessageList: React.FC = () => {
rowKey="id"
search={{ labelWidth: 120 }}
toolBarRender={false}
request={(p) => messageApi.list(p)}
request={(p) => messageApi.list({ ...(p as any), ...params })}
columns={columns}
rowSelection={{ onChange: (_, rows) => setSelectedRows(rows) }}
pagination={{ showQuickJumper: true, showSizeChanger: true }}
@@ -10,6 +10,7 @@ const HomeCarouselPage: React.FC = () => {
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<HomeCarouselItem | undefined>(undefined);
const [params, setParams] = useState<Record<string, any>>({});
const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
@@ -40,14 +41,20 @@ const HomeCarouselPage: React.FC = () => {
return (
<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>} />
<GlassCard>
<ProTable<HomeCarouselItem>
rowKey="id"
request={(p) => ordersApi.homeCarouselList(p as any)}
request={(p) => ordersApi.homeCarouselList({ ...(p as any), ...params })}
columns={columns}
search={false}
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 { Card, Col, Row, Statistic, message, Button } from 'antd';
import TenantScopeFilter from '@/components/TenantScopeFilter';
@@ -8,22 +8,23 @@ import { ActionBar } from '@/components/ui';
const ProfitSharingStatisticsPage: React.FC = () => {
const [loading, setLoading] = useState(false);
const [stat, setStat] = useState<any>({});
const [scope, setScope] = useState<{ tenantId?: string; includeChildren?: boolean }>({});
const load = async () => {
const load = async (p?: any) => {
setLoading(true);
try {
const res = await ordersApi.getProfitSharingStatistics();
const res = await ordersApi.getProfitSharingStatistics(p);
setStat(res?.data || res);
} catch (e) {
message.error('加载统计失败');
} finally { setLoading(false); }
};
useEffect(() => { load(); }, []);
useEffect(() => { load(scope); }, [scope]);
return (
<PageContainer header={{ title: '分账统计' }} extra={<TenantScopeFilter onChanged={() => load()} /> }>
<ActionBar right={<Button size="middle" onClick={() => load()}>刷新</Button>} />
<PageContainer header={{ title: '分账统计' }} extra={<TenantScopeFilter useSwitchTenant onChanged={(tid, inc) => setScope({ tenantId: tid, includeChildren: inc })} /> }>
<ActionBar right={<Button size="middle" onClick={() => load(scope)}>刷新</Button>} />
<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?.sharingCount || 0} /></Card></Col>
@@ -10,6 +10,7 @@ const QrcodePage: React.FC = () => {
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<QrcodeItem | undefined>(undefined);
const [params, setParams] = useState<Record<string, any>>({});
const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
@@ -40,12 +41,18 @@ const QrcodePage: React.FC = () => {
return (
<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>} />
<GlassCard>
<ProTable<QrcodeItem>
rowKey="id"
request={(p) => ordersApi.qrcodeList(p as any)}
request={(p) => ordersApi.qrcodeList({ ...(p as any), ...params })}
columns={columns}
search={false}
pagination={{ showSizeChanger: true, showQuickJumper: true }}
@@ -31,8 +31,15 @@ const StatisticsPage: React.FC = () => {
span={8}
onTenantChanged={() => load(range)}
onFinish={async (values) => {
const v = values?.timeRange;
const r = v && v.length === 2 ? { startTime: v[0]?.toISOString(), endTime: v[1]?.toISOString() } : undefined;
const v = (values as any)?.timeRange;
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);
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 TenantSelector from '@/components/ui/TenantSelector';
export interface TourismItem {
id?: number;
tenantId?: string;
tourismName?: string;
address?: string;
contactPerson?: string;
contactPhone?: string;
status?: number;
tourismAddress?: string;
tourismPhone?: string;
status?: number; // 1 启用,0 禁用
longitude?: string;
latitude?: string;
showInHomepage?: number; // 1 是,0 否
description?: string;
}
@@ -29,14 +33,41 @@ const TourismForm: React.FC<TourismFormProps> = ({ open, title, initialValues, o
initialValues={initialValues}
modalProps={{ destroyOnClose: true }}
>
{/* 所属租户(必选) */}
<TenantSelector nameTenant="tenantId" labelTenant="所属租户" hideIncludeChildren rulesTenant={[{ required: true, message: '请选择租户' }]} />
<ProFormText name="tourismName" label="景区名称" rules={[{ required: true, message: '请输入景区名称' }]} />
<ProFormText name="address" label="地址" />
<ProFormText name="contactPerson" label="联系人" />
<ProFormText name="contactPhone" label="联系电话" />
<ProFormSelect name="status" label="状态" valueEnum={{ 1: '启用', 0: '禁用' }} initialValue={1} />
<ProFormText name="tourismAddress" label="地址" />
<ProFormText name="tourismPhone" label="联系电话" />
<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="描述" />
</ModalForm>
);
};
export default TourismForm;
@@ -1,56 +1,113 @@
import React, { useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import { PageContainer, ProFormText, ProTable } from '@ant-design/pro-components';
import { Popconfirm, Space, Tag, message } from 'antd';
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
import { PlusOutlined } from '@ant-design/icons';
import { ordersApi } from '@/services/orders';
import TourismForm, { TourismItem } from './components/TourismForm';
import { tenantApi } from '@/services/tenant';
const TourismPage: React.FC = () => {
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
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[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '旅游项目', dataIndex: 'tourismName' },
{ title: '地址', dataIndex: 'address' },
{ title: '联系人', dataIndex: 'contactPerson' },
{ title: '联系电话', dataIndex: 'contactPhone' },
{ title: '状态', dataIndex: 'status', render: (v: number) => <Tag color={v === 1 ? 'green' : 'default'}>{v === 1 ? '启用' : '禁用'}</Tag> },
{ title: '地址', dataIndex: 'tourismAddress' },
{ title: '经度', dataIndex: 'longitude' },
{ title: '纬度', dataIndex: 'latitude' },
{
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) => (
<Space>
<a onClick={() => { setCurrent(record); setEditOpen(true); }}>编辑</a>
<Popconfirm title={`确认删除项目[${record.tourismName}]?`} onConfirm={async () => {
const hide = message.loading('删除中...');
try {
await ordersApi.deleteTourism(record.id!);
message.success('删除成功');
} catch (e) {
message.error('删除失败');
} finally { hide(); }
}}>
<Popconfirm
title={`确认删除项目[${record.tourismName}]?`}
onConfirm={async () => {
const hide = message.loading('正在删除...');
try {
await ordersApi.deleteTourism(record.id!);
message.success('删除成功');
} catch {
message.error('删除失败');
} finally { hide(); }
}}
>
<a style={{ color: '#1677ff' }}>删除</a>
</Popconfirm>
</Space>
)
),
},
];
return (
<PageContainer header={{ title: '旅游项目' }}>
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => { /* 租户切换 */ }} />
<ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} />
<SearchBarPlus
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>
<ProTable<TourismItem>
rowKey="id"
request={(p) => ordersApi.tourism(p as any)}
columns={columns}
search={false}
pagination={{ showSizeChanger: true, showQuickJumper: true }}
/>
{params?.tenantId ? (
<ProTable<TourismItem>
rowKey="id"
params={params}
request={(p) => ordersApi.tourism({ ...(p as any), ...params })}
columns={columns}
search={false}
pagination={{ showSizeChanger: true, showQuickJumper: true }}
toolBarRender={false}
/>
) : null}
</GlassCard>
<TourismForm
@@ -63,8 +120,8 @@ const TourismPage: React.FC = () => {
await ordersApi.saveOrUpdateTourism(values);
message.success('新增成功');
return true;
} catch (e) {
message.error('保存失败');
} catch {
message.error('新增失败');
return false;
} finally { hide(); }
}}
@@ -81,7 +138,7 @@ const TourismPage: React.FC = () => {
await ordersApi.saveOrUpdateTourism({ ...(current as any), ...values });
message.success('修改成功');
return true;
} catch (e) {
} catch {
message.error('修改失败');
return false;
} finally { hide(); }
@@ -1,7 +1,7 @@
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 { ActionBar, GradientButton, GlassCard, SearchBarPlus } from '@/components/ui';
import { ActionBar, GradientButton, GlassCard } from '@/components/ui';
import { PlusOutlined } from '@ant-design/icons';
import MenuTree from './components/MenuTree';
import MenuForm from './components/MenuForm';
@@ -10,19 +10,17 @@ import { roleApi } from '@/services/role';
import { buildTree } from '@/utils/tree';
const MenuPage: React.FC = () => {
const [apps, setApps] = useState<any[]>([]);
const [tenantId, setTenantId] = useState<string | undefined>();
const [keyword, setKeyword] = useState<string | undefined>();
const [keyword] = useState<string | undefined>(undefined);
const [data, setData] = useState<MenuItem[]>([]);
const [loading, setLoading] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<MenuItem | undefined>(undefined);
const fetchMenu = useCallback(async (clientId: string) => {
const fetchMenu = useCallback(async () => {
setLoading(true);
try {
const menus = await menuApi.list(clientId);
const menus = await menuApi.list();
const list: any[] = menus || [];
const hasSubMenus = list.some((m) => Array.isArray(m?.subMenus));
if (hasSubMenus) {
@@ -57,24 +55,14 @@ const MenuPage: React.FC = () => {
}
}, []);
useEffect(() => {
(async () => {
const list = await roleApi.apps();
setApps(list || []);
if (list?.length) {
const id = list[0].clientId;
setTenantId(id);
fetchMenu(id);
}
})();
}, [fetchMenu]);
useEffect(() => { fetchMenu(); }, [fetchMenu]);
const handleDelete = async (record: MenuItem) => {
const hide = message.loading('删除中...');
const hide = message.loading('鍒犻櫎涓?..');
try {
await menuApi.delete(record.id!);
message.success('鍒犻櫎鑿滃崟鎴愬姛');
if (tenantId) fetchMenu(tenantId);
fetchMenu();
} catch (e) {
message.error('鍒犻櫎鑿滃崟澶辫触');
} finally { hide(); }
@@ -82,16 +70,7 @@ const MenuPage: React.FC = () => {
return (
<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
left={
@@ -116,11 +95,11 @@ const MenuPage: React.FC = () => {
open={createOpen}
onOpenChange={setCreateOpen}
onFinish={async (values) => {
const hide = message.loading('保存中...');
const hide = message.loading('淇濆瓨涓?..');
try {
await menuApi.saveOrUpdate(values);
message.success('鏂板�鑿滃崟鎴愬姛');
tenantId && fetchMenu(tenantId);
fetchMenu();
return true;
} catch (e) {
message.error('鏂板�鑿滃崟澶辫触');
@@ -135,11 +114,11 @@ const MenuPage: React.FC = () => {
initialValues={current}
onOpenChange={setEditOpen}
onFinish={async (values) => {
const hide = message.loading('保存中...');
const hide = message.loading('淇濆瓨涓?..');
try {
await menuApi.saveOrUpdate({ ...current, ...values });
message.success('淇�敼鑿滃崟鎴愬姛');
tenantId && fetchMenu(tenantId);
fetchMenu();
return true;
} catch (e) {
message.error('淇�敼鑿滃崟澶辫触');
@@ -153,3 +132,5 @@ const MenuPage: React.FC = () => {
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 TenantSelector from '@/components/ui/TenantSelector';
import { RoleItem } from '@/services/role';
export interface RoleFormProps {
@@ -22,13 +23,14 @@ const RoleForm: React.FC<RoleFormProps> = ({ open, title, initialValues, onOpenC
width={500}
>
<ProForm.Group>
<TenantSelector hideIncludeChildren rulesTenant={[{ required: true, message: '请选择所属租户' }]} />
<ProFormText name="name" label="角色名称" rules={[{ required: true, message: '角色名不能为空' }]} width="lg" />
<ProFormText name="code" label="编码" rules={[{ required: true, message: '编码不能为空' }]} width="lg" />
<ProFormRadio.Group
name="dataScope"
label="数据权限"
width="lg"
options={[{ label: '全部', value: 'ALL' }, { label: '本人', value: 'CREATOR' }]}
options={[{ label: '全部', value: 'ALL' }, { label: '自定义', value: 'CREATOR' }]}
/>
</ProForm.Group>
</ModalForm>
@@ -36,3 +38,4 @@ const RoleForm: React.FC<RoleFormProps> = ({ open, title, initialValues, onOpenC
};
export default RoleForm;
@@ -4,30 +4,22 @@ import { Popconfirm, Space, message } from 'antd';
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
import { PlusOutlined } from '@ant-design/icons';
import { roleApi, RoleItem } from '@/services/role';
import { tenantApi } from '@/services/tenant';
import RoleForm from './components/RoleForm';
import AssignAuth from './components/AssignAuth';
const RolePage: React.FC = () => {
const [apps, setApps] = useState<any[]>([]);
const [params, setParams] = useState<{ tenantId?: string; searchKey?: string; searchValue?: string }>({});
const [params, setParams] = useState<{ tenantId?: string; includeChildren?: boolean; searchKey?: string; searchValue?: string }>({});
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [assignOpen, setAssignOpen] = useState(false);
const [current, setCurrent] = useState<RoleItem | undefined>(undefined);
useEffect(() => {
(async () => {
const list = await roleApi.apps();
setApps(list || []);
if (list?.length) {
const tenantId = list[0].clientId;
setParams((p) => ({ ...p, tenantId }));
}
})();
}, []);
// 以租户为主:通过 SearchBarPlus 内置租户选择器
const columns = [
{ 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: '角色名称', dataIndex: 'name' },
{ 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 (
<PageContainer header={{ title: '角色管理' }}>
<SearchBarPlus
defaultCollapsed={false}
split
span={6}
onTenantChanged={() => { /* 切换租户后服务端上下文生效 */ }}
onTenantChanged={(tenantId, includeChildren) => {
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren }));
}}
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: '角色名称' }} />
<ProFormText name="searchValue" placeholder="请输入关键字" />
</SearchBarPlus>
@@ -80,6 +93,7 @@ const RolePage: React.FC = () => {
<ProTable<RoleItem>
rowKey="id"
headerTitle="角色列表"
params={params}
request={async (p) => roleApi.page({ ...p, ...params })}
columns={columns as any}
search={false}
@@ -134,4 +148,3 @@ const RolePage: React.FC = () => {
};
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 { ProTable } from '@ant-design/pro-components';
import { Space, Switch, Popconfirm } from 'antd';
@@ -12,7 +12,7 @@ export interface UserTableProps {
onEdit: (record: UserItem) => void;
onResetPassword: (record: UserItem) => void;
onDelete: (record: UserItem) => void;
// 额外查询参数(由外层统一查询栏传入)
// 额外查询参数(由外部查询条件统一注入)
extraParams?: Record<string, any>;
}
@@ -30,6 +30,7 @@ const UserTable = forwardRef<UserTableRef, UserTableProps>(({ onEdit, onResetPas
const columns: ProColumns<UserItem>[] = [
{ 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: '用户名', dataIndex: 'username' },
{ title: '用户昵称', dataIndex: 'nickname' },
@@ -61,16 +62,18 @@ const UserTable = forwardRef<UserTableRef, UserTableProps>(({ onEdit, onResetPas
actionRef={actionRef}
rowKey="id"
columns={columns}
// 当外部查询参数变更时,自动触发请求
params={extraParams}
request={async (p) => {
const { data, total } = await systemApi.users({ ...(p as any), ...(extraParams || {}) } as any);
return { data, total, success: true };
}}
pagination={{ pageSize: 10 }}
// 统一:关闭 ProTable 自带搜索,由外层 SearchBarPlus 统一承载
// 统一关闭 ProTable 自带搜索,由 SearchBarPlus 统一驱动
search={false}
toolBarRender={false}
/>
);
});
export default UserTable;
export default UserTable;
@@ -70,6 +70,8 @@ const UsersPage: React.FC = () => {
};
const isAppType = params?.type === 'APP';
const { tenantId, includeChildren, ...restParams } = params || {};
const listParams = isAppType ? restParams : params;
return (
<PageContainer header={{ title: '用户管理' }}>
@@ -79,10 +81,15 @@ const UsersPage: React.FC = () => {
defaultCollapsed={false}
split
span={6}
onTenantChanged={() => tableRef.current?.reload()}
showTenant={!isAppType}
onTenantChanged={(tenantId, includeChildren) => {
// 租户切换时,直接更新查询参数,ProTable 会因 params 变更自动请求
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren }));
}}
onFinish={async (values) => {
setParams(values);
tableRef.current?.reload();
const v: any = { ...(values || {}) };
if (v?.type === 'APP') { delete v.tenantId; delete v.includeChildren; }
setParams(v); // 交由 ProTable(params) 触发请求
}}
>
<ProFormSelect name="type" label="用户类型" valueEnum={{ BACKEND: '系统用户', APP: 'C端用户' }} initialValue="BACKEND" />
@@ -96,7 +103,7 @@ const UsersPage: React.FC = () => {
onEdit={(r) => { setCurrentRow(r); setEditVisible(true); }}
onResetPassword={(r) => resetPwd(r)}
onDelete={(r) => delUser(r)}
extraParams={params}
extraParams={listParams}
/>
</GlassCard>
@@ -110,4 +117,3 @@ const UsersPage: React.FC = () => {
};
export default UsersPage;
+3 -2
View File
@@ -16,8 +16,9 @@ export interface MenuItem {
}
export const menuApi = {
list: async (tenantId: string) => {
const res = await request('/api-user/menus/findAlls', { method: 'GET', params: { tenantId } });
list: async (tenantId?: string) => {
const params = tenantId ? { tenantId } : undefined;
const res = await request('/api-user/menus/findAlls', { method: 'GET', params });
return (res as any).data || res;
},
simpleList: async () => {
+30 -4
View File
@@ -5,36 +5,62 @@ export interface RoleItem {
name: string;
code: string;
dataScope?: 'ALL' | 'CREATOR';
// 所属租户ID
tenantId?: string;
// 所属租户名称(如果后端返回)
tenantName?: string;
}
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 };
const res = await request('/api-user/roles', {
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 total = (res as any).count ?? data?.length ?? 0;
return { data, total } as { data: RoleItem[]; total: number };
},
// 新增/修改角色(传入所属租户)
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;
},
// 删除角色
delete: async (id: number) => {
const res = await request(`/api-user/roles/${id}`, { method: 'DELETE' });
return (res as any).data || res;
},
// 所有应用(授权用)
apps: async () => {
const res = await request('/api-uaa/clients/all', { method: 'GET' });
return (res as any).data || [];
},
// 某角色的菜单(按租户)
menuForAuth: async (roleId: number, tenantId: string) => {
const res = await request(`/api-user/menus/${roleId}/menus`, { method: 'GET', params: { tenantId } });
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 });
return (res as any).data || res;
},