feat(platform-web): link summary kpis to vehicle filters

This commit is contained in:
lingniu
2026-07-04 03:32:51 +08:00
parent 948dc774d0
commit a2ccc4a498
7 changed files with 141 additions and 18 deletions

View File

@@ -19,6 +19,7 @@ export default function App() {
const [activeVin, setActiveVin] = useState(initialVehicleKey);
const [analysisVin, setAnalysisVin] = useState(initialVehicleKey);
const [activeProtocol, setActiveProtocol] = useState(initialRoute.protocol ?? '');
const [vehicleFilters, setVehicleFilters] = useState<Record<string, string>>(initialRoute.filters ?? {});
const [linkIssueCount, setLinkIssueCount] = useState<number | null>(null);
const [currentVehicleStatus, setCurrentVehicleStatus] = useState<VehicleServiceStatus | undefined>();
const [currentVehicleLabel, setCurrentVehicleLabel] = useState('');
@@ -81,14 +82,17 @@ export default function App() {
setAnalysisVin(route.keyword);
}
}
if (route.page === 'vehicles') {
setVehicleFilters(route.filters ?? {});
}
setActiveProtocol(route.protocol ?? '');
};
window.addEventListener('hashchange', applyHashRoute);
return () => window.removeEventListener('hashchange', applyHashRoute);
}, []);
const replaceHash = (page: PageKey, keyword?: string, protocol?: string) => {
const nextHash = buildAppHash({ page, keyword, protocol });
const replaceHash = (page: PageKey, keyword?: string, protocol?: string, filters?: Record<string, string>) => {
const nextHash = buildAppHash({ page, keyword, protocol, filters });
if (window.location.hash !== nextHash) {
window.history.replaceState(null, '', nextHash);
}
@@ -104,7 +108,13 @@ export default function App() {
replaceHash(page, analysisVin, activeProtocol);
return;
}
replaceHash(page);
replaceHash(page, undefined, undefined, page === 'vehicles' ? vehicleFilters : undefined);
};
const openVehicles = (filters: Record<string, string> = {}) => {
setVehicleFilters(filters);
setActivePage('vehicles');
replaceHash('vehicles', undefined, undefined, filters);
};
const openVehicle = async (keyword: string, protocol?: string) => {
@@ -165,8 +175,8 @@ export default function App() {
};
const pages: Record<PageKey, JSX.Element> = {
dashboard: <Dashboard onOpenVehicle={openVehicle} onOpenQuality={() => navigatePage('quality')} />,
vehicles: <Vehicles onOpenVehicle={openVehicle} />,
dashboard: <Dashboard onOpenVehicle={openVehicle} onOpenQuality={() => navigatePage('quality')} onOpenVehicles={openVehicles} />,
vehicles: <Vehicles onOpenVehicle={openVehicle} initialFilters={vehicleFilters} />,
realtime: <Realtime onOpenVehicle={openVehicle} />,
detail: <VehicleDetail vin={activeVin} protocol={activeProtocol} onOpenHistory={openHistoryForVehicle} onOpenMileage={openMileageForVehicle} onQueryChange={updateVehicleDetailQuery} />,
history: <History initialVin={analysisVin} initialProtocol={activeProtocol} onOpenVehicle={openVehicle} />,

View File

@@ -6,7 +6,20 @@ describe('parseAppHash', () => {
expect(parseAppHash('#/detail?keyword=%E7%B2%A4AG18312&protocol=JT808')).toEqual({
page: 'detail',
keyword: '粤AG18312',
protocol: 'JT808'
protocol: 'JT808',
filters: {}
});
});
test('parses vehicle list filters from hash query', () => {
expect(parseAppHash('#/vehicles?coverage=multi&serviceStatus=degraded&online=online&bindingStatus=bound')).toEqual({
page: 'vehicles',
filters: {
coverage: 'multi',
serviceStatus: 'degraded',
online: 'online',
bindingStatus: 'bound'
}
});
});
@@ -20,6 +33,10 @@ describe('buildAppHash', () => {
expect(buildAppHash({ page: 'history', keyword: '粤AG18312', protocol: 'GB32960' })).toBe('#/history?keyword=%E7%B2%A4AG18312&protocol=GB32960');
});
test('builds shareable vehicle list hash with filters', () => {
expect(buildAppHash({ page: 'vehicles', filters: { coverage: 'multi', serviceStatus: 'degraded' } })).toBe('#/vehicles?coverage=multi&serviceStatus=degraded');
});
test('builds page-only hash when keyword is empty', () => {
expect(buildAppHash({ page: 'quality', keyword: '' })).toBe('#/quality');
});

View File

@@ -6,8 +6,11 @@ export type AppRoute = {
page?: PageKey;
keyword?: string;
protocol?: string;
filters?: Record<string, string>;
};
const filterKeys = ['coverage', 'serviceStatus', 'online', 'bindingStatus'] as const;
export function parseAppHash(hash: string): AppRoute {
const normalized = hash.trim().replace(/^#\/?/, '');
if (!normalized) {
@@ -20,7 +23,14 @@ export function parseAppHash(hash: string): AppRoute {
const params = new URLSearchParams(queryPart);
const keyword = params.get('keyword')?.trim() || undefined;
const protocol = params.get('protocol')?.trim() || undefined;
return { page: pagePart as PageKey, keyword, protocol };
const filters: Record<string, string> = {};
for (const key of filterKeys) {
const value = params.get(key)?.trim();
if (value) {
filters[key] = value;
}
}
return { page: pagePart as PageKey, keyword, protocol, filters };
}
export function buildAppHash(route: AppRoute): string {
@@ -34,6 +44,12 @@ export function buildAppHash(route: AppRoute): string {
if (protocol) {
params.set('protocol', protocol);
}
for (const key of filterKeys) {
const value = route.filters?.[key]?.trim();
if (value) {
params.set(key, value);
}
}
const query = params.toString();
return query ? `#/${page}?${query}` : `#/${page}`;
}

View File

@@ -51,7 +51,7 @@ function rowServiceStatus(row: { serviceStatus?: { title: string; severity: stri
return { label: '服务正常', color: 'green' as const };
}
export function Dashboard({ onOpenVehicle, onOpenQuality }: { onOpenVehicle: (vin: string) => void; onOpenQuality: () => void }) {
export function Dashboard({ onOpenVehicle, onOpenQuality, onOpenVehicles }: { onOpenVehicle: (vin: string) => void; onOpenQuality: () => void; onOpenVehicles: (filters?: Record<string, string>) => void }) {
const [summary, setSummary] = useState<DashboardSummary | null>(null);
const [serviceSummary, setServiceSummary] = useState<VehicleServiceSummary | null>(null);
const [coverage, setCoverage] = useState<VehicleCoverageRow[]>([]);
@@ -95,11 +95,11 @@ export function Dashboard({ onOpenVehicle, onOpenQuality }: { onOpenVehicle: (vi
.finally(() => setLoading(false));
}, []);
const kpis = [
{ label: '总车辆', value: formatCount(serviceSummary?.totalVehicles) },
{ label: '在线车辆', value: formatCount(serviceSummary?.onlineVehicles ?? summary?.onlineVehicles) },
{ label: '多源车辆', value: formatCount(serviceSummary?.multiSourceVehicles) },
{ label: '身份未绑定', value: formatCount(serviceSummary?.identityRequiredVehicles) }
const kpis: Array<{ label: string; value: string; filters: Record<string, string> }> = [
{ label: '总车辆', value: formatCount(serviceSummary?.totalVehicles), filters: {} },
{ label: '在线车辆', value: formatCount(serviceSummary?.onlineVehicles ?? summary?.onlineVehicles), filters: { online: 'online' } },
{ label: '多源车辆', value: formatCount(serviceSummary?.multiSourceVehicles), filters: { coverage: 'multi' } },
{ label: '身份未绑定', value: formatCount(serviceSummary?.identityRequiredVehicles), filters: { serviceStatus: 'identity_required' } }
];
return (
@@ -108,9 +108,11 @@ export function Dashboard({ onOpenVehicle, onOpenQuality }: { onOpenVehicle: (vi
<Spin spinning={loading}>
<div className="vp-kpi-grid">
{kpis.map((item) => (
<Card key={item.label} bordered>
<Card key={item.label} bordered className="vp-kpi-card" bodyStyle={{ padding: 0 }}>
<button className="vp-kpi-button" type="button" onClick={() => onOpenVehicles(item.filters)} aria-label={`${item.label} ${item.value}`}>
<div className="vp-kpi-value">{item.value}</div>
<div className="vp-kpi-label">{item.label}</div>
</button>
</Card>
))}
</div>

View File

@@ -28,10 +28,10 @@ function vehicleServiceStatus(row: VehicleCoverageRow) {
return { label: '服务正常', color: 'green' as const };
}
export function Vehicles({ onOpenVehicle }: { onOpenVehicle: (vin: string) => void }) {
export function Vehicles({ onOpenVehicle, initialFilters = {} }: { onOpenVehicle: (vin: string) => void; initialFilters?: Record<string, string> }) {
const [rows, setRows] = useState<VehicleCoverageRow[]>([]);
const [loading, setLoading] = useState(true);
const [filters, setFilters] = useState<Record<string, string>>({});
const [filters, setFilters] = useState<Record<string, string>>(initialFilters);
const [pagination, setPagination] = useState({ currentPage: 1, pageSize: 20, total: 0 });
const load = (values: Record<string, string> = filters, page = pagination.currentPage, pageSize = pagination.pageSize) => {
@@ -52,7 +52,10 @@ export function Vehicles({ onOpenVehicle }: { onOpenVehicle: (vin: string) => vo
.finally(() => setLoading(false));
};
useEffect(() => load(), []);
useEffect(() => {
setFilters(initialFilters);
load(initialFilters, 1, pagination.pageSize);
}, [JSON.stringify(initialFilters)]);
const columns = useMemo(
() => [
@@ -90,7 +93,7 @@ export function Vehicles({ onOpenVehicle }: { onOpenVehicle: (vin: string) => vo
<div className="vp-page">
<PageHeader title="车辆服务" description="以 VIN 为主对象维护车辆身份、数据来源覆盖、在线状态和绑定状态" />
<Card bordered>
<Form layout="horizontal" onSubmit={(values) => {
<Form key={JSON.stringify(filters)} initValues={filters} layout="horizontal" onSubmit={(values) => {
const nextFilters = values as Record<string, string>;
setFilters(nextFilters);
load(nextFilters, 1, pagination.pageSize);

View File

@@ -165,6 +165,27 @@ body {
margin-bottom: 16px;
}
.vp-kpi-card {
overflow: hidden;
}
.vp-kpi-button {
width: 100%;
min-height: 94px;
padding: 20px 24px;
border: 0;
background: transparent;
text-align: left;
cursor: pointer;
font: inherit;
}
.vp-kpi-button:hover,
.vp-kpi-button:focus-visible {
background: #f8fbff;
outline: none;
}
.vp-kpi-value {
font-size: 28px;
font-weight: 700;

View File

@@ -123,6 +123,60 @@ test('dashboard renders vehicle service summary metrics', async () => {
expect(fetchMock).toHaveBeenCalledWith('/api/vehicle-service/summary', undefined);
});
test('opens vehicle list filtered by service summary KPI', async () => {
window.history.replaceState(null, '', '/#/dashboard');
const fetchMock = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
const path = String(input);
if (path.includes('/api/dashboard/summary')) {
return {
ok: true,
json: async () => ({
data: { onlineVehicles: 3, activeToday: 4, frameToday: 1286320, issueVehicles: 7, kafkaLag: 0, protocols: [], serviceStatuses: [], linkHealth: [] },
traceId: 'trace-test',
timestamp: 1783094400000
})
} as Response;
}
if (path.includes('/api/vehicle-service/summary')) {
return {
ok: true,
json: async () => ({
data: {
totalVehicles: 1033,
boundVehicles: 1024,
onlineVehicles: 208,
singleSourceVehicles: 391,
multiSourceVehicles: 181,
noDataVehicles: 461,
identityRequiredVehicles: 9,
serviceStatuses: [],
protocols: []
},
traceId: 'trace-test',
timestamp: 1783094400000
})
} as Response;
}
return {
ok: true,
json: async () => ({
data: { items: [], total: 0, limit: 20, offset: 0 },
traceId: 'trace-test',
timestamp: 1783094400000
})
} as Response;
});
render(<App />);
fireEvent.click(await screen.findByRole('button', { name: /多源车辆/ }));
await waitFor(() => {
expect(fetchMock).toHaveBeenCalledWith(expect.stringContaining('/api/vehicles/coverage?limit=20&offset=0&coverage=multi'), undefined);
});
expect(window.location.hash).toBe('#/vehicles?coverage=multi');
});
test('shows resolved vehicle service status after topbar search', async () => {
window.history.replaceState(null, '', '/#/dashboard');
const fetchMock = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {