Files
gofly-platform-services/zlt-web/react-web-next/src/pages/system/TenantManage/index.tsx
T

328 lines
14 KiB
TypeScript
Raw Normal View History

2025-09-26 18:42:41 +08:00
import React, { useCallback, useEffect, useState } from "react";
import { PageContainer } from "@ant-design/pro-components";
2025-10-01 03:51:53 +08:00
import { Space, message, Button, Select } from "antd";
2025-09-26 18:42:41 +08:00
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";
2025-09-26 18:42:41 +08:00
// UI 表单初始值:status 允许 boolean | number,便于与 Switch 绑定
type UITenantFormValues = Partial<TenantInfo> & { status?: boolean | number };
const TenantManage: React.FC = () => {
2025-09-26 18:42:41 +08:00
const [data, setData] = useState<TenantTreeNode[]>([]);
const [loading, setLoading] = useState(false);
const [formOpen, setFormOpen] = useState(false);
const [editing, setEditing] = useState(false);
2025-09-26 18:42:41 +08:00
const [initialValues, setInitialValues] = useState<UITenantFormValues | undefined>(undefined);
const [treeCache, setTreeCache] = useState<TenantTreeNode[]>([]);
2025-10-01 03:51:53 +08:00
// 状态筛选:1=启用, 0=停用, 'all'=全部;默认启用
const [statusFilter, setStatusFilter] = useState<1 | 0 | 'all'>(1);
// 路径拼接:去掉前缀 null/undefined、首尾斜杠,仅用单斜杠连接
const joinPath = (base?: string, id?: string) => {
const b = String(base || '')
.trim()
.replace(/^null/gi, '')
.replace(/^undefined/gi, '')
.replace(/\/+$/g, '')
.replace(/^\/+/, '');
const t = String(id || '')
.trim()
.replace(/^\/+/, '')
.replace(/\/+$/g, '');
return b ? `${b}/${t}` : t;
};
2025-09-26 18:42:41 +08:00
const fetchTree = useCallback(async () => {
setLoading(true);
try {
2025-09-26 18:42:41 +08:00
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;
2025-10-01 03:51:53 +08:00
const resPage: any = await tenantApi.getTenantList({ parentTenantId: parentId, status: (statusFilter === 'all' ? undefined : statusFilter) as any, current: 1, pageSize: 1000 } as any);
2025-09-26 18:42:41 +08:00
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) {
2025-10-01 03:51:53 +08:00
const resp: any = await tenantApi.getTenantList({ parentTenantId: node.tenantId, status: (statusFilter === 'all' ? undefined : statusFilter) as any, current: 1, pageSize: 1000 } as any);
2025-09-26 18:42:41 +08:00
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 {}
2025-10-01 03:51:53 +08:00
// 递进加载至第三级,保证三级部门可见
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;
// 再次兜底补全基础信息
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 {}
const needLoad = !Array.isArray(node.children) || node.children.length === 0;
if (needLoad) {
try {
const resp: any = await tenantApi.getTenantList({ parentTenantId: node.tenantId, status: (statusFilter === 'all' ? undefined : statusFilter) as any, 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 {}
}
if (Array.isArray(node.children)) resultChildren.push(...node.children);
}));
return resultChildren;
};
try {
const level2 = await loadChildrenFor(list);
await loadChildrenFor(level2);
} catch {}
// 按状态筛选(仅当选择启用或停用时)
const filterTreeByStatus = (nodes?: any[]): any[] => {
if (statusFilter === 'all') return Array.isArray(nodes) ? nodes : [];
const want = statusFilter;
const walk = (arr?: any[]): any[] => {
if (!Array.isArray(arr)) return [];
const res: any[] = [];
for (const n of arr) {
const v = (typeof (n as any)?.status === 'boolean') ? ((n as any).status ? 1 : 0) : (n as any)?.status;
if (v === want) {
const item: any = { ...n };
if (Array.isArray((n as any).children)) item.children = walk((n as any).children);
res.push(item);
} else if (Array.isArray((n as any).children)) {
const sub = walk((n as any).children);
if (sub.length) res.push(...sub);
}
}
return res;
};
return walk(nodes);
};
const finalList = filterTreeByStatus(list);
2025-09-26 18:42:41 +08:00
setTreeCache(list);
2025-10-01 03:51:53 +08:00
setData(finalList);
2025-09-26 18:42:41 +08:00
} catch (e) {
message.error("获取租户数据失败");
} finally { setLoading(false); }
2025-10-01 03:51:53 +08:00
}, [statusFilter]);
2025-09-26 18:42:41 +08:00
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("获取租户详情失败");
}
};
2025-09-26 18:42:41 +08:00
const handleDelete = async (record: TenantTreeNode) => {
const hide = message.loading("删除中...");
try {
2025-09-26 18:42:41 +08:00
const r: any = await tenantApi.deleteTenant(record.tenantId);
if (r?.success) {
message.success("删除成功");
fetchTree();
} else {
message.error(r?.msg || "删除失败");
}
} finally { hide(); }
};
return (
2025-09-26 18:42:41 +08:00
<PageContainer header={{ title: "租户管理" }}>
<ActionBar
2025-09-26 18:42:41 +08:00
left={(
<Space>
2025-09-26 18:42:41 +08:00
<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={openCreateRoot}>新增</GradientButton>
<Button onClick={fetchTree}>刷新</Button>
</Space>
)}
2025-10-01 03:51:53 +08:00
right={(
<Space>
<span>状态:</span>
<Select
size="middle"
style={{ width: 120 }}
value={statusFilter}
onChange={(v: any) => setStatusFilter(v)}
options={[
{ value: 1, label: '启用' },
{ value: 0, label: '停用' },
{ value: 'all', label: '全部' },
]}
/>
</Space>
)}
/>
2025-09-26 18:42:41 +08:00
<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 || {};
2025-10-01 03:51:53 +08:00
const base = p?.tenantPath || p?.tenantId || payload.parentTenantId;
payload.tenantPath = joinPath(base, payload.tenantId);
2025-09-26 18:42:41 +08:00
payload.tenantLevel = (p.tenantLevel || 0) + 1;
} catch {
2025-10-01 03:51:53 +08:00
payload.tenantPath = joinPath(payload.parentTenantId, payload.tenantId);
2025-09-26 18:42:41 +08:00
payload.tenantLevel = 1;
}
} else {
2025-10-01 03:51:53 +08:00
payload.tenantPath = joinPath(undefined, payload.tenantId);
2025-09-26 18:42:41 +08:00
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;
2025-10-01 03:51:53 +08:00
// 使用统一的 joinPath 规范化路径
2025-09-26 18:42:41 +08:00
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;
2025-09-26 18:42:41 +08:00