首页统计

This commit is contained in:
2025-10-01 03:51:53 +08:00
parent dbd4d4d198
commit 66d09ef19c
32 changed files with 1293 additions and 499 deletions
@@ -1,51 +1,79 @@
import React, { useEffect, useState } from 'react';
import { Space, Button, TreeSelect, Checkbox, message } from 'antd';
import { tenantApi, TenantTreeNode } from '@/services/tenant';
import { tenantApi } from '@/services/tenant';
interface Props {
// 租户或“包含下级”变化后的回调(外部将 tenantId/includeChildren 透传到请求参数)
onChanged?: (tenantId: string, includeChildren: boolean) => void;
// 可选:是否调用后端切换查询上下文(默认 false,不建议启用)
useSwitchTenant?: boolean;
interface TenantNode {
tenantId?: string;
tenantName?: string;
children?: TenantNode[];
status?: number | boolean;
}
const TenantScopeFilter: React.FC<Props> = ({ onChanged, useSwitchTenant = false }) => {
const [tree, setTree] = useState<TenantTreeNode[]>([]);
interface Props {
// 租户或“包含子租户”变化后回调(外部将 tenantId/includeChildren 透传至请求参数)
onChanged?: (tenantId: string, includeChildren: boolean) => void;
// 可选:是否调用后端切换查询上下文(默认 false)
useSwitchTenant?: boolean;
// 自动应用(变更即触发回调,隐藏“应用”按钮)
autoApply?: boolean;
}
const TenantScopeFilter: React.FC<Props> = ({ onChanged, useSwitchTenant = false, autoApply = false }) => {
const [tree, setTree] = useState<TenantNode[]>([]);
const [tenantId, setTenantId] = useState<string | undefined>();
const [includeChildren, setIncludeChildren] = useState(true);
const [loading, setLoading] = useState(false);
const [includeChildren, setIncludeChildren] = useState<boolean>(true);
const [loading, setLoading] = useState<boolean>(false);
useEffect(() => {
(async () => {
setLoading(true);
try {
const [treeRes, currentRes] = await Promise.all([
tenantApi.getAccessibleTenants(),
tenantApi.getCurrentTenant(),
]);
if ((treeRes as any)?.success) setTree((treeRes as any).data || []);
if ((currentRes as any)?.success) setTenantId((currentRes as any).data?.tenantId);
// 获取可访问租户树
const treeRes: any = await tenantApi.getAccessibleTenants();
let list: TenantNode[] = [];
if (Array.isArray(treeRes)) list = treeRes as any;
else if (Array.isArray(treeRes?.data)) list = treeRes.data as any;
else if (treeRes?.resp_code === 0 && Array.isArray(treeRes?.data)) list = treeRes.data as any;
setTree(list || []);
// 获取当前租户
const curRes: any = await tenantApi.getCurrentTenant();
const curId = curRes?.data?.tenantId || (curRes?.resp_code === 0 ? curRes?.data?.tenantId : undefined);
if (curId) setTenantId(curId);
} catch {
// 忽略错误,展示空树
} finally {
setLoading(false);
}
})();
}, []);
const toTreeData = (nodes: TenantTreeNode[]): any[] =>
nodes?.map((n) => ({
title: n.tenantName,
// 自动应用:参数变化即触发回调
useEffect(() => {
if (!autoApply) return;
if (!tenantId) return;
onChanged?.(tenantId, includeChildren);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tenantId, includeChildren, autoApply]);
const toTreeData = (nodes?: TenantNode[]): any[] =>
(nodes || []).map((n) => ({
title: n.tenantName && n.tenantId ? `${n.tenantName} (${n.tenantId})` : (n.tenantName || n.tenantId || '-'),
value: n.tenantId,
key: n.tenantId,
children: n.children ? toTreeData(n.children) : undefined,
})) || [];
}));
const handleApply = async () => {
if (!tenantId) return;
try {
if (useSwitchTenant) {
const res = await tenantApi.switchTenant(tenantId);
if ((res as any)?.success) message.success('租户范围已更新');
else { message.error((res as any)?.msg || '切换失败'); return; }
const res: any = await tenantApi.switchTenant(tenantId);
if (!(res?.success ?? res?.resp_code === 0)) {
message.error(res?.msg || '切换失败');
return;
}
message.success('租户范围已更新');
}
onChanged?.(tenantId, includeChildren);
} catch {
@@ -57,8 +85,9 @@ const TenantScopeFilter: React.FC<Props> = ({ onChanged, useSwitchTenant = false
<Space>
<TreeSelect
style={{ minWidth: 260 }}
treeDefaultExpandAll
showSearch
loading={loading}
treeNodeFilterProp="title"
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder="选择租户(含子租户)"
value={tenantId}
@@ -66,7 +95,9 @@ const TenantScopeFilter: React.FC<Props> = ({ onChanged, useSwitchTenant = false
treeData={toTreeData(tree)}
/>
<Checkbox checked={includeChildren} onChange={(e) => setIncludeChildren(e.target.checked)}>包含子租户</Checkbox>
<Button type="primary" onClick={handleApply}>应用</Button>
{!autoApply && (
<Button type="primary" onClick={handleApply}>应用</Button>
)}
</Space>
);
};
@@ -1,6 +1,7 @@
import React, { useEffect, useState } from 'react';
import { Form, TreeSelect, Checkbox, message } from 'antd';
import { tenantApi, TenantTreeNode } from '@/services/tenant';
import { getTenantTreeCache, setTenantTreeCache, getTenantChildrenCache, setTenantChildrenCache, getTenantDetailCache, setTenantDetailCache } from '@/utils/tenantCache';
export interface TenantSelectorProps {
nameTenant?: string;
@@ -15,12 +16,17 @@ export interface TenantSelectorProps {
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,
}));
return arr.map((n) => {
const id = (n as any)?.tenantId as string | undefined;
const name = (n as any)?.tenantName as string | undefined;
const title = name && id ? `${name} (${id})` : (name || id || '-');
return {
title,
value: id,
key: id,
children: Array.isArray((n as any)?.children) && (n as any).children!.length ? toTreeData((n as any).children) : undefined,
};
});
};
const TenantSelector: React.FC<TenantSelectorProps> = ({
@@ -39,12 +45,16 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
(async () => {
setLoading(true);
try {
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[];
// 优先从缓存读取可访问租户树
let list: TenantTreeNode[] = (getTenantTreeCache() as any) || [];
if (!list || list.length === 0) {
const treeRes: any = await tenantApi.getAccessibleTenants();
if (typeof treeRes?.success !== 'undefined') {
list = treeRes.success ? (treeRes.data || []) : [];
} else if (Array.isArray(treeRes)) {
list = treeRes as TenantTreeNode[];
}
if (list && list.length) setTenantTreeCache(list as any);
}
if (!list || list.length === 0) {
// 回退:仅当前租户
@@ -62,24 +72,92 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
if (list && list.length && !form?.getFieldValue?.(nameTenant)) {
try { form?.setFieldsValue?.({ [nameTenant]: list[0].tenantId, [nameIncludeChildren]: true }); } catch {}
}
// 补齐每个根节点的一层子租户,保证能看到子级
// 递进补齐:根 -> 二级 -> 三级,确保三级部门可见
const loadChildrenFor = async (nodes?: any[]): Promise<any[]> => {
const resultChildren: any[] = [];
if (!Array.isArray(nodes)) return resultChildren;
await Promise.all((nodes || []).map(async (node: any) => {
if (!node) return;
const pid = node.tenantId;
if (!pid) return;
// 若已有子节点,直接使用;否则尝试缓存;再不行才请求接口
if (Array.isArray(node.children) && node.children.length) {
// 已有
} else {
const cached = getTenantChildrenCache(pid);
if (cached) {
node.children = cached as any;
} else {
try {
const res: any = await tenantApi.getTenantList({ parentTenantId: pid, status: 1 as any, 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, status: c.status }));
} else {
node.children = undefined;
}
setTenantChildrenCache(pid, node.children as any);
} catch {}
}
}
if (Array.isArray(node.children)) resultChildren.push(...node.children);
}));
return resultChildren;
};
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 {}
})
);
const level2 = await loadChildrenFor(list);
await loadChildrenFor(level2);
} catch {}
// 补齐根节点状态,随后过滤仅显示启用(status=1)
try {
await Promise.all((list || []).map(async (node: any) => {
if (node?.status == null && node?.tenantId) {
// 先看缓存,无则请求
const cached = getTenantDetailCache(node.tenantId);
if (typeof (cached as any)?.status !== 'undefined') {
node.status = (cached as any).status as any;
} else {
try {
const d: any = await tenantApi.getTenantDetail(node.tenantId);
node.status = (d?.data?.status ?? node.status);
setTenantDetailCache(node.tenantId, { status: node.status } as any);
} catch {}
}
}
}));
} catch {}
const filterEnabled = (nodes?: any[]): any[] => {
if (!Array.isArray(nodes)) return [];
const out: any[] = [];
for (const n of nodes) {
const v = (typeof (n as any)?.status === 'boolean') ? ((n as any).status ? 1 : 0) : (n as any)?.status;
if (v === 1) {
const item: any = { ...n };
if (Array.isArray((n as any).children)) item.children = filterEnabled((n as any).children);
out.push(item);
}
}
return out;
};
const filtered = filterEnabled(list || []);
setTree(filtered);
// 若当前选择的租户已被过滤(禁用),回退到第一个可用租户
try {
const selected = form?.getFieldValue?.(nameTenant);
const collectIds = (nodes?: any[]): string[] => {
const out: string[] = [];
if (!Array.isArray(nodes)) return out;
for (const n of nodes) {
if ((n as any)?.tenantId) out.push((n as any).tenantId);
if (Array.isArray((n as any).children)) out.push(...collectIds((n as any).children));
}
return out;
};
const ids = collectIds(filtered);
if (!selected || (ids.length && !ids.includes(selected))) {
form?.setFieldsValue?.({ [nameTenant]: ids[0], [nameIncludeChildren]: true });
}
} catch {}
setTree(list || []);
} catch (e) {
message.warn('获取租户列表失败');
} finally {
@@ -95,7 +173,8 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
<Form.Item name={nameTenant} label={labelTenant} rules={rulesTenant as any}>
<TreeSelect
style={{ minWidth: 260 }}
treeDefaultExpandAll
showSearch
treeNodeFilterProp='title'
loading={loading}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder='选择租户(默认当前租户)'