1:首页多租户查询优化 2:景点列表查询优化

This commit is contained in:
2025-10-09 21:08:01 +08:00
parent ff47d983e3
commit a96b775e01
11 changed files with 414 additions and 201 deletions
@@ -54,7 +54,9 @@ public class DashboardController {
anchor = com.central.common.context.LoginUserContextHolder.getCurrentTenantId();
}
}
} catch (Exception ignored) { }
} catch (Exception ignored) {
log.error("获取当前登录用户租户失败");
}
boolean withChildren = (includeChildren == null) || Boolean.TRUE.equals(includeChildren);
params.put("tenantId", anchor);
params.put("includeChildren", withChildren);
@@ -58,21 +58,6 @@ public class TenantResolverService {
log.warn("租户 {} 没有子孙租户,返回自身", anchor);
return Collections.singletonList(anchor);
}
log.info("租户 {} 获取到 {} 个租户(含自身及子孙): {}",
anchor, tenantIds.size(),
tenantIds.size() <= 20 ? tenantIds : tenantIds.subList(0, 20) + "...");
// 特别检查:如果是webApp,验证是否包含了所有预期的租户
if ("webApp".equals(anchor)) {
String[] expectedTenants = {"xcApp", "ymgApp", "zcapp", "zhapp", "djhApp", "sndApp", "sntApp", "tyApp", "ljtxApp", "yfApp"};
for (String expected : expectedTenants) {
if (!tenantIds.contains(expected)) {
log.error("警告:webApp的子孙租户列表缺少预期的租户: {}", expected);
}
}
}
return tenantIds;
} catch (Exception e) {
log.error("获取租户层级失败: {}", e.getMessage(), e);
@@ -1,6 +1,8 @@
package com.central.order.service.impl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.datascope.annotation.IgnoreTenantScope;
import com.central.common.feign.UserService;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.service.impl.SuperServiceImpl;
@@ -37,6 +39,8 @@ public class TourismServiceImpl extends SuperServiceImpl<TourismMapper, Tourism>
@Autowired
private FileCenterService fileCenterService;
@Autowired
private UserService userCenterService;
/**
* 列表
@@ -44,8 +48,22 @@ public class TourismServiceImpl extends SuperServiceImpl<TourismMapper, Tourism>
* @return
*/
@Override
@IgnoreTenantScope
public PageResult<Tourism> findList(Map<String, Object> params){
Page<Tourism> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
String anchor= MapUtils.getString(params,"tenantId");
try {
if (anchor == null || anchor.isEmpty()) {
anchor = com.central.common.context.TenantQueryOverrideContext.getTenantId();
if (anchor == null || anchor.isEmpty()) {
anchor = com.central.common.context.LoginUserContextHolder.getCurrentTenantId();
}
}
} catch (Exception ignored) {
log.error("获取当前登录用户租户失败");
}
List<String> tenantIds = userCenterService.getSonTenantIds(anchor);
params.put("tenantIds",tenantIds);
List<Tourism> list = baseMapper.findList(page, params);
return PageResult.<Tourism>builder().data(list).resp_code(0).count(page.getTotal()).build();
}
+393 -77
View File
@@ -1,27 +1,90 @@
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 { Card, Space, Typography, Row, Col, Button, message, DatePicker, Segmented, List, Tag, Statistic, InputNumber, Slider } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { Line, Pie, Column } from '@ant-design/plots';
import TenantScopeFilter from '@/components/TenantScopeFilter';
import { dashboardApi } from '@/services/dashboard';
import { ordersApi } from '@/services/orders';
import moment, { Moment } from 'moment';
const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
type RangeType = 'date' | 'week' | 'month' | 'year';
const makeDefaultToday = (): [Moment, Moment] => [moment().startOf('day'), moment().endOf('day')];
const computeRangeByType = (type: RangeType, anchor?: Moment): [Moment, Moment] => {
const base = (anchor ? anchor.clone() : moment());
const unit = type === 'date' ? 'day' : type;
return [base.clone().startOf(unit as any), base.clone().endOf(unit as any)];
};
const Welcome: React.FC = () => {
// 租户维度
const [tenantId, setTenantId] = useState<string>();
const [includeChildren, setIncludeChildren] = useState<boolean>(true);
const [statType, setStatType] = useState<'day' | 'month' | 'year'>('day');
// 时间范围(默认今日 00:00:00 - 23:59:59)
const [rangeType, setRangeType] = useState<RangeType>('date');
const [range, setRange] = useState<[Moment, Moment]>(makeDefaultToday());
// 加载状态
const [loading, setLoading] = useState<boolean>(false);
const [pageLoading, setPageLoading] = useState<boolean>(true);
const [ordersLoading, setOrdersLoading] = useState<boolean>(false);
const firstLoadRef = useRef(true);
const [stat, setStat] = useState<any>({ orderStats: {}, chartStats: {} });
const load = async () => {
// 数据
const [stat, setStat] = useState<any>({ orderStats: {}, chartStats: {} });
const [orders, setOrders] = useState<any[]>([]);
const [ordersTotal, setOrdersTotal] = useState<number>(0);
const [page, setPage] = useState<number>(1);
const [pageSize, setPageSize] = useState<number>(10);
// 趋势模式:状态曲线 or 景区柱状
const [trendMode, setTrendMode] = useState<'status' | 'tourism'>('status');
const [aggLoading, setAggLoading] = useState<boolean>(false);
const [statusSeries, setStatusSeries] = useState<{ date: string; type: string; value: number }[]>([]);
const [tourismBars, setTourismBars] = useState<{ name: string; value: number }[]>([]);
// 分账比例(平台),默认 70%
const [splitPercent, setSplitPercent] = useState<number>(70);
// 统一获取 start/end 时间字符串
const getTimeParams = () => {
const [start, end] = range || makeDefaultToday();
// 使用本地时间字符串,避免 ISO(UTC) 引起后端解析或时区偏差
return { startTime: start.format('YYYY-MM-DD HH:mm:ss'), endTime: end.format('YYYY-MM-DD HH:mm:ss') };
};
// 加载统计与订单列表
const load = async (opts?: { page?: number; pageSize?: number }) => {
if (firstLoadRef.current) setPageLoading(true);
setLoading(true);
try {
const res: any = await dashboardApi.statistics({ tenantId, includeChildren, statType });
const { startTime, endTime } = getTimeParams();
// 首页统计(默认排除测试二维码)
const statType = (rangeType === 'month' ? 'month' : (rangeType === 'year' ? 'year' : 'day')) as 'day'|'month'|'year';
const res: any = await dashboardApi.statistics({ tenantId, includeChildren, startTime, endTime, statType, includeTestQrcodes: false });
setStat(res?.data || res);
// 右侧订单列表(默认排除测试二维码)
setOrdersLoading(true);
try {
const curPage = opts?.page ?? page;
const curSize = opts?.pageSize ?? pageSize;
const ordersRes: any = await ordersApi.getDashboardOrders({ tenantId, includeChildren, startTime, endTime, includeTestQrcodes: false, page: curPage, limit: curSize });
const data = ordersRes?.data?.data || ordersRes?.data || [];
const total = ordersRes?.data?.count ?? ordersRes?.count ?? (Array.isArray(data) ? data.length : 0);
setOrders(Array.isArray(data) ? data : []);
setOrdersTotal(Number(total) || 0);
setPage(curPage);
setPageSize(curSize);
} catch {
setOrders([]);
setOrdersTotal(0);
} finally {
setOrdersLoading(false);
}
} catch (e) {
message.error('加载统计失败');
} finally {
@@ -33,17 +96,29 @@ const Welcome: React.FC = () => {
}
};
// 首次/依赖变更自动加载
useEffect(() => {
if (!tenantId) return;
load();
// 条件变化重置到第 1 页
setPage(1);
load({ page: 1, pageSize });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tenantId, includeChildren, statType]);
}, [tenantId, includeChildren, rangeType, range]);
const orderStats = stat?.orderStats || {};
// 趋势聚合:当筛选条件或模式变化时刷新
useEffect(() => {
if (!tenantId) return;
// 趋势分析已关闭,跳过聚合
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tenantId, includeChildren, rangeType, range]);
// Chart 数据
const chartStats = stat?.chartStats || {};
// 每日趋势:订单数/订单金额(元)/退款订单数/退款金额(元)
const trendData = chartStats?.dailySummary || [];
const orderStats = stat?.orderStats || {};
const totalAmountYuan = (orderStats.totalAmount || 0) / 100;
const platformAmount = Number(((totalAmountYuan * splitPercent) / 100).toFixed(2));
const tenantAmount = Number((totalAmountYuan - platformAmount).toFixed(2));
const trendData = (chartStats?.dailySummary || []).map((d: any) => ({ ...d, value: Number(d?.value ?? 0) }));
const distributionData = chartStats?.orderDistribution || [];
const trendColors: Record<string, string> = {
@@ -101,71 +176,206 @@ const Welcome: React.FC = () => {
radius: 0.9,
color: distributionPalette,
legend: { position: 'right' },
label: {
type: 'spider',
content: (data: any) => {
const total = (distributionData || []).reduce((s: number, d: any) => s + (Number(d.value) || 0), 0);
const pct = total > 0 ? `${((Number(data.value) / total) * 100).toFixed(1)}%` : '0%';
return `${data.type} ${pct} (${data.value})`;
},
},
// 由于当前 @ant-design/plots 版本未注册 spider/outer 等 label 形状,关闭标签以避免 Unknown Component 错误
label: false,
animation: false,
};
// 事件:分段切换 -> 根据当前范围起点计算该粒度的起止
const handleRangeTypeChange = (val: any) => {
const t = (val as RangeType) || 'date';
setRangeType(t);
const anchor = range?.[0] || moment();
setRange(computeRangeByType(t, anchor));
};
// 事件:手动选择时间范围
const handleRangeChange = (vals: any) => {
if (!Array.isArray(vals) || vals.length !== 2 || !vals[0] || !vals[1]) {
setRange(makeDefaultToday());
return;
}
let s = vals[0] as Moment;
let e = vals[1] as Moment;
if (rangeType !== 'date') {
s = s.clone().startOf('day');
e = e.clone().endOf('day');
}
setRange([s, e]);
};
// 拉取当前筛选条件下的订单数据,前端聚合生成:
// - 状态曲线(按天、按状态统计订单数)
// - 景区柱状(按景区统计订单数)
const loadAggregations = async () => {
if (!tenantId) return;
setAggLoading(true);
try {
const { startTime, endTime } = getTimeParams();
// 分页抓取,最多抓取一定数量以避免阻塞
const maxRecords = 5000;
const pageSizeAgg = 200;
let cp = 1;
let pulled = 0;
const collected: any[] = [];
// 先探测总量
let total = 0;
try {
const probe: any = await ordersApi.getDashboardOrders({ tenantId, includeChildren, startTime, endTime, includeTestQrcodes: false, page: 1, limit: 1 });
total = Number(probe?.data?.count ?? probe?.count ?? 0) || 0;
} catch {}
if (total === 0) {
setStatusSeries([]);
setTourismBars([]);
return;
}
const target = Math.min(total, maxRecords);
while (pulled < target) {
const res: any = await ordersApi.getDashboardOrders({ tenantId, includeChildren, startTime, endTime, includeTestQrcodes: false, page: cp, limit: pageSizeAgg });
const list = res?.data?.data || res?.data || [];
if (!Array.isArray(list) || list.length === 0) break;
collected.push(...list);
pulled += list.length;
cp += 1;
if (list.length < pageSizeAgg) break;
}
// 聚合:按天、按状态计数
const byDateStatus = new Map<string, Map<number, number>>();
const byTourism = new Map<string, number>();
for (const it of collected) {
const date = (it?.createTime ? moment(it.createTime) : moment()).format('YYYY-MM-DD');
const st = Number(it?.orderStatus);
const name = it?.tourismName || '未知景区';
// 状态聚合
if (!byDateStatus.has(date)) byDateStatus.set(date, new Map<number, number>());
const m = byDateStatus.get(date)!;
m.set(st, (m.get(st) || 0) + 1);
// 景区聚合
byTourism.set(name, (byTourism.get(name) || 0) + 1);
}
// 转换为折线图数据(时间升序)
const dates = Array.from(byDateStatus.keys()).sort((a, b) => a.localeCompare(b));
const series: { date: string; type: string; value: number }[] = [];
for (const d of dates) {
const m = byDateStatus.get(d)!;
for (const opt of STATUS_OPTIONS) {
const v = m.get(opt.value) || 0;
if (v > 0) series.push({ date: d, type: opt.label, value: v });
}
}
// 转换为柱状图数据(按数量降序,取前 20)
const bars: { name: string; value: number }[] = Array.from(byTourism.entries())
.map(([name, value]) => ({ name, value }))
.sort((a, b) => b.value - a.value)
.slice(0, 20);
setStatusSeries(series);
setTourismBars(bars);
} catch {
setStatusSeries([]);
setTourismBars([]);
} finally {
setAggLoading(false);
}
};
// 订单状态:1. 待支付 2. 已取消 3. 支付成功 4. 设备执行中 5. 素材上传中 6. 素材上传完成 7. 用户已下载完成 8. 退款中 9. 退款成功 10. 退款失败
// Tag 颜色使用 antd v4 预设色
const STATUS_OPTIONS: { value: number; label: string; color?: string }[] = [
{ value: 1, label: '待支付', color: 'gold' },
{ value: 2, label: '已取消' },
{ value: 3, label: '支付成功', color: 'green' },
{ value: 4, label: '设备执行中', color: 'blue' },
{ value: 5, label: '素材上传中', color: 'geekblue' },
{ value: 6, label: '素材上传完成', color: 'cyan' },
{ value: 7, label: '用户已下载完成', color: 'purple' },
{ value: 8, label: '退款中', color: 'orange' },
{ value: 9, label: '退款成功', color: 'lime' },
{ value: 10, label: '退款失败', color: 'red' },
];
const PAY_TYPE_OPTIONS: { value: number; label: string; color?: string }[] = [
{ value: 1, label: '微信支付', color: 'green' },
{ value: 2, label: '优惠券支付', color: 'blue' },
];
// 将金额(元)格式化为千分位两位小数
const fmtCurrency = (yuan?: number) => {
const v = Number(yuan || 0);
return v.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};
// 从订单行中解析金额(优先 orderAmount,其次 amount)。
// orderAmount 多为“分”的整数字符串,如 "5000" => 50.00 元。
const getOrderAmountYuan = (it: any): number => {
try {
const oa = (it || {}).orderAmount;
if (oa != null) {
const n = Number(oa);
if (Number.isFinite(n)) return n / 100;
const f = parseFloat(String(oa));
if (Number.isFinite(f)) return f;
}
const a = (it || {}).amount;
if (a != null) {
const n = Number(a);
if (Number.isFinite(n)) return n / 100;
}
} catch {}
return 0;
};
return (
<div className="page-enter" style={{ padding: 24 }}>
{/* 顶部工具区 */}
{/* 顶部工具栏:租户 + 时间选择(分段 + 可自定义起止) */}
<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 flex="none"><Title level={4} style={{ margin: 0 }}>首页统计</Title></Col>
<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>
<span>统计时间</span>
<Segmented
options={[
{ label: '周', value: 'day' },
{ label: '月', value: 'month' },
{ label: '年', value: 'year' },
]}
value={statType}
onChange={(val) => setStatType(val as any)}
options={[{ label: '日', value: 'date' }, { label: '周', value: 'week' }, { label: '月', value: 'month' }, { label: '年', value: 'year' }]}
value={rangeType}
onChange={handleRangeTypeChange}
/>
<RangePicker
showTime={rangeType === 'date'}
allowClear={false}
value={range as any}
picker={rangeType as any}
onChange={handleRangeChange}
/>
<Button type="primary" icon={<ReloadOutlined />} loading={loading && !pageLoading} onClick={() => load()}>刷新</Button>
</Space>
<Button type="primary" icon={<ReloadOutlined />} loading={loading && !pageLoading} onClick={load}>刷新</Button>
</Space>
</Col>
</Row>
</Card>
{/* 第一行:总订单概览 / 收入总览(两侧对称,各3项) */}
{/* 第一行:总订单概览 / 金额统计(两侧对称) */}
<Row gutter={[16, 16]}>
<Col xs={24} md={12}>
<Card loading={pageLoading} style={{ height: '100%' }}>
<Space direction="vertical" style={{ width: '100%' }} size={12}>
<Space align="center" size={8}>
<ShoppingCartOutlined />
<Text strong>总订单概览</Text>
</Space>
<Text strong>总订单概览</Text>
<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="," />
<Statistic value={orderStats.totalOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</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.refundedOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
<Statistic value={orderStats.refundedOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</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="," />
<Statistic value={(orderStats.totalOrders || 0) - (orderStats.refundedOrders || 0)} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</Col>
</Row>
</Space>
@@ -174,26 +384,23 @@ const Welcome: React.FC = () => {
<Col xs={24} md={12}>
<Card loading={pageLoading} style={{ height: '100%' }}>
<Space direction="vertical" style={{ width: '100%' }} size={12}>
<Space align="center" size={8}>
<PayCircleOutlined />
<Text strong>收入总览</Text>
</Space>
<Text strong>金额统计</Text>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">订单总金额</Text></Col>
<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="," />
<Statistic value={(orderStats.totalAmount || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</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={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="," />
<Statistic value={(orderStats.refundAmount || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</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={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="," />
<Statistic value={(orderStats.netIncome || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</Col>
</Row>
</Space>
@@ -201,48 +408,158 @@ const Welcome: React.FC = () => {
</Col>
</Row>
{/* 第二行:今日统计 / 状态分布(两侧对称) */}
{/* 分账明细框 */}
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col xs={24} md={12}>
<Card loading={pageLoading} style={{ height: '100%' }}>
<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.todayOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
<Col span={24}>
<Card title="分账明细" loading={pageLoading}>
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<Row align="middle" gutter={12}>
<Col flex="none"><Text>平台分账比例</Text></Col>
<Col flex="240px">
<InputNumber min={0} max={100} value={splitPercent} onChange={(v) => setSplitPercent(Number(v) || 0)} />
<span style={{ marginLeft: 8 }}>%</span>
</Col>
<Col flex="auto">
<Slider min={0} max={100} value={splitPercent} onChange={(v) => setSplitPercent(Number(v))} />
</Col>
<Col flex="none">
<Button onClick={() => setSplitPercent(70)}>重置为 70%</Button>
</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="," />
<Row gutter={12}>
<Col xs={24} md={8}>
<Card size="small">
<Space direction="vertical" style={{ width: '100%' }}>
<Text type="secondary">订单总金额(元)</Text>
<Statistic value={totalAmountYuan} precision={2} />
</Space>
</Card>
</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.todayPaidOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
<Col xs={24} md={8}>
<Card size="small">
<Space direction="vertical" style={{ width: '100%' }}>
<Text type="secondary">平台分账额度(元)</Text>
<Statistic value={platformAmount} precision={2} />
</Space>
</Card>
</Col>
<Col xs={24} md={8}>
<Card size="small">
<Space direction="vertical" style={{ width: '100%' }}>
<Text type="secondary">租户分账额度(元)</Text>
<Statistic value={tenantAmount} precision={2} />
</Space>
</Card>
</Col>
</Row>
</Space>
</Card>
</Col>
</Row>
{/* 第一行:订单状态分布 + 右侧订单列表 */}
<Row gutter={[16, 16]}>
<Col xs={24} md={12}>
<Card title="订单状态分布" loading={pageLoading} style={{ height: '100%' }}>
<Pie {...distributionConfig} />
</Card>
</Col>
<Col xs={24} md={12}>
<Card title={`订单列表(共 ${ordersTotal} 条)`} loading={pageLoading} style={{ height: '100%' }}>
<List
loading={ordersLoading}
dataSource={orders}
pagination={{
current: page,
pageSize,
total: ordersTotal,
showSizeChanger: true,
showQuickJumper: true,
onChange: (cp, ps) => { load({ page: cp, pageSize: ps }); },
}}
renderItem={(item: any) => (
<List.Item>
<List.Item.Meta
title={
<Space>
<span>订单号:{item?.orderNo}</span>
{typeof item?.orderStatus !== 'undefined' ? (() => {
const s = STATUS_OPTIONS.find(o => o.value === item.orderStatus);
return <Tag color={s?.color}>{s?.label || '未知'}</Tag>;
})() : null}
</Space>
}
description={
<Space size={16} wrap>
<span>金额:¥{fmtCurrency(getOrderAmountYuan(item))}</span>
{typeof item?.payType !== 'undefined' ? (
<span>
支付方式:
<Tag color={PAY_TYPE_OPTIONS.find(o => o.value === item.payType)?.color || 'default'}>
{PAY_TYPE_OPTIONS.find(o => o.value === item.payType)?.label || '未知'}
</Tag>
</span>
) : null}
<span>景区:{item?.tourismName || '-'}</span>
<span>时间:{item?.createTime || '-'}</span>
</Space>
}
/>
</List.Item>
)}
/>
</Card>
</Col>
</Row>
{/* 第三行:每日趋势(满宽) */}
{/* 第二行:趋势分析(状态曲线 / 景区柱状) */}
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col span={24}>
<Card title="每日趋势:订单数 / 订单金额 / 退款" loading={pageLoading}>
<Line {...trendConfig} />
<Card
title={
<Space>
<span>趋势分析</span>
<Segmented
options={[{ label: '状态曲线', value: 'status' }, { label: '景区柱状', value: 'tourism' }]}
value={trendMode}
onChange={(v) => setTrendMode(v as any)}
/>
</Space>
}
style={{ display: 'none' }}
loading={pageLoading || aggLoading}
>
{trendMode === 'status' ? (
<Line
data={statusSeries}
xField="date"
yField="value"
seriesField="type"
smooth
height={340}
legend={{ position: 'top' }}
color={(d: any) => {
const label = d?.type;
const opt = STATUS_OPTIONS.find(o => o.label === label);
const colorMap: any = {
gold: '#FAAD14', green: '#52C41A', blue: '#1677FF', geekblue: '#2F54EB', cyan: '#13C2C2', purple: '#722ED1', orange: '#FA8C16', lime: '#A0D911', red: '#F5222D', default: '#5B8FF9'
};
return colorMap[opt?.color || 'default'] || '#5B8FF9';
}}
point={{ size: 2, shape: 'circle' }}
tooltip={{ shared: true }}
/>
) : (
<Column
data={tourismBars}
xField="name"
yField="value"
height={360}
xAxis={{ label: { autoHide: true, autoRotate: true } }}
meta={{ value: { alias: '订单数' } }}
tooltip={{ formatter: (d: any) => ({ name: '订单数', value: String(d?.value ?? 0) }) }}
/>
)}
</Card>
</Col>
</Row>
@@ -251,4 +568,3 @@ const Welcome: React.FC = () => {
};
export default Welcome;
-108
View File
@@ -1,108 +0,0 @@
# 多租户订单统计修复验证说明
## 问题修复清单
### 1. ✅ 租户层级统计问题修复
**文件**:`DashboardServiceImpl.java`
**修改内容**:
- 行261-342:重写`resolveTenantIds`方法
- 添加本地和远程两种方式获取子孙租户
- 增加详细日志追踪
- 添加降级机制
### 2. ✅ webApp超级租户统计修复
**文件**:`DashboardServiceImpl.java`
**修改内容**:
- 行274-303:特殊处理webApp租户
- webApp获取所有顶级租户及其子孙
- 无法获取时不设置tourismIds(查询所有数据)
### 3. ✅ 订单金额统计SQL修复
**文件**:`DashboardMapper.java`
**修改内容**:
- 行242-247:`getTotalAmount`添加tourismIds过滤
- 行273-278:`getRefundAmount`添加tourismIds过滤
## 验证步骤
### 1. 后端验证
```sql
-- 验证租户层级关系
SELECT * FROM sys_tenant WHERE parent_tenant_id IS NOT NULL;
-- 验证景区与租户关系
SELECT t.id, t.name, t.tenant_id, st.tenant_name
FROM tourisms t
LEFT JOIN sys_tenant st ON t.tenant_id = st.tenant_id;
-- 验证订单统计
SELECT
t.tenant_id,
COUNT(o.id) as order_count,
SUM(o.order_amount) as total_amount
FROM orders o
JOIN tourisms t ON o.tourism_id = t.id
GROUP BY t.tenant_id;
```
### 2. API测试
#### 测试普通租户(含子孙)
```bash
GET /api-order/dashboard/statistics?tenantId={父租户ID}&includeChildren=true&statType=day
```
预期:返回该租户及所有子孙租户的订单统计
#### 测试webApp超级租户
```bash
GET /api-order/dashboard/statistics?tenantId=webApp&includeChildren=true&statType=day
```
预期:返回所有租户的订单统计
#### 测试单个租户(不含子孙)
```bash
GET /api-order/dashboard/statistics?tenantId={租户ID}&includeChildren=false&statType=day
```
预期:仅返回指定租户的订单统计
### 3. 前端验证
1. 登录系统访问首页
2. 切换不同租户,观察数据变化
3. 切换"包含子租户"开关,验证数据范围
4. 切换统计粒度(周/月/年),验证时间维度
## 编译问题说明
当前环境Java版本为8,项目需要Java 17。请确保:
1. 安装Java 17(推荐OpenJDK 17或Oracle JDK 17)
2. 设置JAVA_HOME环境变量
3. 运行`mvn clean compile -pl zlt-business/order-center -am`
## 核心逻辑流程
```
用户请求统计
↓
获取租户ID(前端传入 or 当前登录用户)
↓
判断是否webApp
├─是→ 获取所有租户
└─否→ 获取当前租户[+子孙租户]
↓
查询租户关联的景区
↓
根据景区ID统计订单
↓
返回统计结果
```
## 日志监控点
关键日志位置:
- `DashboardServiceImpl:89` - webApp统计日志
- `DashboardServiceImpl:95` - 租户景区范围日志
- `DashboardServiceImpl:317` - 本地租户层级获取
- `DashboardServiceImpl:331` - 远程租户层级获取
- `DashboardServiceImpl:340` - 降级处理日志
通过这些日志可以追踪统计范围是否正确。