修复页面bug

This commit is contained in:
2025-09-26 18:42:41 +08:00
parent 3c604be299
commit 4c154ec746
19 changed files with 584 additions and 405 deletions
@@ -127,12 +127,20 @@ public class TenantHierarchyController {
// ===== 私有方法:对象转换 ===== // ===== 私有方法:对象转换 =====
private Tenant toTenant(TenantInfo info) { private Tenant toTenant(TenantInfo info) {
if (info == null) return null; if (info == null) return null;
// 规范化关键字段,避免出现 null 前缀或尾部斜杠
String tenantId = info.getTenantId();
String parentId = info.getParentTenantId();
String normalizedPath = normalizePathForSave(info.getTenantPath(), parentId, tenantId);
Integer normalizedLevel = normalizeLevelForSave(info.getTenantLevel(), parentId);
Tenant t = new Tenant(); Tenant t = new Tenant();
t.setTenantId(info.getTenantId()); t.setTenantId(tenantId);
t.setTenantName(info.getTenantName()); t.setTenantName(info.getTenantName());
t.setParentTenantId(info.getParentTenantId()); t.setParentTenantId(parentId);
t.setTenantLevel(info.getTenantLevel()); t.setTenantLevel(normalizedLevel);
t.setTenantPath(info.getTenantPath()); t.setTenantPath(normalizedPath);
t.setTenantType(info.getTenantType()); t.setTenantType(info.getTenantType());
t.setTenantCode(info.getTenantCode()); t.setTenantCode(info.getTenantCode());
t.setContactPerson(info.getContactPerson()); t.setContactPerson(info.getContactPerson());
@@ -144,6 +152,50 @@ public class TenantHierarchyController {
return t; return t;
} }
private String normalizePathForSave(String rawPath, String parentId, String tenantId) {
try {
String path = stripPathSafe(rawPath);
String base = null;
if (StringUtils.hasText(parentId)) {
TenantInfo p = tenantHierarchyService.getTenantInfo(parentId);
base = stripPathSafe(p != null && StringUtils.hasText(p.getTenantPath()) ? p.getTenantPath() : parentId);
}
// 1) 空/异常路径 → 按父路径重建;2) 有父但路径未以父路径开头 → 纠正;
boolean invalid = !StringUtils.hasText(path) || path.toLowerCase().startsWith("null") || path.endsWith("/");
boolean wrongPrefix = StringUtils.hasText(base) && (path == null || !path.startsWith(base + "/"));
if (invalid || wrongPrefix) {
if (!StringUtils.hasText(base)) return stripPathSafe(tenantId);
return base + "/" + stripPathSafe(tenantId);
}
return path;
} catch (Exception e) {
return stripPathSafe(tenantId);
}
}
private Integer normalizeLevelForSave(Integer level, String parentId) {
if (level != null && level > 0) return level;
try {
Integer parentLevel = null;
if (StringUtils.hasText(parentId)) {
TenantInfo p = tenantHierarchyService.getTenantInfo(parentId);
parentLevel = p != null ? p.getTenantLevel() : null;
}
return (parentLevel == null ? 0 : parentLevel) + 1;
} catch (Exception e) {
return 1;
}
}
private String stripPathSafe(String path) {
if (!StringUtils.hasText(path)) return null;
String p = path.trim();
if (p.toLowerCase().startsWith("null")) p = p.substring(4);
while (p.startsWith("/")) p = p.substring(1);
while (p.endsWith("/")) p = p.substring(0, p.length() - 1);
return p;
}
private TenantInfo toTenantInfo(Tenant t) { private TenantInfo toTenantInfo(Tenant t) {
if (t == null) return null; if (t == null) return null;
return TenantInfo.builder() return TenantInfo.builder()
@@ -168,7 +168,16 @@ public class TenantSwitchController {
String userTenantId = getDefaultTenantId(user); String userTenantId = getDefaultTenantId(user);
if (StringUtils.hasText(userTenantId)) { if (StringUtils.hasText(userTenantId)) {
if (isCanSwitchTenant(user)) { if (isCanSwitchTenant(user)) {
return tenantHierarchyService.getAllSubTenantIds(userTenantId); try {
List<String> subIds = tenantHierarchyService != null ? tenantHierarchyService.getAllSubTenantIds(userTenantId) : null;
if (subIds != null && !subIds.isEmpty()) {
return subIds;
}
} catch (Exception e) {
log.warn("获取子租户列表失败,降级为仅当前租户: tenantId={}, error={}", userTenantId, e.getMessage());
}
// 降级:至少返回当前租户本身
return List.of(userTenantId);
} else { } else {
return List.of(userTenantId); return List.of(userTenantId);
} }
@@ -178,6 +187,13 @@ public class TenantSwitchController {
private String getDefaultTenantId(LoginAppUser user) { private String getDefaultTenantId(LoginAppUser user) {
Object company = user.getAttributes().get("company"); Object company = user.getAttributes().get("company");
return company != null ? company.toString() : null; if (company != null && StringUtils.hasText(company.toString())) {
return company.toString();
}
if (StringUtils.hasText(user.getCompany())) {
return user.getCompany();
}
// 兜底:若当前租户已设置则返回
return LoginUserContextHolder.getCurrentTenantId();
} }
} }
@@ -249,7 +249,8 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
} }
} }
// 更新租户 // 使用主键ID执行更新,避免未传ID导致返回0
tenant.setId(existingTenant.getId());
int result = tenantHierarchyMapper.updateById(tenant); int result = tenantHierarchyMapper.updateById(tenant);
if (result > 0) { if (result > 0) {
log.info("更新租户成功: tenantId={}", tenant.getTenantId()); log.info("更新租户成功: tenantId={}", tenant.getTenantId());
@@ -10,6 +10,7 @@ import com.central.common.model.SysRole;
import com.central.common.model.SysUser; import com.central.common.model.SysUser;
import com.central.common.service.UserTenantInitializer; import com.central.common.service.UserTenantInitializer;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
@@ -31,6 +32,7 @@ import java.util.*;
* Blog: http://zlt2000.gitee.io * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000 * Github: https://github.com/zlt2000
*/ */
@Slf4j
public class LoginUserUtils { public class LoginUserUtils {
private final static String ATT_PERMISSIONS = "permissions"; private final static String ATT_PERMISSIONS = "permissions";
@@ -131,11 +133,13 @@ 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 的场景,默认视为启用
boolean enabled = Optional.ofNullable(sysUser.getEnabled()).orElse(true);
LoginAppUser user = new LoginAppUser(sysUser.getId() LoginAppUser user = new LoginAppUser(sysUser.getId()
, sysUser.getUsername(), sysUser.getPassword() , sysUser.getUsername(), sysUser.getPassword()
, sysUser.getMobile(), sysUser.getPermissions() , sysUser.getMobile(), sysUser.getPermissions()
, sysUser.getEnabled(), true, true, true , enabled, true, true, true
, authorities); , authorities);
// 设置用户基本属性到attributes中,供租户初始化使用 // 设置用户基本属性到attributes中,供租户初始化使用
@@ -10,6 +10,9 @@ 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.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException; import java.io.IOException;
@@ -30,7 +33,11 @@ public class LoginUserFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws IOException, ServletException { FilterChain filterChain) throws IOException, ServletException {
try { try {
LoginAppUser user = LoginUserUtils.getCurrentUser(request, false); // 仅在具备认证上下文或携带 Authorization 时使用完整模式,避免在无认证的内部/健康检查请求上递归拉取用户
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String authz = request.getHeader("Authorization");
boolean shouldFull = (auth != null) || StringUtils.hasText(authz);
LoginAppUser user = LoginUserUtils.getCurrentUser(request, shouldFull);
logger.debug(request.toString()); logger.debug(request.toString());
LoginUserContextHolder.setUser(user); LoginUserContextHolder.setUser(user);
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
+37
View File
@@ -248,3 +248,40 @@ zlt:
3) 使用 APP 账号登录,重复上述步骤,观察查询仅限等值 `tenant_id = ...`。 3) 使用 APP 账号登录,重复上述步骤,观察查询仅限等值 `tenant_id = ...`。
如需进一步协助实现 `/tenant/hierarchy/*` 管理接口或自定义 SQL 处理器,请在 Issue 中说明具体诉求与表结构,我们可继续完善。 如需进一步协助实现 `/tenant/hierarchy/*` 管理接口或自定义 SQL 处理器,请在 Issue 中说明具体诉求与表结构,我们可继续完善。
---
## 11. 前端开发计划(react-web-next)
- 目标与范围
- 新增“租户管理”页面(树形结构 + 列表 + 表单),支持租户新增/编辑/删除/查询;以组件方式实现,便于复用。
- 修复并完善“租户查询组件”使用体验(`components/TenantScopeFilter` 与 `components/ui/TenantSelector`)。
- 改造“用户管理”页面:查询区分系统用户(type=BACKEND)与 C 端用户(type=APP);新增系统用户时需绑定租户(`company`),C 端用户不提供新增入口。
- 涉及模块与文件
- 前端:`zlt-web/react-web-next` 下的 pages、components、services。
- 服务调用:`src/services/tenant.ts`、`src/services/system.ts`(用户接口带上 `type` 过滤)。
- 交互与验收要点
- 租户管理
- 左侧树呈现可访问租户层级(来源:`GET /tenant/accessible`)。
- 右侧表格按选中树节点过滤;支持分页、搜索(名称/状态)。
- 新建/编辑弹窗表单包含:租户ID、名称、上级租户、类型、编码、状态、联系人/电话、地址、描述。
- 删除需二次确认;成功后同步刷新树与表。
- 租户筛选组件
- `TenantScopeFilter`:切换后调用 `POST /tenant/switch` 并通过回调通知页面刷新;修复中文文案与关闭标签错误。
- `TenantSelector`(QueryFilter 内使用):支持选择租户与“包含子租户”复选框;修复 JSX 语法错误与文案。
- 用户管理
- 查询区分:在查询栏新增“用户类型”选择(BACKEND/APP),调用 `/api-user/users` 时透传 `type` 参数(后端已支持)。
- 新建限制:当选择 APP 类型时,隐藏“新建用户”按钮;仅 BACKEND 可新建。
- 绑定租户:新建/编辑系统用户表单新增“所属租户(company)”字段(树选择)。
- 实施步骤
1) 组件化重构租户管理页:抽离 Tree、Table、Form 三个组件,页面仅作编排与状态承载。
2) 修复 `TenantScopeFilter` 与 `TenantSelector` 的中文文案与 JSX 语法问题,统一回调语义。
3) 用户管理页:新增“用户类型”查询项;根据类型控制“新建”按钮显隐;在表单中增加“所属租户(company)”字段(仅 BACKEND)。
4) 自测与联调:校验切换租户后各页面数据是否随之刷新;核对新增系统用户的 `company` 入库。
- 回滚与影响
- 仅前端改动,不涉及数据库变更;若需回滚,可恢复页面与组件的旧实现。
- 影响路由:`/system/tenant.html`、`/system/user.html`。
+35 -2
View File
@@ -13,6 +13,24 @@ export const request: any = {
errorConfig: { errorConfig: {
errorHandler(error: any) { errorHandler(error: any) {
// 统一错误处理 // 统一错误处理
// 若出现 401/403 等未授权错误,清理本地态并跳转登录
try {
const status = (error?.response?.status ?? error?.data?.code ?? error?.data?.resp_code) as number | undefined;
const unauthorized = status === 401 || status === 403;
if (unauthorized) {
try {
sessionStorage.removeItem('access_token');
sessionStorage.removeItem('current_user');
} catch {}
const pathname = typeof window !== 'undefined' ? window.location.pathname : '/';
const search = typeof window !== 'undefined' ? window.location.search : '';
const current = encodeURIComponent(`${pathname}${search}`);
const to = `/user/login?redirect=${current}`;
if (!String(pathname).startsWith('/user/login')) {
history.push(to);
}
}
} catch {}
throw error; throw error;
}, },
}, },
@@ -39,6 +57,23 @@ export const request: any = {
} as any; } as any;
(response as any).data = mapped; (response as any).data = mapped;
} }
// 未授权统一处理:HTTP 状态或业务码均触发
const httpUnauthorized = (response.status === 401 || response.status === 403);
const bizCode = (data?.resp_code ?? data?.code) as number | undefined;
const bizUnauthorized = bizCode === 401 || bizCode === 403 || bizCode === 40101 || bizCode === 40100;
if (httpUnauthorized || bizUnauthorized) {
try {
sessionStorage.removeItem('access_token');
sessionStorage.removeItem('current_user');
} catch {}
const pathname = typeof window !== 'undefined' ? window.location.pathname : '/';
const search = typeof window !== 'undefined' ? window.location.search : '';
const current = encodeURIComponent(`${pathname}${search}`);
const to = `/user/login?redirect=${current}`;
if (!String(pathname).startsWith('/user/login')) {
history.push(to);
}
}
} catch (e) { } catch (e) {
// 静默处理解析错误 // 静默处理解析错误
} }
@@ -53,8 +88,6 @@ export function onRouteChange({ location }: any) {
const isLoginPath = String(location?.pathname || '').startsWith('/user/login'); const isLoginPath = String(location?.pathname || '').startsWith('/user/login');
if (!token && !isLoginPath) { if (!token && !isLoginPath) {
history.push('/user/login'); history.push('/user/login');
} else if (token && isLoginPath) {
history.push('/welcome');
} }
} catch {} } catch {}
} }
@@ -1,4 +1,4 @@
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';
@@ -45,7 +45,7 @@ const TenantScopeFilter: React.FC<Props> = ({ onChanged }) => {
message.success('租户范围已更新'); message.success('租户范围已更新');
onChanged?.(tenantId, includeChildren); onChanged?.(tenantId, includeChildren);
} else { } else {
message.error(res.msg || '切换失败'); message.error((res as any).msg || '切换失败');
} }
} catch (e) { } catch (e) {
message.error('切换失败'); message.error('切换失败');
@@ -64,12 +64,8 @@ const TenantScopeFilter: React.FC<Props> = ({ onChanged }) => {
onChange={(val) => setTenantId(val)} onChange={(val) => setTenantId(val)}
treeData={toTreeData(tree)} treeData={toTreeData(tree)}
/> />
<Checkbox checked={includeChildren} onChange={(e) => setIncludeChildren(e.target.checked)}> <Checkbox checked={includeChildren} onChange={(e) => setIncludeChildren(e.target.checked)}>包含子租户</Checkbox>
包含子租户 <Button type="primary" onClick={handleApply}>应用</Button>
</Checkbox>
<Button type="primary" onClick={handleApply}>
应用
</Button>
</Space> </Space>
); );
}; };
@@ -1,29 +1,34 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Form, TreeSelect, Checkbox } from 'antd'; import { Form, TreeSelect, Checkbox, message } from 'antd';
import { tenantApi, TenantTreeNode } from '@/services/tenant'; import { tenantApi, TenantTreeNode } from '@/services/tenant';
export interface TenantSelectorProps { export interface TenantSelectorProps {
// 字段名可自定义;默认与后端接口约定一致 nameTenant?: string;
nameTenant?: string; // 默认 'tenantId' nameIncludeChildren?: string;
nameIncludeChildren?: string; // 默认 'includeChildren'
labelTenant?: React.ReactNode; labelTenant?: React.ReactNode;
labelIncludeChildren?: React.ReactNode; labelIncludeChildren?: React.ReactNode;
// 是否隐藏“包含下级”复选框(用于仅需要选择租户的场景,如用户表单)
hideIncludeChildren?: boolean;
} }
const toTreeData = (nodes: TenantTreeNode[] = []): any[] => const toTreeData = (nodes?: TenantTreeNode[] | any): any[] => {
nodes.map((n) => ({ const arr: TenantTreeNode[] = Array.isArray(nodes) ? nodes : [];
title: n.tenantName, return arr.map((n) => ({
value: n.tenantId, title: (n as any)?.tenantId, // 显示租户ID
key: n.tenantId, value: (n as any)?.tenantId,
children: n.children ? toTreeData(n.children) : undefined, key: (n as any)?.tenantId,
children: Array.isArray((n as any)?.children) && (n as any).children!.length ? toTreeData((n as any).children) : undefined,
})); }));
};
const TenantSelector: React.FC<TenantSelectorProps> = ({ const TenantSelector: React.FC<TenantSelectorProps> = ({
nameTenant = 'tenantId', nameTenant = 'tenantId',
nameIncludeChildren = 'includeChildren', nameIncludeChildren = 'includeChildren',
labelTenant = '租户', labelTenant = '租户',
labelIncludeChildren = '包含子租户', labelIncludeChildren = '包含下级',
hideIncludeChildren = false,
}) => { }) => {
const form = Form.useFormInstance?.();
const [tree, setTree] = useState<TenantTreeNode[]>([]); const [tree, setTree] = useState<TenantTreeNode[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -31,16 +36,57 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
(async () => { (async () => {
setLoading(true); setLoading(true);
try { try {
const [treeRes] = await Promise.all([ const treeRes: any = await tenantApi.getAccessibleTenants();
tenantApi.getAccessibleTenants(), let list: TenantTreeNode[] = [];
]); if (typeof treeRes?.success !== 'undefined') {
if (treeRes?.success) setTree(treeRes.data || []); list = treeRes.success ? (treeRes.data || []) : [];
} else if (Array.isArray(treeRes)) {
list = treeRes as TenantTreeNode[];
}
if (!list || list.length === 0) {
// 回退:仅当前租户
const cur: any = await tenantApi.getCurrentTenant();
if (cur?.success && cur?.data?.tenantId) {
list = [{ tenantId: cur.data.tenantId, tenantName: cur.data.tenantName } as any];
try { form?.setFieldsValue?.({ [nameTenant]: cur.data.tenantId, [nameIncludeChildren]: true }); } catch {}
} else {
const stats: any = await tenantApi.getScopeStats();
const id = stats?.data?.currentTenantId;
if (id) list = [{ tenantId: id, tenantName: id } as any];
try { form?.setFieldsValue?.({ [nameTenant]: id, [nameIncludeChildren]: true }); } catch {}
}
}
if (list && list.length && !form?.getFieldValue?.(nameTenant)) {
try { form?.setFieldsValue?.({ [nameTenant]: list[0].tenantId, [nameIncludeChildren]: true }); } catch {}
}
// 补齐每个根节点的一层子租户,保证能看到子级
try {
await Promise.all(
(list || []).map(async (node: any) => {
if (!node || Array.isArray(node.children)) return;
const pid = node.tenantId;
if (!pid) return;
try {
const res: any = await tenantApi.getTenantList({ parentTenantId: pid, current: 1, pageSize: 1000 } as any);
const children = res?.data?.data || [];
if (children && children.length) {
node.children = children.map((c: any) => ({ tenantId: c.tenantId, tenantName: c.tenantName }));
}
} catch {}
})
);
} catch {}
setTree(list || []);
} catch (e) {
message.warn('获取租户列表失败');
} finally { } finally {
setLoading(false); setLoading(false);
} }
})(); })();
}, []); }, []);
// 不启用懒加载,依赖后端返回的完整树;仅在“仅单根无子”时补一层直系子级(见上方 useEffect)
return ( return (
<> <>
<Form.Item name={nameTenant} label={labelTenant}> <Form.Item name={nameTenant} label={labelTenant}>
@@ -49,14 +95,16 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
treeDefaultExpandAll treeDefaultExpandAll
loading={loading} loading={loading}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder="选择租户(含子租户)" placeholder='选择租户(默认当前租户)'
treeData={toTreeData(tree)} treeData={toTreeData(tree)}
allowClear allowClear
/> />
</Form.Item> </Form.Item>
<Form.Item name={nameIncludeChildren} label={labelIncludeChildren} valuePropName="checked" initialValue={true}> {hideIncludeChildren ? null : (
<Checkbox>包含子租户</Checkbox> <Form.Item name={nameIncludeChildren} label={labelIncludeChildren} valuePropName='checked' initialValue={true}>
</Form.Item> <Checkbox>包含下级租户</Checkbox>
</Form.Item>
)}
</> </>
); );
}; };
@@ -1,4 +1,4 @@
import React from 'react'; import React from 'react';
import { Button, Tooltip } from 'antd'; import { Button, Tooltip } from 'antd';
import { MoonOutlined, SunOutlined } from '@ant-design/icons'; import { MoonOutlined, SunOutlined } from '@ant-design/icons';
import type { ThemeMode } from '@/theme'; import type { ThemeMode } from '@/theme';
@@ -8,20 +8,17 @@ export interface ThemeSwitchProps {
onToggle: () => void; onToggle: () => void;
} }
const ThemeSwitch: React.FC<ThemeSwitchProps> = ({ mode, onToggle }) => { const ThemeSwitch: React.FC<ThemeSwitchProps> = ({ mode, onToggle }) => (
return ( <Tooltip title={mode === 'dark' ? '切换为亮色' : '切换为暗色'}>
<Tooltip title={mode === 'dark' ? '切换为亮色' : '切换为暗色'}> <Button
<Button type="text"
type="text" onClick={onToggle}
onClick={onToggle} icon={mode === 'dark' ? <SunOutlined /> : <MoonOutlined />}
icon={mode === 'dark' ? <SunOutlined /> : <MoonOutlined />} style={{ color: 'var(--text-primary)' }}
style={{ color: 'var(--text-primary)' }} >
> {mode === 'dark' ? '亮色' : '暗色'}
{mode === 'dark' ? '亮色' : '暗色'} </Button>
</Button> </Tooltip>
</Tooltip> );
);
};
export default ThemeSwitch; export default ThemeSwitch;
@@ -8,14 +8,11 @@ import {
AppstoreOutlined, AppstoreOutlined,
FileTextOutlined, FileTextOutlined,
TeamOutlined, TeamOutlined,
ToolOutlined,
BarChartOutlined,
CloudServerOutlined, CloudServerOutlined,
BugOutlined, BugOutlined,
SearchOutlined, SearchOutlined,
MessageOutlined, MessageOutlined,
FolderOutlined, FolderOutlined,
SafetyOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { Link, useLocation, history } from 'umi'; import { Link, useLocation, history } from 'umi';
import ProLayout, { MenuDataItem } from '@ant-design/pro-layout'; import ProLayout, { MenuDataItem } from '@ant-design/pro-layout';
@@ -23,7 +20,6 @@ import { fetchMenuData, outLogin } from '@/services/login';
import { useTheme } from '@/theme'; import { useTheme } from '@/theme';
import { ThemeSwitch } from '@/components/ui'; import { ThemeSwitch } from '@/components/ui';
// 后端菜单节点(兼容 children 与 subMenus)
type MenuNode = { type MenuNode = {
id?: number | string; id?: number | string;
name?: string; name?: string;
@@ -56,16 +52,21 @@ const BasicLayout: React.FC = (props: any) => {
return () => { mounted = false; }; return () => { mounted = false; };
}, []); }, []);
// 将后端菜单转换为 ProLayout 菜单(对齐 react-web 映射规则)
const menuDataRender = useMemo(() => { const menuDataRender = useMemo(() => {
const mapPath = (m: MenuNode): string | undefined => { const mapPath = (m: MenuNode, childrenLen: number): string | undefined => {
const cand = (m.path || m.url || '').trim(); const cand = (m.path || m.url || '').trim();
if (!cand) return undefined; if (!cand) return undefined;
const lower = cand.toLowerCase(); const lower = cand.toLowerCase();
if (lower.startsWith('http')) return cand; // 外链 if (lower.startsWith('http')) return cand; // 外链
if (lower.endsWith('.html')) return cand.startsWith('/') ? cand : `/${cand}`; // 仅 .html 可点击 if (lower.endsWith('.html')) return cand.startsWith('/') ? cand : `/${cand}`; // 静态路由
if (lower === '/welcome' || lower === 'welcome') return '/welcome'; if (lower === '/welcome' || lower === 'welcome') return '/welcome';
return undefined; // 其余作为分组,仅展开不跳转 // 兼容后端菜单未带 .html 的叶子路由,例如 /system/tenant => /system/tenant.html
const ensureSlash = cand.startsWith('/') ? cand : `/${cand}`;
const parts = ensureSlash.split('/').filter(Boolean);
if (childrenLen === 0 && parts.length >= 2) {
return `${ensureSlash}.html`;
}
return undefined; // 作为分组
}; };
const getIcon = (p?: string) => { const getIcon = (p?: string) => {
@@ -90,12 +91,12 @@ const BasicLayout: React.FC = (props: any) => {
`${parentKey}-${menu.name}-${index}`; `${parentKey}-${menu.name}-${index}`;
const keyStr = String(stableKey); const keyStr = String(stableKey);
const path = mapPath(menu);
const childrenList: MenuNode[] = (menu.children && menu.children.length ? menu.children : (menu.subMenus || [])) || []; const childrenList: MenuNode[] = (menu.children && menu.children.length ? menu.children : (menu.subMenus || [])) || [];
const path = mapPath(menu, childrenList.length);
const item: MenuDataItem = { const item: MenuDataItem = {
key: keyStr, key: keyStr,
name: menu.name || `菜单项${index + 1}`, name: menu.name || `菜单${index + 1}`,
path, path,
icon: getIcon(path), icon: getIcon(path),
children: childrenList.map((child: MenuNode, i: number) => normalize(child, i, keyStr)), children: childrenList.map((child: MenuNode, i: number) => normalize(child, i, keyStr)),
@@ -103,13 +104,11 @@ const BasicLayout: React.FC = (props: any) => {
return item; return item;
}; };
// 首次未加载完毕前不渲染默认菜单,避免覆盖接口菜单
if (!loaded) return []; if (!loaded) return [];
const list = menus && menus.length ? menus : [{ name: '欢迎页', url: '/welcome', id: 'welcome-default' }]; const list = menus && menus.length ? menus : [{ name: '欢迎页', url: '/welcome', id: 'welcome-default' }];
return list.map((m, i) => normalize(m, i)); return list.map((m, i) => normalize(m, i));
}, [menus, mode, loaded]); }, [menus, mode, loaded]);
// 右上角操作区
const rightContentRender = () => ( const rightContentRender = () => (
<Space size="middle"> <Space size="middle">
<ThemeSwitch mode={mode} onToggle={toggle} /> <ThemeSwitch mode={mode} onToggle={toggle} />
@@ -196,7 +195,6 @@ const BasicLayout: React.FC = (props: any) => {
)} )}
token={{ token={{
sider: { sider: {
// 左侧侧边栏背景使用更柔和的浅色,避免纯白突兀
colorMenuBackground: 'var(--sider-bg)', colorMenuBackground: 'var(--sider-bg)',
colorBgMenuItemSelected: 'var(--primary-color)', colorBgMenuItemSelected: 'var(--primary-color)',
colorTextMenuSelected: '#ffffff', colorTextMenuSelected: '#ffffff',
@@ -204,7 +202,6 @@ const BasicLayout: React.FC = (props: any) => {
colorBgMenuItemHover: 'var(--bg-glass)', colorBgMenuItemHover: 'var(--bg-glass)',
}, },
header: { header: {
// 顶部导航背景采用柔和渐变
colorBgHeader: 'var(--header-bg)', colorBgHeader: 'var(--header-bg)',
colorHeaderTitle: 'var(--text-primary)', colorHeaderTitle: 'var(--text-primary)',
colorTextRightActionsItem: 'var(--text-secondary)', colorTextRightActionsItem: 'var(--text-secondary)',
+18 -123
View File
@@ -1,15 +1,6 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Card, Space, Typography, Row, Col, Statistic, Progress, Button } from 'antd'; import { Card, Space, Typography, Row, Col, Statistic, Progress, Button } from 'antd';
import { import { RocketOutlined, TeamOutlined, AppstoreOutlined, CloudServerOutlined, TrophyOutlined, ThunderboltOutlined, GlobalOutlined, SafetyOutlined } from '@ant-design/icons';
RocketOutlined,
TeamOutlined,
AppstoreOutlined,
CloudServerOutlined,
TrophyOutlined,
ThunderboltOutlined,
GlobalOutlined,
SafetyOutlined
} from '@ant-design/icons';
import TenantScopeFilter from '@/components/TenantScopeFilter'; import TenantScopeFilter from '@/components/TenantScopeFilter';
const { Title, Paragraph } = Typography; const { Title, Paragraph } = Typography;
@@ -18,24 +9,15 @@ const Welcome: React.FC = () => {
const [time, setTime] = useState(new Date()); const [time, setTime] = useState(new Date());
useEffect(() => { useEffect(() => {
let isMounted = true; const timer = setInterval(() => setTime(new Date()), 1000);
const timer = setInterval(() => { return () => clearInterval(timer);
if (isMounted) {
setTime(new Date());
}
}, 1000);
return () => {
isMounted = false;
clearInterval(timer);
};
}, []); }, []);
const stats = [ const stats = [
{ title: '今日订单', value: 1234, icon: <AppstoreOutlined />, color: '#667eea' }, { title: '今日订单', value: 1234, icon: <AppstoreOutlined />, color: '#667eea' },
{ title: '活跃用户', value: 856, icon: <TeamOutlined />, color: '#764ba2' }, { title: '活跃用户', value: 856, icon: <TeamOutlined />, color: '#764ba2' },
{ title: '设备在线', value: 98, suffix: '%', icon: <CloudServerOutlined />, color: '#f093fb' }, { title: '设备在线', value: 98, suffix: '%', icon: <CloudServerOutlined />, color: '#f093fb' },
{ title: '系统状态', value: 99.9, suffix: '%', icon: <SafetyOutlined />, color: '#4facfe' }, { title: '系统可用率', value: 99.9, suffix: '%', icon: <SafetyOutlined />, color: '#4facfe' },
]; ];
const quickActions = [ const quickActions = [
@@ -47,29 +29,15 @@ const Welcome: React.FC = () => {
return ( return (
<div className="page-enter" style={{ padding: 24 }}> <div className="page-enter" style={{ padding: 24 }}>
{/* 欢迎横幅 */} <Card className="modern-card" style={{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', border: 'none', marginBottom: 24, color: 'white' }}>
<Card
className="modern-card"
style={{
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
border: 'none',
marginBottom: 24,
color: 'white'
}}
>
<Row align="middle" justify="space-between"> <Row align="middle" justify="space-between">
<Col> <Col>
<Space direction="vertical" size={8}> <Space direction="vertical" size={8}>
<Title level={2} style={{ color: 'white', margin: 0 }}> <Title level={2} style={{ color: 'white', margin: 0 }}>
<RocketOutlined style={{ marginRight: 12 }} /> <RocketOutlined style={{ marginRight: 12 }} /> 欢迎使用 Go-Fly Admin
欢迎使用 Go-Fly Admin
</Title> </Title>
<Paragraph style={{ color: 'rgba(255,255,255,0.8)', margin: 0, fontSize: 16 }}> <Paragraph style={{ color: 'rgba(255,255,255,0.8)', margin: 0, fontSize: 16 }}>现代化的智能管理平台 · 科技驱动未来</Paragraph>
现代化的智能管理平台 · 科技驱动未来 <Paragraph style={{ color: 'rgba(255,255,255,0.6)', margin: 0 }}>当前时间:{time.toLocaleString()}</Paragraph>
</Paragraph>
<Paragraph style={{ color: 'rgba(255,255,255,0.6)', margin: 0 }}>
当前时间:{time.toLocaleString()}
</Paragraph>
</Space> </Space>
</Col> </Col>
<Col> <Col>
@@ -78,45 +46,20 @@ const Welcome: React.FC = () => {
</Row> </Row>
</Card> </Card>
{/* 数据统计卡片 */}
<Row gutter={[24, 24]} style={{ marginBottom: 24 }}> <Row gutter={[24, 24]} style={{ marginBottom: 24 }}>
{stats.map((stat, index) => ( {stats.map((stat, index) => (
<Col xs={12} sm={12} md={6} key={index}> <Col xs={12} sm={12} md={6} key={index}>
<Card <Card className="modern-card" style={{ textAlign: 'center', borderLeft: `4px solid ${stat.color}`, background: 'var(--bg-card)' }}>
className="modern-card" <div style={{ color: stat.color, fontSize: 24, marginBottom: 8 }}>{stat.icon}</div>
style={{ <Statistic title={stat.title} value={stat.value} suffix={stat.suffix} valueStyle={{ color: 'var(--text-primary)', fontSize: 28, fontWeight: 'bold' }} />
textAlign: 'center',
borderLeft: `4px solid ${stat.color}`,
background: 'var(--bg-card)'
}}
>
<div style={{ color: stat.color, fontSize: 24, marginBottom: 8 }}>
{stat.icon}
</div>
<Statistic
title={stat.title}
value={stat.value}
suffix={stat.suffix}
valueStyle={{
color: 'var(--text-primary)',
fontSize: 28,
fontWeight: 'bold'
}}
/>
</Card> </Card>
</Col> </Col>
))} ))}
</Row> </Row>
<Row gutter={[24, 24]}> <Row gutter={[24, 24]}>
{/* 系统状态 */}
<Col xs={24} md={12}> <Col xs={24} md={12}>
<Card className="modern-card" title={ <Card className="modern-card" title={<span style={{ color: 'var(--text-primary)' }}><ThunderboltOutlined style={{ marginRight: 8, color: '#667eea' }} />系统状态</span>}>
<span style={{ color: 'var(--text-primary)' }}>
<ThunderboltOutlined style={{ marginRight: 8, color: '#667eea' }} />
系统状态
</span>
}>
<Space direction="vertical" style={{ width: '100%' }} size={16}> <Space direction="vertical" style={{ width: '100%' }} size={16}>
<div> <div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}> <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
@@ -143,14 +86,8 @@ const Welcome: React.FC = () => {
</Card> </Card>
</Col> </Col>
{/* 快捷操作 */}
<Col xs={24} md={12}> <Col xs={24} md={12}>
<Card className="modern-card" title={ <Card className="modern-card" title={<span style={{ color: 'var(--text-primary)' }}><TrophyOutlined style={{ marginRight: 8, color: '#667eea' }} />快捷操作</span>}>
<span style={{ color: 'var(--text-primary)' }}>
<TrophyOutlined style={{ marginRight: 8, color: '#667eea' }} />
快捷操作
</span>
}>
<Row gutter={[16, 16]}> <Row gutter={[16, 16]}>
{quickActions.map((action, index) => ( {quickActions.map((action, index) => (
<Col span={12} key={index}> <Col span={12} key={index}>
@@ -158,16 +95,7 @@ const Welcome: React.FC = () => {
block block
size="large" size="large"
className="tech-button" className="tech-button"
style={{ style={{ height: 64, background: `linear-gradient(135deg, ${action.color}33, ${action.color}11)`, border: `1px solid ${action.color}44`, color: action.color, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}
height: 64,
background: `linear-gradient(135deg, ${action.color}33, ${action.color}11)`,
border: `1px solid ${action.color}44`,
color: action.color,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center'
}}
> >
<div style={{ fontSize: 20, marginBottom: 4 }}>{action.icon}</div> <div style={{ fontSize: 20, marginBottom: 4 }}>{action.icon}</div>
<div style={{ fontSize: 12 }}>{action.title}</div> <div style={{ fontSize: 12 }}>{action.title}</div>
@@ -179,45 +107,13 @@ const Welcome: React.FC = () => {
</Col> </Col>
</Row> </Row>
{/* 功能介绍 */} <Card className="modern-card" style={{ marginTop: 24 }} title={<span style={{ color: 'var(--text-primary)' }}><GlobalOutlined style={{ marginRight: 8, color: '#667eea' }} />平台特性</span>}>
<Card className="modern-card" style={{ marginTop: 24 }} title={
<span style={{ color: 'var(--text-primary)' }}>
<GlobalOutlined style={{ marginRight: 8, color: '#667eea' }} />
平台特性
</span>
}>
<Row gutter={[24, 24]}> <Row gutter={[24, 24]}>
<Col xs={24} sm={12} md={8}> <Col xs={24} sm={12} md={8}>
<div style={{ textAlign: 'center', padding: 16 }}> <div style={{ textAlign: 'center', padding: 16 }}>
<div style={{ fontSize: 32, color: '#667eea', marginBottom: 12 }}> <div style={{ fontSize: 32, color: '#667eea', marginBottom: 12 }}><RocketOutlined /></div>
<RocketOutlined />
</div>
<Title level={4} style={{ color: 'var(--text-primary)' }}>高性能架构</Title> <Title level={4} style={{ color: 'var(--text-primary)' }}>高性能架构</Title>
<Paragraph style={{ color: 'var(--text-secondary)' }}> <Paragraph style={{ color: 'var(--text-secondary)' }}>基于微服务架构,支持高并发访问,确保系统稳定运行</Paragraph>
基于微服务架构,支持高并发访问,确保系统稳定运行
</Paragraph>
</div>
</Col>
<Col xs={24} sm={12} md={8}>
<div style={{ textAlign: 'center', padding: 16 }}>
<div style={{ fontSize: 32, color: '#764ba2', marginBottom: 12 }}>
<SafetyOutlined />
</div>
<Title level={4} style={{ color: 'var(--text-primary)' }}>安全可靠</Title>
<Paragraph style={{ color: 'var(--text-secondary)' }}>
多层安全防护,数据加密传输,保障业务数据安全
</Paragraph>
</div>
</Col>
<Col xs={24} sm={12} md={8}>
<div style={{ textAlign: 'center', padding: 16 }}>
<div style={{ fontSize: 32, color: '#f093fb', marginBottom: 12 }}>
<ThunderboltOutlined />
</div>
<Title level={4} style={{ color: 'var(--text-primary)' }}>智能运维</Title>
<Paragraph style={{ color: 'var(--text-secondary)' }}>
实时监控预警,自动化运维管理,降低运维成本
</Paragraph>
</div> </div>
</Col> </Col>
</Row> </Row>
@@ -227,4 +123,3 @@ const Welcome: React.FC = () => {
}; };
export default Welcome; export default Welcome;
@@ -1,165 +1,237 @@
import React, { useEffect, useMemo, useRef, useState } from 'react'; import React, { useCallback, useEffect, useState } from "react";
import type { ActionType, ProColumns } from '@ant-design/pro-components'; import { PageContainer } from "@ant-design/pro-components";
import { ModalForm, PageContainer, ProForm, ProFormText, ProFormTextArea, ProTable } from '@ant-design/pro-components'; import { Space, message, Button } from "antd";
import { Button, Card, Col, Form, message, Popconfirm, Row, Space, Switch, Tree, TreeSelect } from 'antd'; import { ActionBar, GradientButton, GlassCard } from "@/components/ui";
import { PlusOutlined } from '@ant-design/icons'; import { PlusOutlined } from "@ant-design/icons";
import { tenantApi, TenantInfo, TenantTreeNode } from '@/services/tenant'; import TenantForm from "./components/TenantForm";
import { ActionBar, SearchBarPlus } from '@/components/ui'; import TenantTreeTable from "./components/TenantTreeTable";
import { tenantApi, TenantInfo, TenantTreeNode } from "@/services/tenant";
const toTreeData = (nodes: TenantTreeNode[] = []): any[] => // UI 表单初始值:status 允许 boolean | number,便于与 Switch 绑定
nodes.map((n) => ({ title: n.tenantName, value: n.tenantId, key: n.tenantId, children: n.children ? toTreeData(n.children) : undefined })); type UITenantFormValues = Partial<TenantInfo> & { status?: boolean | number };
const TenantManage: React.FC = () => { const TenantManage: React.FC = () => {
const actionRef = useRef<ActionType>(); const [data, setData] = useState<TenantTreeNode[]>([]);
const [form] = Form.useForm<TenantInfo>(); const [loading, setLoading] = useState(false);
const [orgTree, setOrgTree] = useState<TenantTreeNode[]>([]); const [formOpen, setFormOpen] = useState(false);
const [loadingTree, setLoadingTree] = useState(false);
const [currentNode, setCurrentNode] = useState<string | undefined>(undefined);
const [visible, setVisible] = useState(false);
const [editing, setEditing] = useState(false); const [editing, setEditing] = useState(false);
const [initialValues, setInitialValues] = useState<UITenantFormValues | undefined>(undefined);
const [treeCache, setTreeCache] = useState<TenantTreeNode[]>([]);
const treeSelectData = useMemo(() => toTreeData(orgTree), [orgTree]); const fetchTree = useCallback(async () => {
setLoading(true);
const loadTree = async () => {
setLoadingTree(true);
try { try {
const res = await tenantApi.getAccessibleTenants(); const res: any = await tenantApi.getAccessibleTenants();
if (res.success) setOrgTree(res.data || []); let list: TenantTreeNode[] = [];
} finally { if (typeof res?.success !== "undefined") {
setLoadingTree(false); list = res.success ? (res.data || []) : [];
} else if (Array.isArray(res)) {
list = res as TenantTreeNode[];
}
if (!list || list.length === 0) {
// 回退:至少返回当前租户
const cur: any = await tenantApi.getCurrentTenant();
if (cur?.success && cur?.data?.tenantId) {
list = [{ tenantId: cur.data.tenantId, tenantName: cur.data.tenantName } as any];
} else {
const stats: any = await tenantApi.getScopeStats();
const id = stats?.data?.currentTenantId;
if (id) list = [{ tenantId: id, tenantName: id } as any];
}
}
// 若只有根节点且无子节点,尝试加载一层子租户以展示层级
if (list && list.length === 1 && !Array.isArray((list[0] as any).children)) {
try {
const parentId = (list[0] as any).tenantId;
const resPage: any = await tenantApi.getTenantList({ parentTenantId: parentId, current: 1, pageSize: 1000 } as any);
const children = resPage?.data?.data || [];
if (children && children.length) {
(list[0] as any).children = children.map((c: any) => ({ tenantId: c.tenantId, tenantName: c.tenantName, tenantType: c.tenantType, status: c.status, contactPerson: c.contactPerson, contactPhone: c.contactPhone }));
}
} catch {}
}
// 补充每个根的一层直接子租户,便于默认展开时可见
try {
await Promise.all(
(list || []).map(async (node: any) => {
if (!node) return;
// 顶层节点缺失类型/状态/联系人信息时,补充详情
try {
if (node.tenantType == null || node.status == null || node.contactPerson == null || node.contactPhone == null) {
const detail: any = await tenantApi.getTenantDetail(node.tenantId);
const d = detail?.data || {};
if (node.tenantType == null) node.tenantType = d.tenantType;
if (node.status == null) node.status = d.status;
if (node.contactPerson == null) node.contactPerson = d.contactPerson;
if (node.contactPhone == null) node.contactPhone = d.contactPhone;
}
} catch {}
// 确保至少补一层孩子,方便默认展开后可见
if (!Array.isArray(node.children) || node.children.length === 0) {
const resp: any = await tenantApi.getTenantList({ parentTenantId: node.tenantId, current: 1, pageSize: 1000 } as any);
const children = resp?.data?.data || [];
if (children && children.length) {
node.children = children.map((c: any) => ({ tenantId: c.tenantId, tenantName: c.tenantName, tenantType: c.tenantType, status: c.status, contactPerson: c.contactPerson, contactPhone: c.contactPhone }));
}
}
})
);
} catch {}
setTreeCache(list);
setData(list);
} catch (e) {
message.error("获取租户数据失败");
} finally { setLoading(false); }
}, []);
useEffect(() => { fetchTree(); }, [fetchTree]);
const openCreateRoot = () => {
setEditing(false);
setInitialValues({ status: 1 });
setFormOpen(true);
};
const handleAddChild = (record: TenantTreeNode) => {
setEditing(false);
setInitialValues({ parentTenantId: record.tenantId, status: 1 });
setFormOpen(true);
};
const handleEdit = async (record: TenantTreeNode) => {
try {
const d: any = await tenantApi.getTenantDetail(record.tenantId);
if (d?.success) {
setEditing(true);
const iv = d.data || {};
const patched = { ...iv, status: typeof iv.status === 'number' ? iv.status : (iv.status ? 1 : 0) } as any;
setInitialValues(patched);
setFormOpen(true);
}
} catch (e) {
message.error("获取租户详情失败");
} }
}; };
useEffect(() => { loadTree(); }, []); const handleDelete = async (record: TenantTreeNode) => {
const hide = message.loading("删除中...");
const columns: ProColumns<TenantInfo>[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '租户ID', dataIndex: 'tenantId', copyable: true },
{ title: '租户名称', dataIndex: 'tenantName' },
{ title: '类型', dataIndex: 'tenantType' },
{ title: '父租户ID', dataIndex: 'parentTenantId', hideInSearch: true },
{ title: '状态', dataIndex: 'status', valueType: 'select', valueEnum: { 1: { text: '启用' }, 0: { text: '停用' } } },
{
title: '操作', valueType: 'option', width: 200,
render: (_, record) => (
<Space>
<a onClick={async () => {
setEditing(true);
const d = await tenantApi.getTenantDetail(record.tenantId);
if (d.success) {
form.setFieldsValue(d.data);
setVisible(true);
}
}}>编辑</a>
<Popconfirm title={`确认删除租户[${record.tenantName}]?`} onConfirm={async () => {
const hide = message.loading('删除中...');
try {
const r = await tenantApi.deleteTenant(record.tenantId);
if (r.success) {
message.success('删除成功');
actionRef.current?.reload();
loadTree();
} else {
message.error(r.msg || '删除失败');
}
} finally { hide(); }
}}>
<a>删除</a>
</Popconfirm>
</Space>
)
}
];
const onSave = async (vals: TenantInfo) => {
const hide = message.loading('保存中...');
try { try {
const payload = { ...vals, status: vals.status ?? 1 }; const r: any = await tenantApi.deleteTenant(record.tenantId);
const res = editing ? await tenantApi.updateTenant(payload) : await tenantApi.createTenant(payload); if (r?.success) {
if (res.success) { message.success("删除成功");
message.success(editing ? '修改成功' : '新增成功'); fetchTree();
setVisible(false); } else {
actionRef.current?.reload(); message.error(r?.msg || "删除失败");
loadTree();
return true;
} }
message.error(res.msg || '保存失败');
return false;
} finally { hide(); } } finally { hide(); }
}; };
return ( return (
<PageContainer header={{ title: '租户管理' }}> <PageContainer header={{ title: "租户管理" }}>
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => { actionRef.current?.reload(); loadTree(); }} />
<ActionBar <ActionBar
right={( left={(
<Space> <Space>
<Button size="middle" type="primary" icon={<PlusOutlined />} onClick={() => { <GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={openCreateRoot}>新增</GradientButton>
setEditing(false); <Button onClick={fetchTree}>刷新</Button>
form.resetFields();
form.setFieldsValue({ parentTenantId: currentNode, status: 1 });
setVisible(true);
}}>新增租户</Button>
</Space> </Space>
)} )}
/> />
<Row gutter={16}>
<Col span={6}>
<Card size="small" title="组织">
<Tree treeData={toTreeData(orgTree)} defaultExpandAll onSelect={(keys) => {
const k = (keys && keys[0]) as string | undefined;
setCurrentNode(k);
actionRef.current?.reload();
}} />
</Card>
</Col>
<Col span={18}>
<ProTable<TenantInfo>
actionRef={actionRef}
rowKey="tenantId"
columns={columns}
toolBarRender={false}
request={async (p) => {
const res = await tenantApi.getTenantList({ parentTenantId: currentNode, 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.data?.data || [];
const total = res.data?.total || list.length;
return { data: list, total, success: true };
}}
pagination={{ pageSize: 10 }}
search={{ labelWidth: 'auto' }}
/>
</Col>
</Row>
<ModalForm<TenantInfo> <GlassCard>
title={editing ? '编辑租户' : '新建租户'} <TenantTreeTable
open={visible} data={data}
onOpenChange={setVisible} loading={loading}
form={form} onAddChild={handleAddChild}
width={640} onEdit={handleEdit}
onFinish={onSave} onDelete={handleDelete}
modalProps={{ destroyOnClose: true }} />
> </GlassCard>
<ProForm.Group>
<ProFormText name="tenantId" label="租户ID" rules={[{ required: true }]} disabled={editing} /> <TenantForm
<ProFormText name="tenantName" label="租户名称" rules={[{ required: true }]} /> title={editing ? "编辑租户" : "新建租户"}
</ProForm.Group> visible={formOpen}
<ProForm.Group> onVisibleChange={setFormOpen}
<ProForm.Item name="parentTenantId" label="上级租户"> onFinish={async (values) => {
<TreeSelect style={{ width: 260 }} allowClear dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} treeDefaultExpandAll treeData={treeSelectData} /> const hide = message.loading("保存中...");
</ProForm.Item> try {
<ProFormText name="tenantType" label="类型" rules={[{ required: true }]} /> const payload: any = { ...initialValues, ...values };
</ProForm.Group> payload.status = typeof payload.status === 'boolean' ? (payload.status ? 1 : 0) : (payload.status ?? 1);
<ProFormText name="tenantCode" label="租户编码" /> // 计算 tenantPath / tenantLevel(后端未计算或为null时做兜底)
<ProFormText name="contactPerson" label="联系人" /> if (!editing) {
<ProFormText name="contactPhone" label="联系电话" /> if (payload.parentTenantId) {
<ProFormText name="address" label="地址" /> try {
<ProFormTextArea name="description" label="描述" /> const parent: any = await tenantApi.getTenantDetail(payload.parentTenantId);
<ProForm.Item name="status" label="状态" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></ProForm.Item> const p = parent?.data || {};
</ModalForm> const base = p.tenantPath || p.tenantId || '';
payload.tenantPath = base ? `${base}/${payload.tenantId}` : payload.tenantId;
payload.tenantLevel = (p.tenantLevel || 0) + 1;
} catch {
payload.tenantPath = payload.parentTenantId ? `${payload.parentTenantId}/${payload.tenantId}` : payload.tenantId;
payload.tenantLevel = 1;
}
} else {
payload.tenantPath = payload.tenantId;
payload.tenantLevel = 1;
}
}
// 编辑模式下兜底补齐关键字段,防止后端校验失败
if (editing) {
try {
const cur: any = await tenantApi.getTenantDetail(payload.tenantId);
const cd = cur?.data || {};
if (!payload.parentTenantId && cd.parentTenantId) payload.parentTenantId = cd.parentTenantId;
const joinPath = (base?: string, id?: string) => {
const b = String(base || '').replace(/\/+$/g, '').replace(/^null/gi, '');
const t = String(id || '').replace(/^\/+/, '');
return b ? `${b}/${t}` : t;
};
const badPath = !payload.tenantPath || /^null/i.test(String(payload.tenantPath)) || /\/$/.test(String(payload.tenantPath));
if (badPath) {
let base = '';
if (payload.parentTenantId) {
try {
const pRes: any = await tenantApi.getTenantDetail(payload.parentTenantId);
const p = pRes?.data || {};
base = p.tenantPath || p.tenantId || payload.parentTenantId;
} catch { base = payload.parentTenantId; }
}
payload.tenantPath = joinPath(base, payload.tenantId);
}
if (payload.tenantLevel == null) {
payload.tenantLevel = cd.tenantLevel ?? 1;
}
} catch {}
}
// 仅提交后端可识别字段,避免多余只读字段导致绑定失败
const allowedKeys = ['tenantId','tenantName','parentTenantId','tenantType','tenantCode','contactPerson','contactPhone','address','description','status','tenantLevel','tenantPath'];
const submitData: any = {};
for (const k of allowedKeys) if (Object.prototype.hasOwnProperty.call(payload, k)) submitData[k] = (payload as any)[k];
const res: any = editing ? await tenantApi.updateTenant(submitData) : await tenantApi.createTenant(submitData);
if (res?.success) {
message.success(editing ? "修改成功" : "新增成功");
setFormOpen(false);
await fetchTree();
return true;
}
message.error(res?.msg || "保存失败");
return false;
} finally { hide(); }
}}
initialValues={initialValues}
tree={treeCache}
/>
</PageContainer> </PageContainer>
); );
}; };
export default TenantManage; export default TenantManage;
@@ -1,4 +1,4 @@
import React from 'react'; import React from 'react';
import { Button, Upload } from 'antd'; import { Button, Upload } from 'antd';
import { ExportOutlined, ImportOutlined, PlusOutlined } from '@ant-design/icons'; import { ExportOutlined, ImportOutlined, PlusOutlined } from '@ant-design/icons';
import { GradientButton } from '@/components/ui'; import { GradientButton } from '@/components/ui';
@@ -8,13 +8,17 @@ export interface ToolbarProps {
onCreate: () => void; onCreate: () => void;
// 导出 // 导出
onExport: () => void; onExport: () => void;
// 是否隐藏“新增”按钮(例如:APP 用户)
hideCreate?: boolean;
} }
// 统一:新增按钮固定在左侧;去掉刷新按钮(以查询为主) // 统一:新增按钮固定在左侧;去掉刷新按钮(以查询为主)
const Toolbar: React.FC<ToolbarProps> = ({ onCreate, onExport }) => { const Toolbar: React.FC<ToolbarProps> = ({ onCreate, onExport, hideCreate }) => {
return ( return (
<> <>
<GradientButton size="middle" key="add" type="primary" icon={<PlusOutlined />} onClick={onCreate}>新增</GradientButton> {!hideCreate ? (
<GradientButton size="middle" key="add" type="primary" icon={<PlusOutlined />} onClick={onCreate}>新增</GradientButton>
) : null}
<Button size="middle" key="export" icon={<ExportOutlined />} onClick={onExport}>导出</Button> <Button size="middle" key="export" icon={<ExportOutlined />} onClick={onExport}>导出</Button>
<Upload key="import" action="/api-user/users/import" showUploadList={false} accept=".xls,.xlsx"> <Upload key="import" action="/api-user/users/import" showUploadList={false} accept=".xls,.xlsx">
<Button size="middle" icon={<ImportOutlined />}>导入</Button> <Button size="middle" icon={<ImportOutlined />}>导入</Button>
@@ -24,4 +28,3 @@ const Toolbar: React.FC<ToolbarProps> = ({ onCreate, onExport }) => {
}; };
export default Toolbar; export default Toolbar;
@@ -1,23 +1,26 @@
import React from 'react'; import React from 'react';
import { ModalForm, ProForm, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components'; import { ModalForm, ProForm, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { systemApi, UserItem } from '@/services/system'; import { systemApi, UserItem } from '@/services/system';
import TenantSelector from '@/components/ui/TenantSelector';
export interface UserFormProps { export interface UserFormProps {
open: boolean; visible: boolean;
title: string; title: string;
initialValues?: Partial<UserItem>; initialValues?: Partial<UserItem & { company?: string; type?: string }>;
onOpenChange: (v: boolean) => void; onVisibleChange: (v: boolean) => void;
onFinish: (values: UserItem) => Promise<boolean>; onFinish: (values: UserItem & { company?: string; type?: string }) => Promise<boolean>;
// 是否显示“所属租户”(company)选择(仅系统用户需要)
showCompany?: boolean;
} }
const UserForm: React.FC<UserFormProps> = ({ open, title, initialValues, onOpenChange, onFinish }) => { const UserForm: React.FC<UserFormProps> = ({ visible, title, initialValues, onVisibleChange, onFinish, showCompany = true }) => {
return ( return (
<ModalForm<UserItem> <ModalForm<UserItem & { company?: string; type?: string }>
title={title} title={title}
visible={open} visible={visible}
onVisibleChange={onOpenChange} onVisibleChange={onVisibleChange}
onFinish={onFinish} onFinish={onFinish}
initialValues={initialValues} initialValues={{ type: 'BACKEND', ...(initialValues || {}) }}
modalProps={{ destroyOnClose: true }} modalProps={{ destroyOnClose: true }}
> >
<ProForm.Group> <ProForm.Group>
@@ -27,9 +30,17 @@ const UserForm: React.FC<UserFormProps> = ({ open, title, initialValues, onOpenC
</ProForm.Group> </ProForm.Group>
<ProFormRadio.Group name="sex" label="性别" options={[{ label: '男', value: 0 }, { label: '女', value: 1 }]} /> <ProFormRadio.Group name="sex" label="性别" options={[{ label: '男', value: 0 }, { label: '女', value: 1 }]} />
<ProFormSelect name="roleIds" label="角色" mode="multiple" request={systemApi.roles} placeholder="选择角色" /> <ProFormSelect name="roleIds" label="角色" mode="multiple" request={systemApi.roles} placeholder="选择角色" />
{showCompany ? (
<TenantSelector nameTenant="company" labelTenant="所属租户" hideIncludeChildren />
) : null}
<ProFormTextArea name="remark" label="备注" /> <ProFormTextArea name="remark" label="备注" />
{/* 类型固定为系统用户,默认也会按 BACKEND 新建 */}
<ProFormText name="type" label="用户类型" initialValue="BACKEND" disabled hidden />
</ModalForm> </ModalForm>
); );
}; };
export default UserForm; export default UserForm;
@@ -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';
@@ -1,5 +1,5 @@
import React, { useRef, useState } from 'react'; import React, { useRef, useState } from 'react';
import { PageContainer, ProFormText } from '@ant-design/pro-components'; import { PageContainer, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { message } from 'antd'; import { message } from 'antd';
import { ActionBar, GlassCard, SearchBarPlus } from '@/components/ui'; import { ActionBar, GlassCard, SearchBarPlus } from '@/components/ui';
import { systemApi, UserItem } from '@/services/system'; import { systemApi, UserItem } from '@/services/system';
@@ -9,15 +9,15 @@ import UserForm from './components/UserForm';
const UsersPage: React.FC = () => { const UsersPage: React.FC = () => {
const tableRef = useRef<UserTableRef>(null); const tableRef = useRef<UserTableRef>(null);
const [params, setParams] = useState<Record<string, any>>({}); const [params, setParams] = useState<Record<string, any>>({ type: 'BACKEND' });
const [createVisible, setCreateVisible] = useState(false); const [createVisible, setCreateVisible] = useState(false);
const [editVisible, setEditVisible] = useState(false); const [editVisible, setEditVisible] = useState(false);
const [currentRow, setCurrentRow] = useState<UserItem | undefined>(undefined); const [currentRow, setCurrentRow] = useState<UserItem | undefined>(undefined);
const addUser = async (values: UserItem) => { const addUser = async (values: UserItem & { company?: string; type?: string }) => {
const hide = message.loading('正在添加'); const hide = message.loading('正在添加');
try { try {
const res = await systemApi.saveOrUpdateUser(values); await systemApi.saveOrUpdateUser({ ...(values as any), roleId: (values as any)?.roleIds ? (values as any).roleIds.join(',') : (values as any)?.roleId } as any);
hide(); hide();
message.success('添加用户成功'); message.success('添加用户成功');
tableRef.current?.reload(); tableRef.current?.reload();
@@ -29,10 +29,10 @@ const UsersPage: React.FC = () => {
} }
}; };
const editUser = async (values: UserItem) => { const editUser = async (values: UserItem & { company?: string; type?: string }) => {
const hide = message.loading('正在更新'); const hide = message.loading('正在更新');
try { try {
const res = await systemApi.saveOrUpdateUser({ ...currentRow, ...values }); await systemApi.saveOrUpdateUser({ ...(currentRow as any), ...(values as any), roleId: (values as any)?.roleIds ? (values as any).roleIds.join(',') : (values as any)?.roleId } as any);
hide(); hide();
message.success('修改用户成功'); message.success('修改用户成功');
tableRef.current?.reload(); tableRef.current?.reload();
@@ -44,19 +44,6 @@ const UsersPage: React.FC = () => {
} }
}; };
const switchEnabled = async (record: UserItem) => {
const hide = message.loading('正在更新');
try {
await systemApi.updateEnabled(record.id!, !record.enabled);
hide();
message.success('修改用户成功');
tableRef.current?.reload();
} catch (e) {
hide();
message.error('修改用户失败');
}
};
const resetPwd = async (record: UserItem) => { const resetPwd = async (record: UserItem) => {
const hide = message.loading('正在更新'); const hide = message.loading('正在更新');
try { try {
@@ -82,16 +69,11 @@ const UsersPage: React.FC = () => {
} }
}; };
const isAppType = params?.type === 'APP';
return ( return (
<PageContainer header={{ title: '用户管理' }}> <PageContainer header={{ title: '用户管理' }}>
<ActionBar <ActionBar left={<Toolbar onCreate={() => setCreateVisible(true)} onExport={() => systemApi.exportUser()} hideCreate={isAppType} />} />
left={
<Toolbar
onCreate={() => setCreateVisible(true)}
onExport={() => systemApi.exportUser()}
/>
}
/>
<SearchBarPlus <SearchBarPlus
defaultCollapsed={false} defaultCollapsed={false}
@@ -103,6 +85,7 @@ const UsersPage: React.FC = () => {
tableRef.current?.reload(); tableRef.current?.reload();
}} }}
> >
<ProFormSelect name="type" label="用户类型" valueEnum={{ BACKEND: '系统用户', APP: 'C端用户' }} initialValue="BACKEND" />
<ProFormText name="username" label="用户名" placeholder="请输入用户名" /> <ProFormText name="username" label="用户名" placeholder="请输入用户名" />
<ProFormText name="mobile" label="手机号" placeholder="请输入手机号" /> <ProFormText name="mobile" label="手机号" placeholder="请输入手机号" />
</SearchBarPlus> </SearchBarPlus>
@@ -117,24 +100,14 @@ const UsersPage: React.FC = () => {
/> />
</GlassCard> </GlassCard>
{/* 新建 */} {/* 新建(仅系统用户) */}
<UserForm <UserForm title="新建用户" visible={createVisible} onVisibleChange={setCreateVisible} onFinish={addUser} showCompany={!isAppType ? true : false} />
title="新建用户"
open={createVisible}
onOpenChange={setCreateVisible}
onFinish={addUser}
/>
{/* 编辑 */} {/* 编辑 */}
<UserForm <UserForm title="修改用户" visible={editVisible} onVisibleChange={setEditVisible} onFinish={editUser} initialValues={currentRow} showCompany={!isAppType ? true : false} />
title="修改用户"
open={editVisible}
onOpenChange={setEditVisible}
onFinish={editUser}
initialValues={currentRow}
/>
</PageContainer> </PageContainer>
); );
}; };
export default UsersPage; export default UsersPage;
@@ -1,4 +1,4 @@
import { request } from 'umi'; import { request } from 'umi';
import { download } from '@/utils/download'; import { download } from '@/utils/download';
export interface UserItem { export interface UserItem {
@@ -11,6 +11,9 @@ export interface UserItem {
createTime?: string; createTime?: string;
roleId?: string; // 角色ID(逗号分隔) roleId?: string; // 角色ID(逗号分隔)
roles?: Array<{ id: number; name: string; code: string }>; roles?: Array<{ id: number; name: string; code: string }>;
// 扩展字段:前端使用(后端已支持)
type?: 'BACKEND' | 'APP';
company?: string; // 所属租户ID
} }
export interface PageParams { export interface PageParams {
@@ -33,7 +36,7 @@ export const systemApi = {
}, },
// 保存/更新 // 保存/更新
saveOrUpdateUser: async (data: UserItem) => { saveOrUpdateUser: async (data: Partial<UserItem>) => {
const res = await request('/api-user/users/saveOrUpdate', { method: 'POST', data }); const res = await request('/api-user/users/saveOrUpdate', { method: 'POST', data });
return (res as any).data || res; return (res as any).data || res;
}, },
@@ -91,4 +94,3 @@ export const systemApi = {
return list.map((r: any) => ({ label: r.name, value: r.id })); return list.map((r: any) => ({ label: r.name, value: r.id }));
}, },
}; };
+44 -9
View File
@@ -38,19 +38,54 @@ export interface TenantInfo {
} }
export const tenantApi = { export const tenantApi = {
getAccessibleTenants: () => request('/tenant/accessible', { method: 'GET' }), // 可访问租户树(保持后端原始返回,避免破坏既有前端逻辑)
switchTenant: (tenantId: string) => request('/tenant/switch', { method: 'POST', params: { tenantId } }), getAccessibleTenants: () => request('/api-user/tenant/accessible', { method: 'GET' }),
getCurrentTenant: () => request('/tenant/current', { method: 'GET' }), // 切换当前查询租户(新)
resetToDefaultTenant: () => request('/tenant/reset', { method: 'POST' }), switchTenant: (tenantId: string) => request('/api-user/tenant/switch-query', { method: 'POST', params: { tenantId } }),
createTenant: (data: Partial<TenantInfo>) => request('/tenant/hierarchy/create', { method: 'POST', data }), // 当前租户详情(新)
updateTenant: (data: Partial<TenantInfo>) => request('/tenant/hierarchy/update', { method: 'PUT', data }), getCurrentTenant: () => request('/api-user/tenant/current/info', { method: 'GET' }),
deleteTenant: (tenantId: string) => request(`/tenant/hierarchy/delete`, { method: 'DELETE', params: { tenantId } }), // 当前查询范围统计(新)
getScopeStats: () => request('/api-user/tenant/scope/stats', { method: 'GET' }),
// 重置为默认租户
resetToDefaultTenant: () => request('/api-user/tenant/reset', { method: 'POST' }),
// 租户层级 CRUD
createTenant: async (data: Partial<TenantInfo>) => {
const res: any = await request('/api-user/tenant/hierarchy/create', { method: 'POST', data });
// 兼容 resp_code 结构
if (typeof res?.resp_code !== 'undefined') return { success: res.resp_code === 0, msg: res.resp_msg, data: res.data } as any;
if (typeof res?.success !== 'undefined') return res;
return { success: true, data: res } as any;
},
updateTenant: async (data: Partial<TenantInfo>) => {
const res: any = await request('/api-user/tenant/hierarchy/update', { method: 'PUT', data });
if (typeof res?.resp_code !== 'undefined') return { success: res.resp_code === 0, msg: res.resp_msg, data: res.data } as any;
if (typeof res?.success !== 'undefined') return res;
return { success: true, data: res } as any;
},
deleteTenant: async (tenantId: string) => {
const res: any = await request('/api-user/tenant/hierarchy/delete', { method: 'DELETE', params: { tenantId } });
if (typeof res?.resp_code !== 'undefined') return { success: res.resp_code === 0, msg: res.resp_msg, data: res.data } as any;
if (typeof res?.success !== 'undefined') return res;
return { success: true, data: res } as any;
},
getTenantList: (params: { parentTenantId?: string; tenantName?: string; status?: number; current?: number; pageSize?: number; }) => getTenantList: (params: { parentTenantId?: string; tenantName?: string; status?: number; current?: number; pageSize?: number; }) =>
request('/tenant/hierarchy/list', { request('/api-user/tenant/hierarchy/list', {
method: 'GET', method: 'GET',
params: { ...params, page: params.current, size: params.pageSize }, params: { ...params, page: params.current, size: params.pageSize },
}), }),
getTenantDetail: (tenantId: string) => request(`/tenant/hierarchy/detail/${tenantId}`, { method: 'GET' }), getTenantDetail: async (tenantId: string) => {
const res: any = await request(`/api-user/tenant/hierarchy/detail/${tenantId}`, { method: 'GET' });
if (typeof res?.resp_code !== 'undefined') return { success: res.resp_code === 0, msg: res.resp_msg, data: res.data } as any;
if (typeof res?.success !== 'undefined') return res;
return { success: true, data: res } as any;
},
// 规范化获取详情,供表单使用(可选导出)
getTenantDetailStd: async (tenantId: string) => {
const res: any = await request(`/api-user/tenant/hierarchy/detail/${tenantId}`, { method: 'GET' });
if (typeof res?.resp_code !== 'undefined') return { success: res.resp_code === 0, msg: res.resp_msg, data: res.data } as any;
if (typeof res?.success !== 'undefined') return res;
return { success: true, data: res } as any;
},
}; };
declare global { declare global {