多租户与景区关系

This commit is contained in:
2025-09-29 19:29:41 +08:00
parent 4c154ec746
commit dbd4d4d198
37 changed files with 997 additions and 267 deletions
+2 -2
View File
@@ -41,7 +41,7 @@ const Welcome: React.FC = () => {
</Space>
</Col>
<Col>
<TenantScopeFilter />
<TenantScopeFilter useSwitchTenant onChanged={() => { /* 切换后由后端上下文生效 */ }} />
</Col>
</Row>
</Card>
@@ -122,4 +122,4 @@ const Welcome: React.FC = () => {
);
};
export default Welcome;
export default Welcome;
@@ -27,10 +27,10 @@ const AuditLogPage: React.FC = () => {
span={8}
onTenantChanged={() => actionRef.current?.reload?.()}
onFinish={async (values) => {
const { searchKey, searchValue } = values as any;
const { searchKey, searchValue, ...rest } = values as any;
let queryStr = '';
if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`;
setParams({ ...params, queryStr });
setParams({ ...rest, queryStr });
}}
>
<ProFormSelect
@@ -26,10 +26,10 @@ const SlowSqlLogPage: React.FC = () => {
span={8}
onTenantChanged={() => actionRef.current?.reload?.()}
onFinish={async (values) => {
const { searchKey, searchValue } = values as any;
const { searchKey, searchValue, ...rest } = values as any;
let queryStr = '';
if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`;
setParams({ ...params, queryStr });
setParams({ ...rest, queryStr });
}}
>
<ProFormSelect name="searchKey" label="检索" valueEnum={{ none: '全文检索', query_str: '查询语句' }} />
@@ -42,10 +42,10 @@ const SysLogPage: React.FC = () => {
span={8}
onTenantChanged={() => actionRef.current?.reload?.()}
onFinish={async (values) => {
const { searchKey, searchValue } = values as any;
const { searchKey, searchValue, ...rest } = values as any;
let queryStr = '';
if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`;
setParams({ ...params, queryStr });
setParams({ ...rest, queryStr });
}}
>
<ProFormSelect name="searchKey" label="检索" valueEnum={{ none: '全文检索', message: '日志信息', logLevel: '日志级别', appName: '应用名', classname: '类名', traceId: '链路追踪ID' }} />
@@ -21,6 +21,7 @@ const MESSAGE_STATUS: Record<number, { text: string; color: string }> = {
const MessageList: React.FC = () => {
const actionRef = useRef<ActionType>();
const [selectedRows, setSelectedRows] = useState<MessageItem[]>([]);
const [params, setParams] = useState<Record<string, any>>({});
const handleMessageClick = async (record: MessageItem) => {
if (record.status === 0) {
@@ -97,6 +98,7 @@ const MessageList: React.FC = () => {
split
span={8}
onTenantChanged={() => actionRef.current?.reload()}
onFinish={async (values) => setParams(values)}
/>
<ActionBar right={<GradientButton size="middle" key="markAllRead" onClick={handleMarkAllRead}>全部标记已读</GradientButton>} />
@@ -107,7 +109,7 @@ const MessageList: React.FC = () => {
rowKey="id"
search={{ labelWidth: 120 }}
toolBarRender={false}
request={(p) => messageApi.list(p)}
request={(p) => messageApi.list({ ...(p as any), ...params })}
columns={columns}
rowSelection={{ onChange: (_, rows) => setSelectedRows(rows) }}
pagination={{ showQuickJumper: true, showSizeChanger: true }}
@@ -10,6 +10,7 @@ const HomeCarouselPage: React.FC = () => {
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<HomeCarouselItem | undefined>(undefined);
const [params, setParams] = useState<Record<string, any>>({});
const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
@@ -40,14 +41,20 @@ const HomeCarouselPage: React.FC = () => {
return (
<PageContainer header={{ title: '首页轮播' }}>
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => { /* 切换后后端生效 */ }} />
<SearchBarPlus
defaultCollapsed
split
span={8}
onTenantChanged={() => { /* 仅触发表格刷新 */ }}
onFinish={async (values) => setParams(values)}
/>
<ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} />
<GlassCard>
<ProTable<HomeCarouselItem>
rowKey="id"
request={(p) => ordersApi.homeCarouselList(p as any)}
request={(p) => ordersApi.homeCarouselList({ ...(p as any), ...params })}
columns={columns}
search={false}
pagination={{ showSizeChanger: true, showQuickJumper: true }}
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Col, Row, Statistic, message, Button } from 'antd';
import TenantScopeFilter from '@/components/TenantScopeFilter';
@@ -8,22 +8,23 @@ import { ActionBar } from '@/components/ui';
const ProfitSharingStatisticsPage: React.FC = () => {
const [loading, setLoading] = useState(false);
const [stat, setStat] = useState<any>({});
const [scope, setScope] = useState<{ tenantId?: string; includeChildren?: boolean }>({});
const load = async () => {
const load = async (p?: any) => {
setLoading(true);
try {
const res = await ordersApi.getProfitSharingStatistics();
const res = await ordersApi.getProfitSharingStatistics(p);
setStat(res?.data || res);
} catch (e) {
message.error('加载统计失败');
} finally { setLoading(false); }
};
useEffect(() => { load(); }, []);
useEffect(() => { load(scope); }, [scope]);
return (
<PageContainer header={{ title: '分账统计' }} extra={<TenantScopeFilter onChanged={() => load()} /> }>
<ActionBar right={<Button size="middle" onClick={() => load()}>刷新</Button>} />
<PageContainer header={{ title: '分账统计' }} extra={<TenantScopeFilter useSwitchTenant onChanged={(tid, inc) => setScope({ tenantId: tid, includeChildren: inc })} /> }>
<ActionBar right={<Button size="middle" onClick={() => load(scope)}>刷新</Button>} />
<Row gutter={16}>
<Col span={6}><Card loading={loading}><Statistic title="总分账额" value={stat?.totalSharingAmount || 0} precision={2} /></Card></Col>
<Col span={6}><Card loading={loading}><Statistic title="分账笔数" value={stat?.sharingCount || 0} /></Card></Col>
@@ -10,6 +10,7 @@ const QrcodePage: React.FC = () => {
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<QrcodeItem | undefined>(undefined);
const [params, setParams] = useState<Record<string, any>>({});
const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
@@ -40,12 +41,18 @@ const QrcodePage: React.FC = () => {
return (
<PageContainer header={{ title: '二维码管理' }}>
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => { /* 租户切换 */ }} />
<SearchBarPlus
defaultCollapsed
split
span={8}
onTenantChanged={() => { /* 仅触发表格刷新 */ }}
onFinish={async (values) => setParams(values)}
/>
<ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} />
<GlassCard>
<ProTable<QrcodeItem>
rowKey="id"
request={(p) => ordersApi.qrcodeList(p as any)}
request={(p) => ordersApi.qrcodeList({ ...(p as any), ...params })}
columns={columns}
search={false}
pagination={{ showSizeChanger: true, showQuickJumper: true }}
@@ -31,8 +31,15 @@ const StatisticsPage: React.FC = () => {
span={8}
onTenantChanged={() => load(range)}
onFinish={async (values) => {
const v = values?.timeRange;
const r = v && v.length === 2 ? { startTime: v[0]?.toISOString(), endTime: v[1]?.toISOString() } : undefined;
const v = (values as any)?.timeRange;
const base: any = {};
if (v && v.length === 2) {
base.startTime = v[0]?.toISOString();
base.endTime = v[1]?.toISOString();
}
// 合并租户筛选参数
const r = { ...values, ...base } as any;
delete r.timeRange;
setRange(r);
await load(r);
}}
@@ -1,13 +1,17 @@
import React from 'react';
import React from 'react';
import { ModalForm, ProForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import TenantSelector from '@/components/ui/TenantSelector';
export interface TourismItem {
id?: number;
tenantId?: string;
tourismName?: string;
address?: string;
contactPerson?: string;
contactPhone?: string;
status?: number;
tourismAddress?: string;
tourismPhone?: string;
status?: number; // 1 启用,0 禁用
longitude?: string;
latitude?: string;
showInHomepage?: number; // 1 是,0 否
description?: string;
}
@@ -29,14 +33,41 @@ const TourismForm: React.FC<TourismFormProps> = ({ open, title, initialValues, o
initialValues={initialValues}
modalProps={{ destroyOnClose: true }}
>
{/* 所属租户(必选) */}
<TenantSelector nameTenant="tenantId" labelTenant="所属租户" hideIncludeChildren rulesTenant={[{ required: true, message: '请选择租户' }]} />
<ProFormText name="tourismName" label="景区名称" rules={[{ required: true, message: '请输入景区名称' }]} />
<ProFormText name="address" label="地址" />
<ProFormText name="contactPerson" label="联系人" />
<ProFormText name="contactPhone" label="联系电话" />
<ProFormSelect name="status" label="状态" valueEnum={{ 1: '启用', 0: '禁用' }} initialValue={1} />
<ProFormText name="tourismAddress" label="地址" />
<ProFormText name="tourismPhone" label="联系电话" />
<ProForm.Group>
<ProFormText name="longitude" label="经度" placeholder="例如 116.397128" />
<ProFormText name="latitude" label="纬度" placeholder="例如 39.916527" />
</ProForm.Group>
{/* 下拉中文,不显示数字 */}
<ProFormSelect
name="showInHomepage"
label="首页展示"
options={[
{ label: '是', value: 1 },
{ label: '否', value: 0 },
]}
initialValue={0}
/>
<ProFormSelect
name="status"
label="状态"
options={[
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
]}
initialValue={1}
/>
<ProFormTextArea name="description" label="描述" />
</ModalForm>
);
};
export default TourismForm;
@@ -1,56 +1,113 @@
import React, { useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import { PageContainer, ProFormText, ProTable } from '@ant-design/pro-components';
import { Popconfirm, Space, Tag, message } from 'antd';
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
import { PlusOutlined } from '@ant-design/icons';
import { ordersApi } from '@/services/orders';
import TourismForm, { TourismItem } from './components/TourismForm';
import { tenantApi } from '@/services/tenant';
const TourismPage: React.FC = () => {
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<TourismItem | undefined>(undefined);
const [params, setParams] = useState<Record<string, any>>({});
// 首次进入时,默认按“当前租户 + 包含下级租户”查询,避免全量数据
useEffect(() => {
(async () => {
try {
let tenantId: string | undefined;
const cur: any = await tenantApi.getCurrentTenant();
tenantId = cur?.data?.tenantId ?? cur?.tenantId;
if (!tenantId) {
const stats: any = await tenantApi.getScopeStats();
tenantId = stats?.data?.currentTenantId ?? stats?.currentTenantId;
}
if (tenantId) setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren: true }));
} catch {
// 忽略错误,保留手动查询能力
}
})();
}, []);
const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '旅游项目', dataIndex: 'tourismName' },
{ title: '地址', dataIndex: 'address' },
{ title: '联系人', dataIndex: 'contactPerson' },
{ title: '联系电话', dataIndex: 'contactPhone' },
{ title: '状态', dataIndex: 'status', render: (v: number) => <Tag color={v === 1 ? 'green' : 'default'}>{v === 1 ? '启用' : '禁用'}</Tag> },
{ title: '地址', dataIndex: 'tourismAddress' },
{ title: '经度', dataIndex: 'longitude' },
{ title: '纬度', dataIndex: 'latitude' },
{
title: '操作', key: 'action',
title: '首页展示',
dataIndex: 'showInHomepage',
render: (v: number) => <Tag color={v === 1 ? 'green' : 'default'}>{v === 1 ? '是' : '否'}</Tag>,
},
{ title: '联系电话', dataIndex: 'tourismPhone' },
{ title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime' },
{
title: '状态',
dataIndex: 'status',
render: (v: number) => <Tag color={v === 1 ? 'green' : 'default'}>{v === 1 ? '启用' : '禁用'}</Tag>,
},
{
title: '操作',
key: 'action',
render: (_: any, record: TourismItem) => (
<Space>
<a onClick={() => { setCurrent(record); setEditOpen(true); }}>编辑</a>
<Popconfirm title={`确认删除项目[${record.tourismName}]?`} onConfirm={async () => {
const hide = message.loading('删除中...');
try {
await ordersApi.deleteTourism(record.id!);
message.success('删除成功');
} catch (e) {
message.error('删除失败');
} finally { hide(); }
}}>
<Popconfirm
title={`确认删除项目[${record.tourismName}]?`}
onConfirm={async () => {
const hide = message.loading('正在删除...');
try {
await ordersApi.deleteTourism(record.id!);
message.success('删除成功');
} catch {
message.error('删除失败');
} finally { hide(); }
}}
>
<a style={{ color: '#1677ff' }}>删除</a>
</Popconfirm>
</Space>
)
),
},
];
return (
<PageContainer header={{ title: '旅游项目' }}>
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => { /* 租户切换 */ }} />
<ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} />
<SearchBarPlus
defaultCollapsed
split
span={8}
onTenantChanged={(tenantId, includeChildren) => {
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren }));
}}
onFinish={async (values) => setParams(values)}
>
<ProFormText name="tourismName" label="景区名称" placeholder="请输入景区名称" />
</SearchBarPlus>
<ActionBar
left={
<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>
新增
</GradientButton>
}
/>
<GlassCard>
<ProTable<TourismItem>
rowKey="id"
request={(p) => ordersApi.tourism(p as any)}
columns={columns}
search={false}
pagination={{ showSizeChanger: true, showQuickJumper: true }}
/>
{params?.tenantId ? (
<ProTable<TourismItem>
rowKey="id"
params={params}
request={(p) => ordersApi.tourism({ ...(p as any), ...params })}
columns={columns}
search={false}
pagination={{ showSizeChanger: true, showQuickJumper: true }}
toolBarRender={false}
/>
) : null}
</GlassCard>
<TourismForm
@@ -63,8 +120,8 @@ const TourismPage: React.FC = () => {
await ordersApi.saveOrUpdateTourism(values);
message.success('新增成功');
return true;
} catch (e) {
message.error('保存失败');
} catch {
message.error('新增失败');
return false;
} finally { hide(); }
}}
@@ -81,7 +138,7 @@ const TourismPage: React.FC = () => {
await ordersApi.saveOrUpdateTourism({ ...(current as any), ...values });
message.success('修改成功');
return true;
} catch (e) {
} catch {
message.error('修改失败');
return false;
} finally { hide(); }
@@ -1,7 +1,7 @@
import React, { useCallback, useEffect, useState } from 'react';
import { PageContainer, ProFormText, ProFormSelect } from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-components';
import { Space, message } from 'antd';
import { ActionBar, GradientButton, GlassCard, SearchBarPlus } from '@/components/ui';
import { ActionBar, GradientButton, GlassCard } from '@/components/ui';
import { PlusOutlined } from '@ant-design/icons';
import MenuTree from './components/MenuTree';
import MenuForm from './components/MenuForm';
@@ -10,19 +10,17 @@ import { roleApi } from '@/services/role';
import { buildTree } from '@/utils/tree';
const MenuPage: React.FC = () => {
const [apps, setApps] = useState<any[]>([]);
const [tenantId, setTenantId] = useState<string | undefined>();
const [keyword, setKeyword] = useState<string | undefined>();
const [keyword] = useState<string | undefined>(undefined);
const [data, setData] = useState<MenuItem[]>([]);
const [loading, setLoading] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<MenuItem | undefined>(undefined);
const fetchMenu = useCallback(async (clientId: string) => {
const fetchMenu = useCallback(async () => {
setLoading(true);
try {
const menus = await menuApi.list(clientId);
const menus = await menuApi.list();
const list: any[] = menus || [];
const hasSubMenus = list.some((m) => Array.isArray(m?.subMenus));
if (hasSubMenus) {
@@ -57,24 +55,14 @@ const MenuPage: React.FC = () => {
}
}, []);
useEffect(() => {
(async () => {
const list = await roleApi.apps();
setApps(list || []);
if (list?.length) {
const id = list[0].clientId;
setTenantId(id);
fetchMenu(id);
}
})();
}, [fetchMenu]);
useEffect(() => { fetchMenu(); }, [fetchMenu]);
const handleDelete = async (record: MenuItem) => {
const hide = message.loading('删除中...');
const hide = message.loading('鍒犻櫎涓?..');
try {
await menuApi.delete(record.id!);
message.success('鍒犻櫎鑿滃崟鎴愬姛');
if (tenantId) fetchMenu(tenantId);
fetchMenu();
} catch (e) {
message.error('鍒犻櫎鑿滃崟澶辫触');
} finally { hide(); }
@@ -82,16 +70,7 @@ const MenuPage: React.FC = () => {
return (
<PageContainer header={{ title: '鑿滃崟绠$悊' }}>
<SearchBarPlus
defaultCollapsed
split
span={8}
onTenantChanged={() => tenantId && fetchMenu(tenantId)}
onFinish={async (values: any) => { setTenantId(values.tenantId); fetchMenu(values.tenantId); setKeyword(values.keyword); }}
>
<ProFormSelect name="tenantId" label="所属应用" allowClear={false} options={(apps || []).map((i) => ({ label: i.clientId, value: i.clientId }))} />
<ProFormText name="keyword" label="关键字" placeholder="菜单名称关键字" />
</SearchBarPlus>
{/* 去掉查询条件(租户/所属应用),默认查询当前登录人所属租户 */}
<ActionBar
left={
@@ -116,11 +95,11 @@ const MenuPage: React.FC = () => {
open={createOpen}
onOpenChange={setCreateOpen}
onFinish={async (values) => {
const hide = message.loading('保存中...');
const hide = message.loading('淇濆瓨涓?..');
try {
await menuApi.saveOrUpdate(values);
message.success('鏂板�鑿滃崟鎴愬姛');
tenantId && fetchMenu(tenantId);
fetchMenu();
return true;
} catch (e) {
message.error('鏂板�鑿滃崟澶辫触');
@@ -135,11 +114,11 @@ const MenuPage: React.FC = () => {
initialValues={current}
onOpenChange={setEditOpen}
onFinish={async (values) => {
const hide = message.loading('保存中...');
const hide = message.loading('淇濆瓨涓?..');
try {
await menuApi.saveOrUpdate({ ...current, ...values });
message.success('淇�敼鑿滃崟鎴愬姛');
tenantId && fetchMenu(tenantId);
fetchMenu();
return true;
} catch (e) {
message.error('淇�敼鑿滃崟澶辫触');
@@ -153,3 +132,5 @@ const MenuPage: React.FC = () => {
export default MenuPage;
@@ -1,5 +1,6 @@
import React from 'react';
import React from 'react';
import { ModalForm, ProForm, ProFormRadio, ProFormText } from '@ant-design/pro-components';
import TenantSelector from '@/components/ui/TenantSelector';
import { RoleItem } from '@/services/role';
export interface RoleFormProps {
@@ -22,13 +23,14 @@ const RoleForm: React.FC<RoleFormProps> = ({ open, title, initialValues, onOpenC
width={500}
>
<ProForm.Group>
<TenantSelector hideIncludeChildren rulesTenant={[{ required: true, message: '请选择所属租户' }]} />
<ProFormText name="name" label="角色名称" rules={[{ required: true, message: '角色名不能为空' }]} width="lg" />
<ProFormText name="code" label="编码" rules={[{ required: true, message: '编码不能为空' }]} width="lg" />
<ProFormRadio.Group
name="dataScope"
label="数据权限"
width="lg"
options={[{ label: '全部', value: 'ALL' }, { label: '本人', value: 'CREATOR' }]}
options={[{ label: '全部', value: 'ALL' }, { label: '自定义', value: 'CREATOR' }]}
/>
</ProForm.Group>
</ModalForm>
@@ -36,3 +38,4 @@ const RoleForm: React.FC<RoleFormProps> = ({ open, title, initialValues, onOpenC
};
export default RoleForm;
@@ -4,30 +4,22 @@ import { Popconfirm, Space, message } from 'antd';
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
import { PlusOutlined } from '@ant-design/icons';
import { roleApi, RoleItem } from '@/services/role';
import { tenantApi } from '@/services/tenant';
import RoleForm from './components/RoleForm';
import AssignAuth from './components/AssignAuth';
const RolePage: React.FC = () => {
const [apps, setApps] = useState<any[]>([]);
const [params, setParams] = useState<{ tenantId?: string; searchKey?: string; searchValue?: string }>({});
const [params, setParams] = useState<{ tenantId?: string; includeChildren?: boolean; searchKey?: string; searchValue?: string }>({});
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [assignOpen, setAssignOpen] = useState(false);
const [current, setCurrent] = useState<RoleItem | undefined>(undefined);
useEffect(() => {
(async () => {
const list = await roleApi.apps();
setApps(list || []);
if (list?.length) {
const tenantId = list[0].clientId;
setParams((p) => ({ ...p, tenantId }));
}
})();
}, []);
// 以租户为主:通过 SearchBarPlus 内置租户选择器
const columns = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '租户', dataIndex: 'tenantId', width: 160, search: false, render: (_: any, r: RoleItem) => (r as any)?.tenantName || (r as any)?.tenantId || '-' },
{ title: 'ID', dataIndex: 'id' },
{ title: '角色名称', dataIndex: 'name' },
{ title: '编码', dataIndex: 'code' },
@@ -54,16 +46,37 @@ const RolePage: React.FC = () => {
}
];
// 页面初次进入时,自动获取当前租户并触发表格请求
useEffect(() => {
(async () => {
try {
let tenantId: string | undefined;
const cur: any = await tenantApi.getCurrentTenant();
tenantId = cur?.data?.tenantId ?? cur?.tenantId;
if (!tenantId) {
const stats: any = await tenantApi.getScopeStats();
tenantId = stats?.data?.currentTenantId ?? stats?.currentTenantId;
}
if (tenantId) {
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren: true }));
}
} catch (e) {
// 忽略错误,保持手动查询可用
}
})();
}, []);
return (
<PageContainer header={{ title: '角色管理' }}>
<SearchBarPlus
defaultCollapsed={false}
split
span={6}
onTenantChanged={() => { /* 切换租户后服务端上下文生效 */ }}
onTenantChanged={(tenantId, includeChildren) => {
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren }));
}}
onFinish={async (values) => setParams(values)}
>
<ProFormSelect name="tenantId" label="所属应用" allowClear={false} options={(apps || []).map((i) => ({ label: i.clientId, value: i.clientId }))} />
<ProFormSelect name="searchKey" label="搜索" valueEnum={{ name: '角色名称' }} />
<ProFormText name="searchValue" placeholder="请输入关键字" />
</SearchBarPlus>
@@ -80,6 +93,7 @@ const RolePage: React.FC = () => {
<ProTable<RoleItem>
rowKey="id"
headerTitle="角色列表"
params={params}
request={async (p) => roleApi.page({ ...p, ...params })}
columns={columns as any}
search={false}
@@ -134,4 +148,3 @@ const RolePage: React.FC = () => {
};
export default RolePage;
@@ -0,0 +1,116 @@
import React, { useEffect, useMemo, useState } from 'react';
import { ModalForm, ProForm, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { Select, Switch, TreeSelect } from 'antd';
import type { TenantInfo, TenantTreeNode } from '@/services/tenant';
import { tenantApi } from '@/services/tenant';
type UITenantFormValues = Partial<TenantInfo> & { status?: boolean | number };
export interface TenantFormProps {
visible: boolean;
title: string;
initialValues?: UITenantFormValues;
tree: TenantTreeNode[];
onVisibleChange: (v: boolean) => void;
onFinish: (values: TenantInfo) => Promise<boolean>;
form?: any;
}
const toTreeData = (nodes?: TenantTreeNode[] | any): any[] => {
const arr: TenantTreeNode[] = Array.isArray(nodes) ? nodes : [];
return arr.map((n) => ({
title: n.tenantName,
value: n.tenantId,
key: n.tenantId,
children: Array.isArray((n as any).children) && (n as any).children!.length ? toTreeData((n as any).children) : undefined,
}));
};
const TenantForm: React.FC<TenantFormProps> = ({ visible, title, initialValues, tree, onVisibleChange, onFinish, form }) => {
const editing = !!initialValues?.tenantId;
const [allowedTypes, setAllowedTypes] = useState<string[] | undefined>(undefined);
const typeOrder = useMemo(() => ['PLATFORM', 'GROUP', 'COMPANY', 'DEPARTMENT'], []);
const allTypeOptions = useMemo(() => ([
{ value: 'PLATFORM', label: '平台' },
{ value: 'GROUP', label: '集团' },
{ value: 'COMPANY', label: '公司' },
{ value: 'DEPARTMENT', label: '部门' },
]), []);
useEffect(() => {
(async () => {
if (!editing && initialValues?.parentTenantId) {
try {
const pd = await tenantApi.getTenantDetailStd(initialValues.parentTenantId);
const pType = pd?.data?.tenantType as string | undefined;
if (pType) {
const idx = typeOrder.indexOf(pType);
const allowed = idx >= 0 ? typeOrder.slice(idx + 1) : typeOrder;
setAllowedTypes(allowed);
const cur = form?.getFieldValue?.('tenantType');
if (!cur && allowed.length) form?.setFieldsValue?.({ tenantType: allowed[0] });
} else {
setAllowedTypes(typeOrder);
}
} catch {
setAllowedTypes(typeOrder);
}
} else {
setAllowedTypes(typeOrder);
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [visible, editing, initialValues?.parentTenantId]);
const safeInitialValues = useMemo(() => {
const iv: any = initialValues || {};
const s = iv.status;
const statusNum = typeof s === 'boolean' ? (s ? 1 : 0) : s;
return { ...iv, status: statusNum };
}, [initialValues]);
return (
<ModalForm<TenantInfo>
title={title}
visible={visible}
onVisibleChange={onVisibleChange}
onFinish={onFinish}
initialValues={safeInitialValues}
form={form}
width={640}
modalProps={{ destroyOnClose: true, maskClosable: false }}
>
<ProForm.Group>
<ProFormText name='tenantId' label='租户ID' placeholder='唯一标识,创建后不可修改' rules={[{ required: true, message: '请输入租户ID' }]} disabled={editing} />
<ProFormText name='tenantName' label='租户名称' rules={[{ required: true, message: '请输入租户名称' }]} />
</ProForm.Group>
<ProForm.Group>
<ProForm.Item name='parentTenantId' label='上级租户'>
<TreeSelect style={{ width: 260 }} allowClear dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} treeDefaultExpandAll treeData={toTreeData(tree)} placeholder='选择上级租户' disabled={editing} />
</ProForm.Item>
<ProForm.Item name='tenantType' label='类型' rules={[{ required: true, message: '请选择类型' }]}>
<Select style={{ width: 260 }} placeholder='选择类型' disabled={editing && !initialValues?.parentTenantId}>
{(allowedTypes || typeOrder).map((t) => (
<Select.Option key={t} value={t}>{(allTypeOptions.find((x) => x.value === t)?.label) || t}</Select.Option>
))}
</Select>
</ProForm.Item>
</ProForm.Group>
<ProForm.Group>
<ProFormText name='tenantCode' label='编码' />
<ProForm.Item name='status' label='状态' valuePropName='checked' tooltip='启用/停用'>
<Switch checkedChildren='启用' unCheckedChildren='停用' />
</ProForm.Item>
</ProForm.Group>
<ProForm.Group>
<ProFormText name='contactPerson' label='联系人' />
<ProFormText name='contactPhone' label='联系电话' />
</ProForm.Group>
<ProFormText name='address' label='地址' />
<ProFormTextArea name='description' label='描述' />
</ModalForm>
);
};
export default TenantForm;
@@ -0,0 +1,70 @@
import React from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { message, Popconfirm, Space } from 'antd';
import type { TenantInfo } from '@/services/tenant';
import { tenantApi } from '@/services/tenant';
export interface TenantTableProps {
parentTenantId?: string;
actionRef?: React.MutableRefObject<ActionType | undefined>;
onEdit: (record: TenantInfo) => Promise<void> | void;
onDeleted?: () => void;
}
const TenantTable: React.FC<TenantTableProps> = ({ parentTenantId, actionRef, onEdit, onDeleted }) => {
const columns: ProColumns<TenantInfo>[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '租户ID', dataIndex: 'tenantId', copyable: true, ellipsis: true, width: 160 },
{ title: '租户名称', dataIndex: 'tenantName' },
{ title: '类型', dataIndex: 'tenantType', valueType: 'select', valueEnum: { PLATFORM: { text: '平台' }, GROUP: { text: '集团' }, COMPANY: { text: '公司' }, DEPARTMENT: { text: '部门' } } },
{ title: '父租户ID', dataIndex: 'parentTenantId', hideInSearch: true, width: 160 },
{ title: '层级', dataIndex: 'tenantLevel', hideInSearch: true, width: 80 },
{ title: '编码', dataIndex: 'tenantCode', hideInSearch: true },
{ title: '状态', dataIndex: 'status', valueType: 'select', valueEnum: { 1: { text: '启用' }, 0: { text: '停用' } } },
{ title: '联系人', dataIndex: 'contactPerson', hideInSearch: true },
{ title: '联系电话', dataIndex: 'contactPhone', hideInSearch: true },
{
title: '操作', valueType: 'option', width: 200,
render: (_, record) => (
<Space>
<a onClick={() => onEdit(record)}>编辑</a>
<Popconfirm title={`确认删除租户[${record.tenantName}]?`} onConfirm={async () => {
const hide = message.loading('删除中...');
try {
const r = await tenantApi.deleteTenant(record.tenantId);
if ((r as any)?.success) {
message.success('删除成功');
actionRef?.current?.reload?.();
onDeleted?.();
} else {
message.error(((r as any)?.msg) || '删除失败');
}
} finally { hide(); }
}}>
<a style={{ color: '#ff4d4f' }}>删除</a>
</Popconfirm>
</Space>
)
}
];
return (
<ProTable<TenantInfo>
actionRef={actionRef as any}
rowKey="tenantId"
columns={columns}
toolBarRender={false}
request={async (p) => {
const res = await tenantApi.getTenantList({ parentTenantId, 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 as any)?.data?.data || [];
const total = (res as any)?.data?.total || list.length;
return { data: list, total, success: true };
}}
pagination={{ pageSize: 10 }}
search={{ labelWidth: 'auto' }}
/>
);
};
export default TenantTable;
@@ -0,0 +1,72 @@
import React, { useMemo, useState } from 'react';
import { Button, Card, Input, Space, Tree } from 'antd';
import type { DataNode } from 'antd/es/tree';
import { ReloadOutlined } from '@ant-design/icons';
import type { TenantTreeNode } from '@/services/tenant';
export interface TenantTreeProps {
title?: React.ReactNode;
loading?: boolean;
tree: TenantTreeNode[];
value?: string;
onChange?: (tenantId?: string) => void;
onReload?: () => void;
}
const toTreeData = (nodes?: TenantTreeNode[] | any): DataNode[] => {
const arr: TenantTreeNode[] = Array.isArray(nodes) ? nodes : [];
return arr.map((n) => ({
title: n.tenantName,
key: n.tenantId,
value: n.tenantId,
children: Array.isArray((n as any).children) && (n as any).children!.length ? toTreeData((n as any).children) : undefined,
}));
};
const filterTree = (nodes?: TenantTreeNode[] | any, keyword: string = ''): TenantTreeNode[] => {
const arr: TenantTreeNode[] = Array.isArray(nodes) ? nodes : [];
if (!keyword) return arr;
const kw = keyword.trim().toLowerCase();
const loop = (arr: TenantTreeNode[]): TenantTreeNode[] =>
arr.map((n) => ({ ...n, children: n.children ? loop(n.children) : undefined }))
.filter((n) => {
const selfHit = String(n.tenantName || '').toLowerCase().includes(kw);
const childHit = (n.children || []).length > 0;
return selfHit || childHit;
});
return loop(arr);
};
const TenantTree: React.FC<TenantTreeProps> = ({ title = '组织', loading, tree, onChange, onReload }) => {
const [keyword, setKeyword] = useState('');
const displayTree = useMemo(() => filterTree(tree, keyword), [tree, keyword]);
return (
<Card
size="small"
title={title}
extra={(
<Space size={8}>
<Input.Search
allowClear
placeholder="搜索租户"
size="small"
style={{ width: 160 }}
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
/>
<Button size="small" icon={<ReloadOutlined />} loading={!!loading} onClick={onReload}>刷新</Button>
</Space>
)}
bodyStyle={{ height: 'calc(70vh - 24px)', overflow: 'auto' }}
>
<Tree
treeData={toTreeData(displayTree)}
defaultExpandAll
onSelect={(keys) => onChange?.((keys?.[0] as string) || undefined)}
/>
</Card>
);
};
export default TenantTree;
@@ -0,0 +1,121 @@
import React, { useEffect, useMemo, useState } from 'react';
import { Table, Space, Popconfirm, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TenantTreeNode } from '@/services/tenant';
export interface TenantTreeTableProps {
data: TenantTreeNode[];
loading?: boolean;
onAddChild?: (record: TenantTreeNode) => void;
onEdit?: (record: TenantTreeNode) => void;
onDelete?: (record: TenantTreeNode) => void;
}
const TenantTreeTable: React.FC<TenantTreeTableProps> = ({ data, loading, onAddChild, onEdit, onDelete }) => {
const normalize = (nodes?: any[]): any[] => {
if (!Array.isArray(nodes)) return [];
return nodes.map((n: any) => ({
...n,
children: Array.isArray(n?.children) && n.children.length ? normalize(n.children) : undefined,
}));
};
const safeData = useMemo(() => normalize(data as any), [data]);
// 计算并控制展开行,保证“默认展开”在异步数据加载后仍生效
const allExpandableKeys = useMemo(() => {
const keys: React.Key[] = [];
const walk = (arr?: any[]) => {
if (!Array.isArray(arr)) return;
for (const n of arr) {
const hasChildren = Array.isArray(n?.children) && n.children.length > 0;
if (hasChildren) keys.push(n.tenantId);
if (hasChildren) walk(n.children);
}
};
walk(safeData);
return keys;
}, [safeData]);
const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]);
useEffect(() => {
// 仅当列表 keys 实际发生变化时才更新,避免无意义的重复 setState
setExpandedRowKeys((prev) => {
const a = allExpandableKeys;
if (prev.length === a.length && prev.every((v, i) => v === a[i])) return prev;
return a;
});
}, [allExpandableKeys]);
const columns: ColumnsType<TenantTreeNode> = [
{
title: '租户名称',
dataIndex: 'tenantName',
render: (_: any, record: TenantTreeNode) => <span>{record.tenantName}</span>,
},
{ title: '租户ID', dataIndex: 'tenantId', width: 180, ellipsis: true },
{
title: '类型', dataIndex: 'tenantType', width: 120,
render: (v: any) => {
const map: Record<string, { color: string; text: string }> = {
PLATFORM: { color: 'purple', text: '平台' },
GROUP: { color: 'cyan', text: '集团' },
COMPANY: { color: 'blue', text: '公司' },
DEPARTMENT: { color: 'geekblue', text: '部门' },
};
const m = map[String(v)] || { color: 'default', text: String(v || '-') } as any;
return <Tag color={m.color}>{m.text}</Tag>;
},
},
{
title: '状态', dataIndex: 'status', width: 100,
render: (v: any, record: TenantTreeNode) => {
const enabled = typeof v === 'boolean' ? v : (v === 1 || v === '1' || (record as any)?.enabled === true || v == null);
return enabled ? <Tag color='green'>启用</Tag> : <Tag color='red'>停用</Tag>;
},
},
{ title: '联系人', dataIndex: 'contactPerson', width: 120 },
{ title: '联系电话', dataIndex: 'contactPhone', width: 140 },
{
title: '操作', key: 'action', width: 220,
render: (_: any, rec: TenantTreeNode | undefined) => {
const record = (rec || ({} as TenantTreeNode));
const hasId = !!(record as any)?.tenantId;
return (
<Space>
<a onClick={() => hasId && onEdit?.(record)}>编辑</a>
{onAddChild ? <a onClick={() => hasId && onAddChild?.(record)}>新增下级</a> : null}
<Popconfirm title={`确认删除租户[${record?.tenantName ?? ''}]?`} onConfirm={() => hasId && onDelete?.(record)}>
<a style={{ color: '#1677ff' }}>删除</a>
</Popconfirm>
</Space>
);
},
},
];
return (
<Table
rowKey='tenantId'
columns={columns}
dataSource={safeData as any}
loading={loading}
pagination={false}
expandable={{
expandedRowKeys,
onExpand: (expanded, record: any) => {
setExpandedRowKeys((prev) => {
const key = record?.tenantId;
if (key == null) return prev;
const set = new Set(prev);
if (expanded) set.add(key);
else set.delete(key);
return Array.from(set);
});
},
}}
size='middle'
/>
);
};
export default TenantTreeTable;
@@ -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';
@@ -12,7 +12,7 @@ export interface UserTableProps {
onEdit: (record: UserItem) => void;
onResetPassword: (record: UserItem) => void;
onDelete: (record: UserItem) => void;
// 额外查询参数(由外层统一查询栏传入)
// 额外查询参数(由外部查询条件统一注入)
extraParams?: Record<string, any>;
}
@@ -30,6 +30,7 @@ const UserTable = forwardRef<UserTableRef, UserTableProps>(({ onEdit, onResetPas
const columns: ProColumns<UserItem>[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '所属租户', dataIndex: 'company', width: 160, search: false, render: (_, r) => (r as any)?.company || (r as any)?.tenantId || '-' },
{ title: '用户ID', dataIndex: 'id', width: 100, search: false },
{ title: '用户名', dataIndex: 'username' },
{ title: '用户昵称', dataIndex: 'nickname' },
@@ -61,16 +62,18 @@ const UserTable = forwardRef<UserTableRef, UserTableProps>(({ onEdit, onResetPas
actionRef={actionRef}
rowKey="id"
columns={columns}
// 当外部查询参数变更时,自动触发请求
params={extraParams}
request={async (p) => {
const { data, total } = await systemApi.users({ ...(p as any), ...(extraParams || {}) } as any);
return { data, total, success: true };
}}
pagination={{ pageSize: 10 }}
// 统一:关闭 ProTable 自带搜索,由外层 SearchBarPlus 统一承载
// 统一关闭 ProTable 自带搜索,由 SearchBarPlus 统一驱动
search={false}
toolBarRender={false}
/>
);
});
export default UserTable;
export default UserTable;
@@ -70,6 +70,8 @@ const UsersPage: React.FC = () => {
};
const isAppType = params?.type === 'APP';
const { tenantId, includeChildren, ...restParams } = params || {};
const listParams = isAppType ? restParams : params;
return (
<PageContainer header={{ title: '用户管理' }}>
@@ -79,10 +81,15 @@ const UsersPage: React.FC = () => {
defaultCollapsed={false}
split
span={6}
onTenantChanged={() => tableRef.current?.reload()}
showTenant={!isAppType}
onTenantChanged={(tenantId, includeChildren) => {
// 租户切换时,直接更新查询参数,ProTable 会因 params 变更自动请求
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren }));
}}
onFinish={async (values) => {
setParams(values);
tableRef.current?.reload();
const v: any = { ...(values || {}) };
if (v?.type === 'APP') { delete v.tenantId; delete v.includeChildren; }
setParams(v); // 交由 ProTable(params) 触发请求
}}
>
<ProFormSelect name="type" label="用户类型" valueEnum={{ BACKEND: '系统用户', APP: 'C端用户' }} initialValue="BACKEND" />
@@ -96,7 +103,7 @@ const UsersPage: React.FC = () => {
onEdit={(r) => { setCurrentRow(r); setEditVisible(true); }}
onResetPassword={(r) => resetPwd(r)}
onDelete={(r) => delUser(r)}
extraParams={params}
extraParams={listParams}
/>
</GlassCard>
@@ -110,4 +117,3 @@ const UsersPage: React.FC = () => {
};
export default UsersPage;