修复页面bug
This commit is contained in:
@@ -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;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user