修复页面bug
This commit is contained in:
+56
-4
@@ -127,12 +127,20 @@ public class TenantHierarchyController {
|
||||
// ===== 私有方法:对象转换 =====
|
||||
private Tenant toTenant(TenantInfo info) {
|
||||
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();
|
||||
t.setTenantId(info.getTenantId());
|
||||
t.setTenantId(tenantId);
|
||||
t.setTenantName(info.getTenantName());
|
||||
t.setParentTenantId(info.getParentTenantId());
|
||||
t.setTenantLevel(info.getTenantLevel());
|
||||
t.setTenantPath(info.getTenantPath());
|
||||
t.setParentTenantId(parentId);
|
||||
t.setTenantLevel(normalizedLevel);
|
||||
t.setTenantPath(normalizedPath);
|
||||
t.setTenantType(info.getTenantType());
|
||||
t.setTenantCode(info.getTenantCode());
|
||||
t.setContactPerson(info.getContactPerson());
|
||||
@@ -144,6 +152,50 @@ public class TenantHierarchyController {
|
||||
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) {
|
||||
if (t == null) return null;
|
||||
return TenantInfo.builder()
|
||||
|
||||
+18
-2
@@ -168,7 +168,16 @@ public class TenantSwitchController {
|
||||
String userTenantId = getDefaultTenantId(user);
|
||||
if (StringUtils.hasText(userTenantId)) {
|
||||
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 {
|
||||
return List.of(userTenantId);
|
||||
}
|
||||
@@ -178,6 +187,13 @@ public class TenantSwitchController {
|
||||
|
||||
private String getDefaultTenantId(LoginAppUser user) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -249,7 +249,8 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
||||
}
|
||||
}
|
||||
|
||||
// 更新租户
|
||||
// 使用主键ID执行更新,避免未传ID导致返回0
|
||||
tenant.setId(existingTenant.getId());
|
||||
int result = tenantHierarchyMapper.updateById(tenant);
|
||||
if (result > 0) {
|
||||
log.info("更新租户成功: tenantId={}", tenant.getTenantId());
|
||||
@@ -396,4 +397,4 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
||||
.creatorId(tenant.getCreatorId())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+6
-2
@@ -10,6 +10,7 @@ import com.central.common.model.SysRole;
|
||||
import com.central.common.model.SysUser;
|
||||
import com.central.common.service.UserTenantInitializer;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
@@ -31,6 +32,7 @@ import java.util.*;
|
||||
* Blog: http://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Slf4j
|
||||
public class LoginUserUtils {
|
||||
private final static String ATT_PERMISSIONS = "permissions";
|
||||
|
||||
@@ -131,11 +133,13 @@ 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()
|
||||
, sysUser.getUsername(), sysUser.getPassword()
|
||||
, sysUser.getMobile(), sysUser.getPermissions()
|
||||
, sysUser.getEnabled(), true, true, true
|
||||
, enabled, true, true, true
|
||||
, authorities);
|
||||
|
||||
// 设置用户基本属性到attributes中,供租户初始化使用
|
||||
|
||||
+8
-1
@@ -10,6 +10,9 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
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 java.io.IOException;
|
||||
@@ -30,7 +33,11 @@ public class LoginUserFilter extends OncePerRequestFilter {
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain filterChain) throws IOException, ServletException {
|
||||
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());
|
||||
LoginUserContextHolder.setUser(user);
|
||||
filterChain.doFilter(request, response);
|
||||
|
||||
@@ -248,3 +248,40 @@ zlt:
|
||||
3) 使用 APP 账号登录,重复上述步骤,观察查询仅限等值 `tenant_id = ...`。
|
||||
|
||||
如需进一步协助实现 `/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`。
|
||||
|
||||
@@ -13,6 +13,24 @@ export const request: any = {
|
||||
errorConfig: {
|
||||
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;
|
||||
},
|
||||
},
|
||||
@@ -39,6 +57,23 @@ export const request: any = {
|
||||
} as any;
|
||||
(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) {
|
||||
// 静默处理解析错误
|
||||
}
|
||||
@@ -53,8 +88,6 @@ export function onRouteChange({ location }: any) {
|
||||
const isLoginPath = String(location?.pathname || '').startsWith('/user/login');
|
||||
if (!token && !isLoginPath) {
|
||||
history.push('/user/login');
|
||||
} else if (token && isLoginPath) {
|
||||
history.push('/welcome');
|
||||
}
|
||||
} 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 { tenantApi, TenantTreeNode } from '@/services/tenant';
|
||||
|
||||
@@ -45,7 +45,7 @@ const TenantScopeFilter: React.FC<Props> = ({ onChanged }) => {
|
||||
message.success('租户范围已更新');
|
||||
onChanged?.(tenantId, includeChildren);
|
||||
} else {
|
||||
message.error(res.msg || '切换失败');
|
||||
message.error((res as any).msg || '切换失败');
|
||||
}
|
||||
} catch (e) {
|
||||
message.error('切换失败');
|
||||
@@ -64,14 +64,10 @@ const TenantScopeFilter: React.FC<Props> = ({ onChanged }) => {
|
||||
onChange={(val) => setTenantId(val)}
|
||||
treeData={toTreeData(tree)}
|
||||
/>
|
||||
<Checkbox checked={includeChildren} onChange={(e) => setIncludeChildren(e.target.checked)}>
|
||||
包含子租户
|
||||
</Checkbox>
|
||||
<Button type="primary" onClick={handleApply}>
|
||||
应用
|
||||
</Button>
|
||||
<Checkbox checked={includeChildren} onChange={(e) => setIncludeChildren(e.target.checked)}>包含子租户</Checkbox>
|
||||
<Button type="primary" onClick={handleApply}>应用</Button>
|
||||
</Space>
|
||||
);
|
||||
};
|
||||
|
||||
export default TenantScopeFilter;
|
||||
export default TenantScopeFilter;
|
||||
@@ -1,29 +1,34 @@
|
||||
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';
|
||||
|
||||
export interface TenantSelectorProps {
|
||||
// 字段名可自定义;默认与后端接口约定一致
|
||||
nameTenant?: string; // 默认 'tenantId'
|
||||
nameIncludeChildren?: string; // 默认 'includeChildren'
|
||||
nameTenant?: string;
|
||||
nameIncludeChildren?: string;
|
||||
labelTenant?: React.ReactNode;
|
||||
labelIncludeChildren?: React.ReactNode;
|
||||
// 是否隐藏“包含下级”复选框(用于仅需要选择租户的场景,如用户表单)
|
||||
hideIncludeChildren?: boolean;
|
||||
}
|
||||
|
||||
const toTreeData = (nodes: TenantTreeNode[] = []): any[] =>
|
||||
nodes.map((n) => ({
|
||||
title: n.tenantName,
|
||||
value: n.tenantId,
|
||||
key: n.tenantId,
|
||||
children: n.children ? toTreeData(n.children) : undefined,
|
||||
const toTreeData = (nodes?: TenantTreeNode[] | any): any[] => {
|
||||
const arr: TenantTreeNode[] = Array.isArray(nodes) ? nodes : [];
|
||||
return arr.map((n) => ({
|
||||
title: (n as any)?.tenantId, // 显示租户ID
|
||||
value: (n as any)?.tenantId,
|
||||
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> = ({
|
||||
nameTenant = 'tenantId',
|
||||
nameIncludeChildren = 'includeChildren',
|
||||
labelTenant = '租户',
|
||||
labelIncludeChildren = '包含子租户',
|
||||
labelIncludeChildren = '包含下级',
|
||||
hideIncludeChildren = false,
|
||||
}) => {
|
||||
const form = Form.useFormInstance?.();
|
||||
const [tree, setTree] = useState<TenantTreeNode[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
@@ -31,16 +36,57 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
|
||||
(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [treeRes] = await Promise.all([
|
||||
tenantApi.getAccessibleTenants(),
|
||||
]);
|
||||
if (treeRes?.success) setTree(treeRes.data || []);
|
||||
const treeRes: any = await tenantApi.getAccessibleTenants();
|
||||
let list: TenantTreeNode[] = [];
|
||||
if (typeof treeRes?.success !== 'undefined') {
|
||||
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 {
|
||||
setLoading(false);
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
// 不启用懒加载,依赖后端返回的完整树;仅在“仅单根无子”时补一层直系子级(见上方 useEffect)
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form.Item name={nameTenant} label={labelTenant}>
|
||||
@@ -49,14 +95,16 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
|
||||
treeDefaultExpandAll
|
||||
loading={loading}
|
||||
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
|
||||
placeholder="选择租户(含子租户)"
|
||||
placeholder='选择租户(默认当前租户)'
|
||||
treeData={toTreeData(tree)}
|
||||
allowClear
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name={nameIncludeChildren} label={labelIncludeChildren} valuePropName="checked" initialValue={true}>
|
||||
<Checkbox>包含子租户</Checkbox>
|
||||
</Form.Item>
|
||||
{hideIncludeChildren ? null : (
|
||||
<Form.Item name={nameIncludeChildren} label={labelIncludeChildren} valuePropName='checked' initialValue={true}>
|
||||
<Checkbox>包含下级租户</Checkbox>
|
||||
</Form.Item>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React from 'react';
|
||||
import React from 'react';
|
||||
import { Button, Tooltip } from 'antd';
|
||||
import { MoonOutlined, SunOutlined } from '@ant-design/icons';
|
||||
import type { ThemeMode } from '@/theme';
|
||||
@@ -8,20 +8,17 @@ export interface ThemeSwitchProps {
|
||||
onToggle: () => void;
|
||||
}
|
||||
|
||||
const ThemeSwitch: React.FC<ThemeSwitchProps> = ({ mode, onToggle }) => {
|
||||
return (
|
||||
<Tooltip title={mode === 'dark' ? '切换为亮色' : '切换为暗色'}>
|
||||
<Button
|
||||
type="text"
|
||||
onClick={onToggle}
|
||||
icon={mode === 'dark' ? <SunOutlined /> : <MoonOutlined />}
|
||||
style={{ color: 'var(--text-primary)' }}
|
||||
>
|
||||
{mode === 'dark' ? '亮色' : '暗色'}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
|
||||
export default ThemeSwitch;
|
||||
const ThemeSwitch: React.FC<ThemeSwitchProps> = ({ mode, onToggle }) => (
|
||||
<Tooltip title={mode === 'dark' ? '切换为亮色' : '切换为暗色'}>
|
||||
<Button
|
||||
type="text"
|
||||
onClick={onToggle}
|
||||
icon={mode === 'dark' ? <SunOutlined /> : <MoonOutlined />}
|
||||
style={{ color: 'var(--text-primary)' }}
|
||||
>
|
||||
{mode === 'dark' ? '亮色' : '暗色'}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
export default ThemeSwitch;
|
||||
@@ -8,14 +8,11 @@ import {
|
||||
AppstoreOutlined,
|
||||
FileTextOutlined,
|
||||
TeamOutlined,
|
||||
ToolOutlined,
|
||||
BarChartOutlined,
|
||||
CloudServerOutlined,
|
||||
BugOutlined,
|
||||
SearchOutlined,
|
||||
MessageOutlined,
|
||||
FolderOutlined,
|
||||
SafetyOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { Link, useLocation, history } from 'umi';
|
||||
import ProLayout, { MenuDataItem } from '@ant-design/pro-layout';
|
||||
@@ -23,7 +20,6 @@ import { fetchMenuData, outLogin } from '@/services/login';
|
||||
import { useTheme } from '@/theme';
|
||||
import { ThemeSwitch } from '@/components/ui';
|
||||
|
||||
// 后端菜单节点(兼容 children 与 subMenus)
|
||||
type MenuNode = {
|
||||
id?: number | string;
|
||||
name?: string;
|
||||
@@ -56,16 +52,21 @@ const BasicLayout: React.FC = (props: any) => {
|
||||
return () => { mounted = false; };
|
||||
}, []);
|
||||
|
||||
// 将后端菜单转换为 ProLayout 菜单(对齐 react-web 映射规则)
|
||||
const menuDataRender = useMemo(() => {
|
||||
const mapPath = (m: MenuNode): string | undefined => {
|
||||
const mapPath = (m: MenuNode, childrenLen: number): string | undefined => {
|
||||
const cand = (m.path || m.url || '').trim();
|
||||
if (!cand) return undefined;
|
||||
const lower = cand.toLowerCase();
|
||||
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';
|
||||
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) => {
|
||||
@@ -90,12 +91,12 @@ const BasicLayout: React.FC = (props: any) => {
|
||||
`${parentKey}-${menu.name}-${index}`;
|
||||
const keyStr = String(stableKey);
|
||||
|
||||
const path = mapPath(menu);
|
||||
const childrenList: MenuNode[] = (menu.children && menu.children.length ? menu.children : (menu.subMenus || [])) || [];
|
||||
const path = mapPath(menu, childrenList.length);
|
||||
|
||||
const item: MenuDataItem = {
|
||||
key: keyStr,
|
||||
name: menu.name || `菜单项${index + 1}`,
|
||||
name: menu.name || `菜单${index + 1}`,
|
||||
path,
|
||||
icon: getIcon(path),
|
||||
children: childrenList.map((child: MenuNode, i: number) => normalize(child, i, keyStr)),
|
||||
@@ -103,13 +104,11 @@ const BasicLayout: React.FC = (props: any) => {
|
||||
return item;
|
||||
};
|
||||
|
||||
// 首次未加载完毕前不渲染默认菜单,避免覆盖接口菜单
|
||||
if (!loaded) return [];
|
||||
const list = menus && menus.length ? menus : [{ name: '欢迎页', url: '/welcome', id: 'welcome-default' }];
|
||||
return list.map((m, i) => normalize(m, i));
|
||||
}, [menus, mode, loaded]);
|
||||
|
||||
// 右上角操作区
|
||||
const rightContentRender = () => (
|
||||
<Space size="middle">
|
||||
<ThemeSwitch mode={mode} onToggle={toggle} />
|
||||
@@ -196,7 +195,6 @@ const BasicLayout: React.FC = (props: any) => {
|
||||
)}
|
||||
token={{
|
||||
sider: {
|
||||
// 左侧侧边栏背景使用更柔和的浅色,避免纯白突兀
|
||||
colorMenuBackground: 'var(--sider-bg)',
|
||||
colorBgMenuItemSelected: 'var(--primary-color)',
|
||||
colorTextMenuSelected: '#ffffff',
|
||||
@@ -204,7 +202,6 @@ const BasicLayout: React.FC = (props: any) => {
|
||||
colorBgMenuItemHover: 'var(--bg-glass)',
|
||||
},
|
||||
header: {
|
||||
// 顶部导航背景采用柔和渐变
|
||||
colorBgHeader: 'var(--header-bg)',
|
||||
colorHeaderTitle: 'var(--text-primary)',
|
||||
colorTextRightActionsItem: 'var(--text-secondary)',
|
||||
|
||||
@@ -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 {
|
||||
RocketOutlined,
|
||||
TeamOutlined,
|
||||
AppstoreOutlined,
|
||||
CloudServerOutlined,
|
||||
TrophyOutlined,
|
||||
ThunderboltOutlined,
|
||||
GlobalOutlined,
|
||||
SafetyOutlined
|
||||
} from '@ant-design/icons';
|
||||
import { RocketOutlined, TeamOutlined, AppstoreOutlined, CloudServerOutlined, TrophyOutlined, ThunderboltOutlined, GlobalOutlined, SafetyOutlined } from '@ant-design/icons';
|
||||
import TenantScopeFilter from '@/components/TenantScopeFilter';
|
||||
|
||||
const { Title, Paragraph } = Typography;
|
||||
@@ -18,24 +9,15 @@ const Welcome: React.FC = () => {
|
||||
const [time, setTime] = useState(new Date());
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
const timer = setInterval(() => {
|
||||
if (isMounted) {
|
||||
setTime(new Date());
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
clearInterval(timer);
|
||||
};
|
||||
const timer = setInterval(() => setTime(new Date()), 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
const stats = [
|
||||
{ title: '今日订单', value: 1234, icon: <AppstoreOutlined />, color: '#667eea' },
|
||||
{ title: '活跃用户', value: 856, icon: <TeamOutlined />, color: '#764ba2' },
|
||||
{ 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 = [
|
||||
@@ -47,29 +29,15 @@ const Welcome: React.FC = () => {
|
||||
|
||||
return (
|
||||
<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">
|
||||
<Col>
|
||||
<Space direction="vertical" size={8}>
|
||||
<Title level={2} style={{ color: 'white', margin: 0 }}>
|
||||
<RocketOutlined style={{ marginRight: 12 }} />
|
||||
欢迎使用 Go-Fly Admin
|
||||
<RocketOutlined style={{ marginRight: 12 }} /> 欢迎使用 Go-Fly Admin
|
||||
</Title>
|
||||
<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 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>
|
||||
</Space>
|
||||
</Col>
|
||||
<Col>
|
||||
@@ -78,45 +46,20 @@ const Welcome: React.FC = () => {
|
||||
</Row>
|
||||
</Card>
|
||||
|
||||
{/* 数据统计卡片 */}
|
||||
<Row gutter={[24, 24]} style={{ marginBottom: 24 }}>
|
||||
{stats.map((stat, index) => (
|
||||
<Col xs={12} sm={12} md={6} key={index}>
|
||||
<Card
|
||||
className="modern-card"
|
||||
style={{
|
||||
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 className="modern-card" style={{ 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>
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
|
||||
<Row gutter={[24, 24]}>
|
||||
{/* 系统状态 */}
|
||||
<Col xs={24} md={12}>
|
||||
<Card className="modern-card" title={
|
||||
<span style={{ color: 'var(--text-primary)' }}>
|
||||
<ThunderboltOutlined style={{ marginRight: 8, color: '#667eea' }} />
|
||||
系统状态
|
||||
</span>
|
||||
}>
|
||||
<Card className="modern-card" title={<span style={{ color: 'var(--text-primary)' }}><ThunderboltOutlined style={{ marginRight: 8, color: '#667eea' }} />系统状态</span>}>
|
||||
<Space direction="vertical" style={{ width: '100%' }} size={16}>
|
||||
<div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
|
||||
@@ -143,14 +86,8 @@ const Welcome: React.FC = () => {
|
||||
</Card>
|
||||
</Col>
|
||||
|
||||
{/* 快捷操作 */}
|
||||
<Col xs={24} md={12}>
|
||||
<Card className="modern-card" title={
|
||||
<span style={{ color: 'var(--text-primary)' }}>
|
||||
<TrophyOutlined style={{ marginRight: 8, color: '#667eea' }} />
|
||||
快捷操作
|
||||
</span>
|
||||
}>
|
||||
<Card className="modern-card" title={<span style={{ color: 'var(--text-primary)' }}><TrophyOutlined style={{ marginRight: 8, color: '#667eea' }} />快捷操作</span>}>
|
||||
<Row gutter={[16, 16]}>
|
||||
{quickActions.map((action, index) => (
|
||||
<Col span={12} key={index}>
|
||||
@@ -158,16 +95,7 @@ const Welcome: React.FC = () => {
|
||||
block
|
||||
size="large"
|
||||
className="tech-button"
|
||||
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'
|
||||
}}
|
||||
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' }}
|
||||
>
|
||||
<div style={{ fontSize: 20, marginBottom: 4 }}>{action.icon}</div>
|
||||
<div style={{ fontSize: 12 }}>{action.title}</div>
|
||||
@@ -179,45 +107,13 @@ const Welcome: React.FC = () => {
|
||||
</Col>
|
||||
</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]}>
|
||||
<Col xs={24} sm={12} md={8}>
|
||||
<div style={{ textAlign: 'center', padding: 16 }}>
|
||||
<div style={{ fontSize: 32, color: '#667eea', marginBottom: 12 }}>
|
||||
<RocketOutlined />
|
||||
</div>
|
||||
<div style={{ fontSize: 32, color: '#667eea', marginBottom: 12 }}><RocketOutlined /></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: '#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>
|
||||
<Paragraph style={{ color: 'var(--text-secondary)' }}>基于微服务架构,支持高并发访问,确保系统稳定运行</Paragraph>
|
||||
</div>
|
||||
</Col>
|
||||
</Row>
|
||||
@@ -226,5 +122,4 @@ const Welcome: React.FC = () => {
|
||||
);
|
||||
};
|
||||
|
||||
export default Welcome;
|
||||
|
||||
export default Welcome;
|
||||
@@ -1,165 +1,237 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { ActionType, ProColumns } from '@ant-design/pro-components';
|
||||
import { ModalForm, PageContainer, ProForm, ProFormText, ProFormTextArea, ProTable } from '@ant-design/pro-components';
|
||||
import { Button, Card, Col, Form, message, Popconfirm, Row, Space, Switch, Tree, TreeSelect } from 'antd';
|
||||
import { PlusOutlined } from '@ant-design/icons';
|
||||
import { tenantApi, TenantInfo, TenantTreeNode } from '@/services/tenant';
|
||||
import { ActionBar, SearchBarPlus } from '@/components/ui';
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import { PageContainer } from "@ant-design/pro-components";
|
||||
import { Space, message, Button } from "antd";
|
||||
import { ActionBar, GradientButton, GlassCard } from "@/components/ui";
|
||||
import { PlusOutlined } from "@ant-design/icons";
|
||||
import TenantForm from "./components/TenantForm";
|
||||
import TenantTreeTable from "./components/TenantTreeTable";
|
||||
import { tenantApi, TenantInfo, TenantTreeNode } from "@/services/tenant";
|
||||
|
||||
const toTreeData = (nodes: TenantTreeNode[] = []): any[] =>
|
||||
nodes.map((n) => ({ title: n.tenantName, value: n.tenantId, key: n.tenantId, children: n.children ? toTreeData(n.children) : undefined }));
|
||||
// UI 表单初始值:status 允许 boolean | number,便于与 Switch 绑定
|
||||
type UITenantFormValues = Partial<TenantInfo> & { status?: boolean | number };
|
||||
|
||||
const TenantManage: React.FC = () => {
|
||||
const actionRef = useRef<ActionType>();
|
||||
const [form] = Form.useForm<TenantInfo>();
|
||||
const [orgTree, setOrgTree] = useState<TenantTreeNode[]>([]);
|
||||
const [loadingTree, setLoadingTree] = useState(false);
|
||||
const [currentNode, setCurrentNode] = useState<string | undefined>(undefined);
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [data, setData] = useState<TenantTreeNode[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [formOpen, setFormOpen] = 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 loadTree = async () => {
|
||||
setLoadingTree(true);
|
||||
const fetchTree = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await tenantApi.getAccessibleTenants();
|
||||
if (res.success) setOrgTree(res.data || []);
|
||||
} finally {
|
||||
setLoadingTree(false);
|
||||
const res: any = await tenantApi.getAccessibleTenants();
|
||||
let list: TenantTreeNode[] = [];
|
||||
if (typeof res?.success !== "undefined") {
|
||||
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 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('保存中...');
|
||||
const handleDelete = async (record: TenantTreeNode) => {
|
||||
const hide = message.loading("删除中...");
|
||||
try {
|
||||
const payload = { ...vals, status: vals.status ?? 1 };
|
||||
const res = editing ? await tenantApi.updateTenant(payload) : await tenantApi.createTenant(payload);
|
||||
if (res.success) {
|
||||
message.success(editing ? '修改成功' : '新增成功');
|
||||
setVisible(false);
|
||||
actionRef.current?.reload();
|
||||
loadTree();
|
||||
return true;
|
||||
const r: any = await tenantApi.deleteTenant(record.tenantId);
|
||||
if (r?.success) {
|
||||
message.success("删除成功");
|
||||
fetchTree();
|
||||
} else {
|
||||
message.error(r?.msg || "删除失败");
|
||||
}
|
||||
message.error(res.msg || '保存失败');
|
||||
return false;
|
||||
} finally { hide(); }
|
||||
};
|
||||
|
||||
return (
|
||||
<PageContainer header={{ title: '租户管理' }}>
|
||||
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => { actionRef.current?.reload(); loadTree(); }} />
|
||||
<PageContainer header={{ title: "租户管理" }}>
|
||||
<ActionBar
|
||||
right={(
|
||||
left={(
|
||||
<Space>
|
||||
<Button size="middle" type="primary" icon={<PlusOutlined />} onClick={() => {
|
||||
setEditing(false);
|
||||
form.resetFields();
|
||||
form.setFieldsValue({ parentTenantId: currentNode, status: 1 });
|
||||
setVisible(true);
|
||||
}}>新增租户</Button>
|
||||
<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={openCreateRoot}>新增</GradientButton>
|
||||
<Button onClick={fetchTree}>刷新</Button>
|
||||
</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>
|
||||
title={editing ? '编辑租户' : '新建租户'}
|
||||
open={visible}
|
||||
onOpenChange={setVisible}
|
||||
form={form}
|
||||
width={640}
|
||||
onFinish={onSave}
|
||||
modalProps={{ destroyOnClose: true }}
|
||||
>
|
||||
<ProForm.Group>
|
||||
<ProFormText name="tenantId" label="租户ID" rules={[{ required: true }]} disabled={editing} />
|
||||
<ProFormText name="tenantName" label="租户名称" rules={[{ required: true }]} />
|
||||
</ProForm.Group>
|
||||
<ProForm.Group>
|
||||
<ProForm.Item name="parentTenantId" label="上级租户">
|
||||
<TreeSelect style={{ width: 260 }} allowClear dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} treeDefaultExpandAll treeData={treeSelectData} />
|
||||
</ProForm.Item>
|
||||
<ProFormText name="tenantType" label="类型" rules={[{ required: true }]} />
|
||||
</ProForm.Group>
|
||||
<ProFormText name="tenantCode" label="租户编码" />
|
||||
<ProFormText name="contactPerson" label="联系人" />
|
||||
<ProFormText name="contactPhone" label="联系电话" />
|
||||
<ProFormText name="address" label="地址" />
|
||||
<ProFormTextArea name="description" label="描述" />
|
||||
<ProForm.Item name="status" label="状态" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></ProForm.Item>
|
||||
</ModalForm>
|
||||
<GlassCard>
|
||||
<TenantTreeTable
|
||||
data={data}
|
||||
loading={loading}
|
||||
onAddChild={handleAddChild}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
</GlassCard>
|
||||
|
||||
<TenantForm
|
||||
title={editing ? "编辑租户" : "新建租户"}
|
||||
visible={formOpen}
|
||||
onVisibleChange={setFormOpen}
|
||||
onFinish={async (values) => {
|
||||
const hide = message.loading("保存中...");
|
||||
try {
|
||||
const payload: any = { ...initialValues, ...values };
|
||||
payload.status = typeof payload.status === 'boolean' ? (payload.status ? 1 : 0) : (payload.status ?? 1);
|
||||
// 计算 tenantPath / tenantLevel(后端未计算或为null时做兜底)
|
||||
if (!editing) {
|
||||
if (payload.parentTenantId) {
|
||||
try {
|
||||
const parent: any = await tenantApi.getTenantDetail(payload.parentTenantId);
|
||||
const p = parent?.data || {};
|
||||
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>
|
||||
);
|
||||
};
|
||||
|
||||
export default TenantManage;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React from 'react';
|
||||
import React from 'react';
|
||||
import { Button, Upload } from 'antd';
|
||||
import { ExportOutlined, ImportOutlined, PlusOutlined } from '@ant-design/icons';
|
||||
import { GradientButton } from '@/components/ui';
|
||||
@@ -8,13 +8,17 @@ export interface ToolbarProps {
|
||||
onCreate: () => void;
|
||||
// 导出
|
||||
onExport: () => void;
|
||||
// 是否隐藏“新增”按钮(例如:APP 用户)
|
||||
hideCreate?: boolean;
|
||||
}
|
||||
|
||||
// 统一:新增按钮固定在左侧;去掉刷新按钮(以查询为主)
|
||||
const Toolbar: React.FC<ToolbarProps> = ({ onCreate, onExport }) => {
|
||||
const Toolbar: React.FC<ToolbarProps> = ({ onCreate, onExport, hideCreate }) => {
|
||||
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>
|
||||
<Upload key="import" action="/api-user/users/import" showUploadList={false} accept=".xls,.xlsx">
|
||||
<Button size="middle" icon={<ImportOutlined />}>导入</Button>
|
||||
@@ -23,5 +27,4 @@ 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 { systemApi, UserItem } from '@/services/system';
|
||||
import TenantSelector from '@/components/ui/TenantSelector';
|
||||
|
||||
export interface UserFormProps {
|
||||
open: boolean;
|
||||
visible: boolean;
|
||||
title: string;
|
||||
initialValues?: Partial<UserItem>;
|
||||
onOpenChange: (v: boolean) => void;
|
||||
onFinish: (values: UserItem) => Promise<boolean>;
|
||||
initialValues?: Partial<UserItem & { company?: string; type?: string }>;
|
||||
onVisibleChange: (v: boolean) => void;
|
||||
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 (
|
||||
<ModalForm<UserItem>
|
||||
<ModalForm<UserItem & { company?: string; type?: string }>
|
||||
title={title}
|
||||
visible={open}
|
||||
onVisibleChange={onOpenChange}
|
||||
visible={visible}
|
||||
onVisibleChange={onVisibleChange}
|
||||
onFinish={onFinish}
|
||||
initialValues={initialValues}
|
||||
initialValues={{ type: 'BACKEND', ...(initialValues || {}) }}
|
||||
modalProps={{ destroyOnClose: true }}
|
||||
>
|
||||
<ProForm.Group>
|
||||
@@ -27,9 +30,17 @@ const UserForm: React.FC<UserFormProps> = ({ open, title, initialValues, onOpenC
|
||||
</ProForm.Group>
|
||||
<ProFormRadio.Group name="sex" label="性别" options={[{ label: '男', value: 0 }, { label: '女', value: 1 }]} />
|
||||
<ProFormSelect name="roleIds" label="角色" mode="multiple" request={systemApi.roles} placeholder="选择角色" />
|
||||
|
||||
{showCompany ? (
|
||||
<TenantSelector nameTenant="company" labelTenant="所属租户" hideIncludeChildren />
|
||||
) : null}
|
||||
|
||||
<ProFormTextArea name="remark" label="备注" />
|
||||
{/* 类型固定为系统用户,默认也会按 BACKEND 新建 */}
|
||||
<ProFormText name="type" label="用户类型" initialValue="BACKEND" disabled hidden />
|
||||
</ModalForm>
|
||||
);
|
||||
};
|
||||
|
||||
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 { ProTable } from '@ant-design/pro-components';
|
||||
import { Space, Switch, Popconfirm } from 'antd';
|
||||
@@ -73,4 +73,4 @@ const UserTable = forwardRef<UserTableRef, UserTableProps>(({ onEdit, onResetPas
|
||||
);
|
||||
});
|
||||
|
||||
export default UserTable;
|
||||
export default UserTable;
|
||||
@@ -1,5 +1,5 @@
|
||||
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 { ActionBar, GlassCard, SearchBarPlus } from '@/components/ui';
|
||||
import { systemApi, UserItem } from '@/services/system';
|
||||
@@ -9,15 +9,15 @@ import UserForm from './components/UserForm';
|
||||
|
||||
const UsersPage: React.FC = () => {
|
||||
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 [editVisible, setEditVisible] = useState(false);
|
||||
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('正在添加');
|
||||
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();
|
||||
message.success('添加用户成功');
|
||||
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('正在更新');
|
||||
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();
|
||||
message.success('修改用户成功');
|
||||
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 hide = message.loading('正在更新');
|
||||
try {
|
||||
@@ -82,16 +69,11 @@ const UsersPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const isAppType = params?.type === 'APP';
|
||||
|
||||
return (
|
||||
<PageContainer header={{ title: '用户管理' }}>
|
||||
<ActionBar
|
||||
left={
|
||||
<Toolbar
|
||||
onCreate={() => setCreateVisible(true)}
|
||||
onExport={() => systemApi.exportUser()}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<ActionBar left={<Toolbar onCreate={() => setCreateVisible(true)} onExport={() => systemApi.exportUser()} hideCreate={isAppType} />} />
|
||||
|
||||
<SearchBarPlus
|
||||
defaultCollapsed={false}
|
||||
@@ -103,6 +85,7 @@ const UsersPage: React.FC = () => {
|
||||
tableRef.current?.reload();
|
||||
}}
|
||||
>
|
||||
<ProFormSelect name="type" label="用户类型" valueEnum={{ BACKEND: '系统用户', APP: 'C端用户' }} initialValue="BACKEND" />
|
||||
<ProFormText name="username" label="用户名" placeholder="请输入用户名" />
|
||||
<ProFormText name="mobile" label="手机号" placeholder="请输入手机号" />
|
||||
</SearchBarPlus>
|
||||
@@ -117,24 +100,14 @@ const UsersPage: React.FC = () => {
|
||||
/>
|
||||
</GlassCard>
|
||||
|
||||
{/* 新建 */}
|
||||
<UserForm
|
||||
title="新建用户"
|
||||
open={createVisible}
|
||||
onOpenChange={setCreateVisible}
|
||||
onFinish={addUser}
|
||||
/>
|
||||
{/* 新建(仅系统用户) */}
|
||||
<UserForm title="新建用户" visible={createVisible} onVisibleChange={setCreateVisible} onFinish={addUser} showCompany={!isAppType ? true : false} />
|
||||
|
||||
{/* 编辑 */}
|
||||
<UserForm
|
||||
title="修改用户"
|
||||
open={editVisible}
|
||||
onOpenChange={setEditVisible}
|
||||
onFinish={editUser}
|
||||
initialValues={currentRow}
|
||||
/>
|
||||
<UserForm title="修改用户" visible={editVisible} onVisibleChange={setEditVisible} onFinish={editUser} initialValues={currentRow} showCompany={!isAppType ? true : false} />
|
||||
</PageContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default UsersPage;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { request } from 'umi';
|
||||
import { request } from 'umi';
|
||||
import { download } from '@/utils/download';
|
||||
|
||||
export interface UserItem {
|
||||
@@ -11,6 +11,9 @@ export interface UserItem {
|
||||
createTime?: string;
|
||||
roleId?: string; // 角色ID(逗号分隔)
|
||||
roles?: Array<{ id: number; name: string; code: string }>;
|
||||
// 扩展字段:前端使用(后端已支持)
|
||||
type?: 'BACKEND' | 'APP';
|
||||
company?: string; // 所属租户ID
|
||||
}
|
||||
|
||||
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 });
|
||||
return (res as any).data || res;
|
||||
},
|
||||
@@ -90,5 +93,4 @@ export const systemApi = {
|
||||
const list = (res as any).data || [];
|
||||
return list.map((r: any) => ({ label: r.name, value: r.id }));
|
||||
},
|
||||
};
|
||||
|
||||
};
|
||||
@@ -38,19 +38,54 @@ export interface TenantInfo {
|
||||
}
|
||||
|
||||
export const tenantApi = {
|
||||
getAccessibleTenants: () => request('/tenant/accessible', { method: 'GET' }),
|
||||
switchTenant: (tenantId: string) => request('/tenant/switch', { method: 'POST', params: { tenantId } }),
|
||||
getCurrentTenant: () => request('/tenant/current', { method: 'GET' }),
|
||||
resetToDefaultTenant: () => request('/tenant/reset', { method: 'POST' }),
|
||||
createTenant: (data: Partial<TenantInfo>) => request('/tenant/hierarchy/create', { method: 'POST', data }),
|
||||
updateTenant: (data: Partial<TenantInfo>) => request('/tenant/hierarchy/update', { method: 'PUT', data }),
|
||||
deleteTenant: (tenantId: string) => request(`/tenant/hierarchy/delete`, { method: 'DELETE', params: { tenantId } }),
|
||||
// 可访问租户树(保持后端原始返回,避免破坏既有前端逻辑)
|
||||
getAccessibleTenants: () => request('/api-user/tenant/accessible', { method: 'GET' }),
|
||||
// 切换当前查询租户(新)
|
||||
switchTenant: (tenantId: string) => request('/api-user/tenant/switch-query', { method: 'POST', params: { tenantId } }),
|
||||
// 当前租户详情(新)
|
||||
getCurrentTenant: () => request('/api-user/tenant/current/info', { method: 'GET' }),
|
||||
// 当前查询范围统计(新)
|
||||
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; }) =>
|
||||
request('/tenant/hierarchy/list', {
|
||||
request('/api-user/tenant/hierarchy/list', {
|
||||
method: 'GET',
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user