首页统计

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
+5
View File
@@ -2,6 +2,7 @@ import './global.less';
import React from 'react';
import { ThemeProvider } from './theme';
import { history } from 'umi';
import { clearTenantCache, ensureTenantCacheTokenGuard } from '@/utils/tenantCache';
export function rootContainer(container: React.ReactNode, _args?: any) {
return React.createElement(ThemeProvider, null, container);
@@ -21,6 +22,7 @@ export const request: any = {
try {
sessionStorage.removeItem('access_token');
sessionStorage.removeItem('current_user');
clearTenantCache();
} catch {}
const pathname = typeof window !== 'undefined' ? window.location.pathname : '/';
const search = typeof window !== 'undefined' ? window.location.search : '';
@@ -39,6 +41,8 @@ export const request: any = {
const token = sessionStorage.getItem('access_token');
const headers: Record<string, string> = { ...(options?.headers as any) };
if (token) headers['Authorization'] = `Bearer ${token}`;
// 确保缓存与当前 Token 一致(Token 变化则清缓存)
ensureTenantCacheTokenGuard();
return { url, options: { ...options, headers } };
},
],
@@ -65,6 +69,7 @@ export const request: any = {
try {
sessionStorage.removeItem('access_token');
sessionStorage.removeItem('current_user');
clearTenantCache();
} catch {}
const pathname = typeof window !== 'undefined' ? window.location.pathname : '/';
const search = typeof window !== 'undefined' ? window.location.search : '';
@@ -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='选择租户(默认当前租户)'
@@ -17,6 +17,7 @@ import {
import { Link, useLocation, history } from 'umi';
import ProLayout, { MenuDataItem } from '@ant-design/pro-layout';
import { fetchMenuData, outLogin } from '@/services/login';
import { clearTenantCache } from '@/utils/tenantCache';
import { useTheme } from '@/theme';
import { ThemeSwitch } from '@/components/ui';
@@ -57,16 +58,15 @@ const BasicLayout: React.FC = (props: any) => {
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}`; // 静态路由
if (lower === '/welcome' || lower === 'welcome') return '/welcome';
// 兼容后端菜单未带 .html 的叶子路由,例如 /system/tenant => /system/tenant.html
if (lower.startsWith('http')) return cand; // 澶栭摼
if (lower.endsWith('.html')) return cand.startsWith('/') ? cand : `/${cand}`; // 闈欐€佽矾鐢? if (lower === '/welcome' || lower === 'welcome') return '/welcome';
// 鍏煎鍚庣鑿滃崟鏈甫 .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; // 作为分组
return undefined; // 浣滀负鍒嗙粍
};
const getIcon = (p?: string) => {
@@ -96,7 +96,7 @@ const BasicLayout: React.FC = (props: any) => {
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)),
@@ -105,18 +105,24 @@ const BasicLayout: React.FC = (props: any) => {
};
if (!loaded) return [];
const list = menus && menus.length ? menus : [{ name: '欢迎页', url: '/welcome', id: 'welcome-default' }];
return list.map((m, i) => normalize(m, i));
const list = menus && menus.length ? menus : [{ name: '首页', url: '/welcome', id: 'welcome-default' }];
const rendered = list.map((m, i) => normalize(m, i));
const hasHome = rendered.some((r) => r.path === '/welcome');
if (!hasHome) {
rendered.unshift({ key: 'welcome-fixed', name: '首页', path: '/welcome', icon: <DashboardOutlined /> });
}
return rendered;
}, [menus, mode, loaded]);
const rightContentRender = () => (
<Space size="middle">
<Link to="/welcome" style={{ color: 'var(--text-primary)' }}>首页</Link>
<ThemeSwitch mode={mode} onToggle={toggle} />
<Dropdown
menu={{
items: [
{ key: 'profile', icon: <UserOutlined />, label: '个人中心' },
{ key: 'settings', icon: <SettingOutlined />, label: '系统设置' },
{ key: 'settings', icon: <SettingOutlined />, label: '设置' },
{ type: 'divider' as any },
{
key: 'logout',
@@ -127,6 +133,7 @@ const BasicLayout: React.FC = (props: any) => {
try {
sessionStorage.removeItem('access_token');
sessionStorage.removeItem('current_user');
clearTenantCache();
} catch {}
message.success('已退出登录');
history.push('/user/login');
@@ -175,6 +182,7 @@ const BasicLayout: React.FC = (props: any) => {
);
}}
headerTitleRender={(logo, title) => (
<Link to="/welcome" style={{ textDecoration: 'none' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, fontWeight: 600 }}>
<div
style={{
@@ -192,6 +200,7 @@ const BasicLayout: React.FC = (props: any) => {
</div>
<span style={{ fontSize: 18, color: 'var(--text-primary)', fontWeight: 700 }}>{title}</span>
</div>
</Link>
)}
token={{
sider: {
@@ -217,3 +226,6 @@ const BasicLayout: React.FC = (props: any) => {
};
export default BasicLayout;
+161 -98
View File
@@ -1,123 +1,186 @@
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 React, { useEffect, useRef, useState } from 'react';
import { Card, Space, Typography, Row, Col, Statistic, Segmented, Button, message } from 'antd';
import { ShoppingCartOutlined, PayCircleOutlined, ReloadOutlined } from '@ant-design/icons';
import { Line, Pie } from '@ant-design/plots';
import TenantScopeFilter from '@/components/TenantScopeFilter';
import { dashboardApi } from '@/services/dashboard';
const { Title, Paragraph } = Typography;
const { Title, Text } = Typography;
const Welcome: React.FC = () => {
const [time, setTime] = useState(new Date());
const [tenantId, setTenantId] = useState<string>();
const [includeChildren, setIncludeChildren] = useState<boolean>(true);
const [statType, setStatType] = useState<'day' | 'month' | 'year'>('day');
const [loading, setLoading] = useState<boolean>(false);
const [pageLoading, setPageLoading] = useState<boolean>(true);
const firstLoadRef = useRef(true);
const [stat, setStat] = useState<any>({ orderStats: {}, chartStats: {} });
const load = async () => {
if (firstLoadRef.current) setPageLoading(true);
setLoading(true);
try {
const res: any = await dashboardApi.statistics({ tenantId, includeChildren, statType });
setStat(res?.data || res);
} catch (e) {
message.error('加载统计失败');
} finally {
setLoading(false);
if (firstLoadRef.current) {
firstLoadRef.current = false;
setPageLoading(false);
}
}
};
// 仅当选择了租户后再拉取,避免进入页面出现“空 -> 有”的闪动
useEffect(() => {
const timer = setInterval(() => setTime(new Date()), 1000);
return () => clearInterval(timer);
}, []);
if (!tenantId) return;
load();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tenantId, includeChildren, statType]);
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' },
];
const orderStats = stat?.orderStats || {};
const chartStats = stat?.chartStats || {};
const quickActions = [
{ title: '新增订单', icon: <AppstoreOutlined />, color: '#667eea' },
{ title: '用户管理', icon: <TeamOutlined />, color: '#764ba2' },
{ title: '设备监控', icon: <CloudServerOutlined />, color: '#f093fb' },
{ title: '系统设置', icon: <SafetyOutlined />, color: '#4facfe' },
];
const trendData = chartStats?.orderTrend || [];
const distributionData = chartStats?.orderDistribution || [];
const trendConfig: any = {
data: trendData,
xField: 'date',
yField: 'value',
seriesField: 'type',
smooth: true,
height: 300,
legend: { position: 'top' },
tooltip: { shared: true },
animation: false,
};
const distributionConfig: any = {
data: distributionData,
angleField: 'value',
colorField: 'type',
radius: 0.9,
label: { type: 'outer', content: '{name}\n{percentage}' },
animation: false,
};
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' }}>
<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
</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>
</Space>
{/* 顶部工具区:左标题,右侧筛选/粒度/刷新 */}
<Card className="modern-card" style={{ marginBottom: 16 }}>
<Row align="middle" justify="space-between" gutter={[12, 12]}>
<Col flex="none">
<Title level={4} style={{ margin: 0 }}>首页统计</Title>
</Col>
<Col>
<TenantScopeFilter useSwitchTenant onChanged={() => { /* 切换后由后端上下文生效 */ }} />
<Col flex="auto">
<Space style={{ width: '100%', justifyContent: 'flex-end', flexWrap: 'wrap' }} size={12}>
<TenantScopeFilter autoApply onChanged={(tid, inc) => { setTenantId(tid); setIncludeChildren(!!inc); }} />
<Space>
<span>统计粒度</span>
<Segmented
options={[
{ label: '日', value: 'day' },
{ label: '月', value: 'month' },
{ label: '年', value: 'year' },
]}
value={statType}
onChange={(val) => setStatType(val as any)}
/>
</Space>
<Button type="primary" icon={<ReloadOutlined />} loading={loading && !pageLoading} onClick={load}>刷新</Button>
</Space>
</Col>
</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>
</Col>
))}
</Row>
<Row gutter={[24, 24]}>
{/* KPI 指标卡:两列均分,内容居中,不留空白 */}
<Row gutter={[16, 16]}>
<Col xs={24} md={12}>
<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 }}>
<span style={{ color: 'var(--text-secondary)' }}>CPU 使用率</span>
<span style={{ color: 'var(--text-primary)' }}>45%</span>
</div>
<Progress percent={45} strokeColor="#667eea" />
</div>
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
<span style={{ color: 'var(--text-secondary)' }}>内存使用率</span>
<span style={{ color: 'var(--text-primary)' }}>68%</span>
</div>
<Progress percent={68} strokeColor="#764ba2" />
</div>
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
<span style={{ color: 'var(--text-secondary)' }}>磁盘使用率</span>
<span style={{ color: 'var(--text-primary)' }}>32%</span>
</div>
<Progress percent={32} strokeColor="#f093fb" />
</div>
</Space>
</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>}>
<Row gutter={[16, 16]}>
{quickActions.map((action, index) => (
<Col span={12} key={index}>
<Button
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' }}
>
<div style={{ fontSize: 20, marginBottom: 4 }}>{action.icon}</div>
<div style={{ fontSize: 12 }}>{action.title}</div>
</Button>
<Card loading={pageLoading}>
<Space direction="vertical" style={{ width: '100%' }} size={12}>
<Space align="center" size={8}>
<ShoppingCartOutlined />
<Text strong>订单</Text>
</Space>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">总订单数</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={orderStats.totalOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
))}
</Row>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">退款订单数</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={orderStats.refundedOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">今日订单</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={orderStats.todayOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">今日退款</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={orderStats.todayRefundedOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
</Space>
</Card>
</Col>
<Col xs={24} md={12}>
<Card loading={pageLoading}>
<Space direction="vertical" style={{ width: '100%' }} size={12}>
<Space align="center" size={8}>
<PayCircleOutlined />
<Text strong>收入</Text>
</Space>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">订单总金额(元)</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={(orderStats.totalAmount || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">退款金额(元)</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={(orderStats.refundAmount || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">净收入(元)</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={(orderStats.netIncome || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">净订单数(笔)</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={(orderStats.totalOrders || 0) - (orderStats.refundedOrders || 0)} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
</Space>
</Card>
</Col>
</Row>
<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>
<Title level={4} style={{ color: 'var(--text-primary)' }}>高性能架构</Title>
<Paragraph style={{ color: 'var(--text-secondary)' }}>基于微服务架构,支持高并发访问,确保系统稳定运行</Paragraph>
</div>
</Col>
</Row>
</Card>
{/* 图表区:趋势 + 状态分布 */}
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col xs={24} md={16}>
<Card title="订单趋势(创建/完成/退款)" loading={pageLoading}>
<Line {...trendConfig} />
</Card>
</Col>
<Col xs={24} md={8}>
<Card title="订单状态分布" loading={pageLoading}>
<Pie {...distributionConfig} />
</Card>
</Col>
</Row>
</div>
);
};
@@ -83,7 +83,7 @@ const TourismPage: React.FC = () => {
onTenantChanged={(tenantId, includeChildren) => {
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren }));
}}
onFinish={async (values) => setParams(values)}
onFinish={async (values) => setParams((prev) => ({ ...(prev || {}), ...values }))}
>
<ProFormText name="tourismName" label="景区名称" placeholder="请输入景区名称" />
</SearchBarPlus>
@@ -149,4 +149,3 @@ const TourismPage: React.FC = () => {
};
export default TourismPage;
@@ -56,12 +56,16 @@ const TenantTable: React.FC<TenantTableProps> = ({ parentTenantId, actionRef, on
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 });
// 默认按启用筛选;当未选择时传 1
const status = (p as any)?.status ?? 1;
const res = await tenantApi.getTenantList({ parentTenantId, tenantName: (p as any).tenantName, status: 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 }}
// 让搜索表单默认展示“启用”
form={{ initialValues: { status: 1 } }}
search={{ labelWidth: 'auto' }}
/>
);
@@ -1,6 +1,6 @@
import React, { useCallback, useEffect, useState } from "react";
import { PageContainer } from "@ant-design/pro-components";
import { Space, message, Button } from "antd";
import { Space, message, Button, Select } from "antd";
import { ActionBar, GradientButton, GlassCard } from "@/components/ui";
import { PlusOutlined } from "@ant-design/icons";
import TenantForm from "./components/TenantForm";
@@ -17,6 +17,23 @@ const TenantManage: React.FC = () => {
const [editing, setEditing] = useState(false);
const [initialValues, setInitialValues] = useState<UITenantFormValues | undefined>(undefined);
const [treeCache, setTreeCache] = useState<TenantTreeNode[]>([]);
// 状态筛选: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;
};
const fetchTree = useCallback(async () => {
setLoading(true);
@@ -43,7 +60,7 @@ const TenantManage: React.FC = () => {
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 resPage: any = await tenantApi.getTenantList({ parentTenantId: parentId, status: (statusFilter === 'all' ? undefined : statusFilter) as any, 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 }));
@@ -68,7 +85,7 @@ const TenantManage: React.FC = () => {
} 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 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 }));
@@ -77,12 +94,73 @@ const TenantManage: React.FC = () => {
})
);
} 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;
// 再次兜底补全基础信息
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);
setTreeCache(list);
setData(list);
setData(finalList);
} catch (e) {
message.error("获取租户数据失败");
} finally { setLoading(false); }
}, []);
}, [statusFilter]);
useEffect(() => { fetchTree(); }, [fetchTree]);
@@ -136,6 +214,22 @@ const TenantManage: React.FC = () => {
<Button onClick={fetchTree}>刷新</Button>
</Space>
)}
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>
)}
/>
<GlassCard>
@@ -163,15 +257,15 @@ const TenantManage: React.FC = () => {
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;
const base = p?.tenantPath || p?.tenantId || payload.parentTenantId;
payload.tenantPath = joinPath(base, payload.tenantId);
payload.tenantLevel = (p.tenantLevel || 0) + 1;
} catch {
payload.tenantPath = payload.parentTenantId ? `${payload.parentTenantId}/${payload.tenantId}` : payload.tenantId;
payload.tenantPath = joinPath(payload.parentTenantId, payload.tenantId);
payload.tenantLevel = 1;
}
} else {
payload.tenantPath = payload.tenantId;
payload.tenantPath = joinPath(undefined, payload.tenantId);
payload.tenantLevel = 1;
}
}
@@ -181,11 +275,7 @@ const TenantManage: React.FC = () => {
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;
};
// 使用统一的 joinPath 规范化路径
const badPath = !payload.tenantPath || /^null/i.test(String(payload.tenantPath)) || /\/$/.test(String(payload.tenantPath));
if (badPath) {
let base = '';
@@ -1,4 +1,5 @@
import logo from '@/assets/logo.png';
import logo from '@/assets/logo.png';
import React, { useEffect, useRef, useState } from 'react';
import { LoginForm, ProFormText, ProFormCaptcha, ProFormCheckbox } from '@ant-design/pro-components';
import { AppstoreOutlined, LockOutlined, UserOutlined } from '@ant-design/icons';
@@ -26,14 +27,25 @@ const LoginPage: React.FC = () => {
if (loading) return;
setLoading(true);
try {
const res = await login({ ...values, deviceId: uuid });
const res = await login({ ...values, clientId: 'webApp', deviceId: uuid });
// 检查多种可能的token字段位置
const accessToken = res?.access_token || res?.data?.access_token || res?.accessToken;
if (accessToken) {
sessionStorage.setItem('access_token', accessToken);
localStorage.setItem('tenant_client_id', String(values.clientId ?? ''));
// 登录后预热可访问租户树缓存,便于各页快速使用
try {
const { ensureTenantCacheTokenGuard, setTenantTreeCache } = await import('@/utils/tenantCache');
const { tenantApi } = await import('@/services/tenant');
ensureTenantCacheTokenGuard();
const treeRes: any = await tenantApi.getAccessibleTenants();
let list: any[] = [];
if (typeof treeRes?.success !== 'undefined') list = treeRes.success ? (treeRes.data || []) : [];
else if (Array.isArray(treeRes)) list = treeRes as any[];
if (list && list.length) setTenantTreeCache(list);
} catch {}
localStorage.setItem('tenant_client_id', 'webApp');
message.success('登录成功,正在跳转...');
// 使用umi的history进行路由跳转
@@ -84,6 +96,8 @@ const LoginPage: React.FC = () => {
>
<ProFormText
name="clientId"
initialValue="webApp"
disabled
fieldProps={{ size: 'large', prefix: <AppstoreOutlined /> }}
placeholder="请输入租户标识"
rules={[{ required: true, message: '请输入租户标识' }]}
@@ -0,0 +1,19 @@
import { request } from 'umi';
export type StatType = 'day' | 'month' | 'year';
export interface DashboardParams {
tenantId?: string;
includeChildren?: boolean;
statType?: StatType;
[k: string]: any;
}
export const dashboardApi = {
// 首页统计(根据租户 + 子孙 + 时间粒度)
statistics: async (params?: DashboardParams) => {
const res = await request('/api-order/dashboard/statistics', { method: 'GET', params });
return res as any;
},
};
+38 -25
View File
@@ -1,4 +1,4 @@
import { request } from 'umi';
import { request } from 'umi';
export interface OrderItem {
id: number;
@@ -12,6 +12,7 @@ export interface OrderItem {
}
export const ordersApi = {
// 订单列表
order: async (params: { current?: number; pageSize?: number; orderNo?: string; orderStatus?: number; tourismId?: number; payType?: number }) => {
const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
@@ -21,19 +22,19 @@ export const ordersApi = {
const res = await request('/api-order/update/order', { method: 'POST', data });
return (res as any).data || res;
},
// 订单文件相关接口
// 订单文件
orderFiles: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/files', {
method: 'GET',
params: { page: current, limit: pageSize, ...rest },
});
const res = await request('/api-order/files', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number };
},
deleteOrderFile: async (id: number) => {
const res = await request(`/api-order/files/${id}`, { method: 'DELETE' });
return (res as any).data || res;
},
// 二维码
qrcodeList: async (params: { current?: number; pageSize?: number }) => {
const { current, pageSize } = params || {};
const res = await request('/api-order/qrcode', { method: 'GET', params: { page: current, limit: pageSize } });
@@ -47,8 +48,9 @@ export const ordersApi = {
const res = await request(`/api-order/qrcode/${id}`, { method: 'DELETE' });
return (res as any).data || res;
},
// 鏃呮父鏅尯
tourism: async (params: { current?: number; pageSize?: number; [k:string]: any }) => {
// 旅游景区
tourism: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/tourism', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count };
@@ -61,8 +63,9 @@ export const ordersApi = {
const res = await request(`/api-order/tourism/${id}`, { method: 'DELETE' });
return (res as any).data || res;
},
// 棣栭〉杞挱
homeCarousel: async (params: { current?: number; pageSize?: number; [k:string]: any }) => {
// 首页轮播
homeCarousel: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/home/carousel', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count };
@@ -75,13 +78,11 @@ export const ordersApi = {
const res = await request(`/api-order/home/carousel/${id}`, { method: 'DELETE' });
return (res as any).data || res;
},
// 景区素材(图片/视频等)
// 景区资源(图片/视频等)
tourismFile: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/tourism/files', {
method: 'GET',
params: { page: current, limit: pageSize, ...rest },
});
const res = await request('/api-order/tourism/files', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number };
},
saveOrUpdateTourismFile: async (data: any) => {
@@ -92,8 +93,9 @@ export const ordersApi = {
const res = await request(`/api-order/tourism/files/${id}`, { method: 'DELETE' });
return (res as any).data || res;
},
// 退款
refund: async (params: { current?: number; pageSize?: number; [k:string]: any }) => {
refund: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/refund', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count };
@@ -106,11 +108,21 @@ export const ordersApi = {
const res = await request('/api-order/refund/auto', { method: 'PUT', data: payload });
return (res as any).data || res;
},
// 仪表盘统计
dashboard: async (params?: any) => {
// 首页统计
dashboard: async (params?: { tenantId?: string; includeChildren?: boolean; statType?: 'day' | 'month' | 'year'; [k: string]: any }) => {
const res = await request('/api-order/dashboard/statistics', { method: 'GET', params });
return res as any;
},
getDashboardOrders: async (params?: { [k: string]: any }) => {
const res = await request('/api-order/dashboard/orders', { method: 'GET', params });
return res as any;
},
getQrcodeOptions: async (params?: { [k: string]: any }) => {
const res = await request('/api-order/dashboard/qrcode/options', { method: 'GET', params });
return res as any;
},
// 分账
getProfitSharingDetail: async (orderNo: string) => {
const res = await request('/api-order/profitSharing/detail', { method: 'GET', params: { orderNo } });
@@ -124,8 +136,9 @@ export const ordersApi = {
const res = await request('/api-order/profitSharing/statistics', { method: 'GET', params });
return res as any;
},
// 视频模板
getVideoTemplateList: async (params: { current?: number; pageSize?: number; [k:string]: any }) => {
getVideoTemplateList: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/videoTemplate/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count };
@@ -146,8 +159,9 @@ export const ordersApi = {
const res = await request(`/api-order/videoTemplate/${id}/status`, { method: 'PUT', params: { status } });
return (res as any).data || res;
},
// 编辑任务
getEditTaskList: async (params: { current?: number; pageSize?: number; [k:string]: any }) => {
getEditTaskList: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/editTask/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count };
@@ -164,8 +178,9 @@ export const ordersApi = {
const res = await request('/api-order/auto/cut/generate', { method: 'POST', params: { orderNo } });
return (res as any).data || res;
},
// 微信消息
getWxMessageRecords: async (params: { current?: number; pageSize?: number; [k:string]: any }) => {
getWxMessageRecords: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/wx/message/records', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count };
@@ -174,13 +189,11 @@ export const ordersApi = {
const res = await request('/api-order/wx/message/statistics', { method: 'GET', params });
return res as any;
},
// 优惠券
getCouponList: async (params?: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/coupon', {
method: 'GET',
params: { page: current, limit: pageSize, ...rest },
});
const res = await request('/api-order/coupon', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number };
},
getCouponById: async (id: number) => {
@@ -0,0 +1,88 @@
// 租户数据缓存工具:会话级缓存(sessionStorage),按 token 隔离
// - 缓存内容:可访问租户树、按父ID的子节点、详情状态
// - 生命周期:登录成功后预热;退出登录/Token失效时清理;检测到Token变更时自动清理
type AnyNode = { tenantId?: string; tenantName?: string; status?: number | boolean; children?: AnyNode[] };
const KEY_META = 'tenant_cache_meta';
const KEY_TREE = 'tenant_cache_tree';
const KEY_CHILDREN = 'tenant_cache_children';
const KEY_DETAIL = 'tenant_cache_detail';
const safeParse = <T = any>(s?: string | null): T | undefined => {
if (!s) return undefined as any;
try { return JSON.parse(s) as T; } catch { return undefined as any; }
};
const getToken = () => {
try { return sessionStorage.getItem('access_token') || undefined; } catch { return undefined; }
};
export const ensureTenantCacheTokenGuard = () => {
try {
const meta = safeParse<{ token?: string }>(sessionStorage.getItem(KEY_META));
const cur = getToken();
if (!meta?.token || !cur || meta.token !== cur) {
// Token 为空或已变化:清理缓存
clearTenantCache();
if (cur) sessionStorage.setItem(KEY_META, JSON.stringify({ token: cur }));
}
} catch {}
};
export const setTenantTreeCache = (tree: AnyNode[]) => {
try {
ensureTenantCacheTokenGuard();
sessionStorage.setItem(KEY_TREE, JSON.stringify(tree || []));
} catch {}
};
export const getTenantTreeCache = (): AnyNode[] | undefined => {
try {
ensureTenantCacheTokenGuard();
return safeParse<AnyNode[]>(sessionStorage.getItem(KEY_TREE));
} catch { return undefined; }
};
export const setTenantChildrenCache = (parentId: string, children: AnyNode[] | undefined) => {
try {
ensureTenantCacheTokenGuard();
const map = safeParse<Record<string, AnyNode[]>>(sessionStorage.getItem(KEY_CHILDREN)) || {};
if (parentId) map[parentId] = children || [];
sessionStorage.setItem(KEY_CHILDREN, JSON.stringify(map));
} catch {}
};
export const getTenantChildrenCache = (parentId: string): AnyNode[] | undefined => {
try {
ensureTenantCacheTokenGuard();
const map = safeParse<Record<string, AnyNode[]>>(sessionStorage.getItem(KEY_CHILDREN)) || {};
return parentId ? (map[parentId] || undefined) : undefined;
} catch { return undefined; }
};
export const setTenantDetailCache = (tenantId: string, detail: AnyNode | undefined) => {
try {
ensureTenantCacheTokenGuard();
const map = safeParse<Record<string, AnyNode>>(sessionStorage.getItem(KEY_DETAIL)) || {};
if (tenantId) map[tenantId] = detail || {};
sessionStorage.setItem(KEY_DETAIL, JSON.stringify(map));
} catch {}
};
export const getTenantDetailCache = (tenantId: string): AnyNode | undefined => {
try {
ensureTenantCacheTokenGuard();
const map = safeParse<Record<string, AnyNode>>(sessionStorage.getItem(KEY_DETAIL)) || {};
return tenantId ? (map[tenantId] || undefined) : undefined;
} catch { return undefined; }
};
export const clearTenantCache = () => {
try {
sessionStorage.removeItem(KEY_TREE);
sessionStorage.removeItem(KEY_CHILDREN);
sessionStorage.removeItem(KEY_DETAIL);
sessionStorage.removeItem(KEY_META);
} catch {}
};