import { afterEach, expect, test, vi } from 'vitest'; import { api } from './client'; afterEach(() => { vi.restoreAllMocks(); }); test('rawFramesQuery posts structured JSON instead of URL query strings', async () => { const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ data: { items: [], total: 0, limit: 20, offset: 0 }, traceId: 'trace-test', timestamp: 1783094400000 }) } as Response); await api.rawFramesQuery({ keyword: '粤AG18312', protocol: 'GB32960', fields: ['gb32960.vehicle.speed_kmh'], includeFields: true, limit: 20, offset: 0 }); expect(fetchMock).toHaveBeenCalledWith('/api/history/raw-frames/query', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ keyword: '粤AG18312', protocol: 'GB32960', fields: ['gb32960.vehicle.speed_kmh'], includeFields: true, limit: 20, offset: 0 }) }); }); test('vehicleResolve sends keyword to the identity resolution endpoint', async () => { const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ data: { lookupKey: '粤AG18312', resolved: true, vin: 'LB9A32A24R0LS1426', plate: '粤AG18312', phone: '13307795425', oem: 'G7s', protocols: ['GB32960', 'JT808'], online: true, lastSeen: '2026-07-03 20:12:10' }, traceId: 'trace-test', timestamp: 1783094400000 }) } as Response); const result = await api.vehicleResolve(new URLSearchParams({ keyword: '粤AG18312' })); expect(fetchMock).toHaveBeenCalledWith('/api/vehicles/resolve?keyword=%E7%B2%A4AG18312', undefined); expect(result.vin).toBe('LB9A32A24R0LS1426'); }); test('vehicleServiceOverview sends keyword to the lightweight overview endpoint', async () => { const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ data: { vin: 'LB9A32A24R0LS1426', plate: '粤AG18312', phone: '13307795425', oem: 'G7s', protocols: ['GB32960', 'JT808'], primaryProtocol: 'JT808', coverageStatus: 'partial', sourceCount: 2, onlineSourceCount: 1, lastSeen: '2026-07-03 20:12:10', realtimeCount: 2, historyCount: 0, rawCount: 0, mileageCount: 0, qualityIssueCount: 0, serviceStatus: { status: 'degraded', severity: 'warning', title: '来源不完整', detail: '1/2 个来源在线', sourceCount: 2, onlineSourceCount: 1 } }, traceId: 'trace-test', timestamp: 1783094400000 }) } as Response); const result = await api.vehicleServiceOverview(new URLSearchParams({ keyword: '粤AG18312' })); expect(fetchMock).toHaveBeenCalledWith('/api/vehicle-service/overview?keyword=%E7%B2%A4AG18312', undefined); expect(result.coverageStatus).toBe('partial'); expect(result.serviceStatus?.status).toBe('degraded'); }); test('vehicleServiceOverviews posts keywords to the batch overview endpoint', async () => { const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ data: { items: [ { vin: 'VIN001', plate: '粤AG18312', protocols: ['JT808'], coverageStatus: 'online', sourceCount: 1, onlineSourceCount: 1 }, { vin: 'VIN002', plate: '豫A88888', protocols: ['YUTONG_MQTT'], coverageStatus: 'online', sourceCount: 1, onlineSourceCount: 1 } ], total: 2, limit: 200, offset: 0 }, traceId: 'trace-test', timestamp: 1783094400000 }) } as Response); const result = await api.vehicleServiceOverviews({ keywords: ['粤AG18312', 'LMRKH9AC2R1004087'], limit: 200, offset: 0 }); expect(fetchMock).toHaveBeenCalledWith('/api/vehicle-service/overviews', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ keywords: ['粤AG18312', 'LMRKH9AC2R1004087'], limit: 200, offset: 0 }) }); expect(result.total).toBe(2); }); test('vehicleServiceSummary reads the vehicle service summary endpoint', async () => { const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ data: { totalVehicles: 1033, boundVehicles: 1024, onlineVehicles: 208, singleSourceVehicles: 391, multiSourceVehicles: 181, noDataVehicles: 461, identityRequiredVehicles: 9, serviceStatuses: [ { status: 'healthy', title: '服务正常', count: 161 }, { status: 'no_data', title: '暂无数据来源', count: 461 } ], protocols: [{ protocol: 'JT808', online: 157, total: 388 }] }, traceId: 'trace-test', timestamp: 1783094400000 }) } as Response); const result = await api.vehicleServiceSummary(); expect(fetchMock).toHaveBeenCalledWith('/api/vehicle-service/summary', undefined); expect(result.totalVehicles).toBe(1033); expect(result.multiSourceVehicles).toBe(181); expect(result.serviceStatuses.find((item) => item.status === 'no_data')?.count).toBe(461); }); test('reverseGeocode reads the server-side AMap reverse geocode endpoint', async () => { const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ data: { provider: 'AMap', longitude: 113.2, latitude: 23.1, formattedAddress: '广东省广州市天河区测试路', province: '广东省', city: '广州市', district: '天河区', adcode: '440106' }, traceId: 'trace-test', timestamp: 1783094400000 }) } as Response); const result = await api.reverseGeocode(new URLSearchParams({ longitude: '113.2', latitude: '23.1' })); expect(fetchMock).toHaveBeenCalledWith('/api/map/reverse-geocode?longitude=113.2&latitude=23.1', undefined); expect(result.formattedAddress).toBe('广东省广州市天河区测试路'); }); test('qualityNotificationPlan reads alert rules and priority issues from backend', async () => { const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ data: { summary: { issueVehicleCount: 1, issueRecordCount: 1, errorCount: 1, warningCount: 0, protocols: [], issueTypes: [] }, rules: [{ issueType: 'NO_SOURCE', title: '无数据来源', level: 'P0', owner: '平台接入', trigger: '无来源', notify: '立即通知', sla: '30 分钟确认', count: 1 }], policies: [{ name: 'P0 实时中断', target: '接入运维', channel: '邮件', condition: '无来源', escalationMinutes: 30, acceptanceCriteria: '来源恢复并持续 10 分钟' }], priorityIssues: [{ vin: 'VIN001', plate: '粤A001', phone: '', sourceEndpoint: '', protocol: 'VEHICLE_SERVICE', issueType: 'NO_SOURCE', severity: 'error', lastSeen: '', detail: '无来源', priority: 'P0', actionLabel: '确认平台转发', actionDetail: '确认平台转发', sla: '30 分钟确认', vehicleLabel: '粤A001 / VIN001', realtimeHash: '#/realtime?keyword=VIN001', historyHash: '#/history?keyword=VIN001', rawHash: '#/history-query?keyword=VIN001&tab=raw', vehicleHash: '#/detail?keyword=VIN001', notificationText: '【P0 告警通知】无数据来源' }], activeRuleCount: 1, p0RuleCount: 1 }, traceId: 'trace-test', timestamp: 1783094400000 }) } as Response); const result = await api.qualityNotificationPlan(new URLSearchParams({ issueType: 'NO_SOURCE' })); expect(fetchMock).toHaveBeenCalledWith('/api/quality/notification-plan?issueType=NO_SOURCE', undefined); expect(result.rules[0].level).toBe('P0'); expect(result.policies[0].escalationMinutes).toBe(30); expect(result.policies[0].acceptanceCriteria).toContain('来源恢复'); expect(result.priorityIssues[0].notificationText).toContain('告警通知'); }); test('alertEvents reads the vehicle alert event endpoint', async () => { const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ data: { items: [{ vin: 'VIN001', plate: '粤A001', phone: '13307795425', sourceEndpoint: '115.29.187.205:808', protocol: 'JT808', issueType: 'LINK_GAP', severity: 'warning', lastSeen: '2026-07-03 20:12:10', detail: '来源间断' }], total: 1, limit: 20, offset: 0 }, traceId: 'trace-test', timestamp: 1783094400000 }) } as Response); const result = await api.alertEvents(new URLSearchParams({ protocol: 'JT808', limit: '20' })); expect(fetchMock).toHaveBeenCalledWith('/api/alert-events?protocol=JT808&limit=20', undefined); expect(result.items[0].issueType).toBe('LINK_GAP'); }); test('onlineVehicleStatuses reads paged online vehicle status rows', async () => { const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ data: { items: [{ vin: 'LB9A32A24R0LS1426', plate: '粤AG18312', phone: '13307795425', oem: 'G7s', protocols: ['JT808', 'GB32960'], online: false, lastSeen: '2026-07-03 20:12:10', offlineDurationMinutes: 18, sourceCount: 2, onlineSourceCount: 0, bindingStatus: 'bound' }], total: 1, limit: 10, offset: 0 }, traceId: 'trace-test', timestamp: 1783094400000 }) } as Response); const result = await api.onlineVehicleStatuses(new URLSearchParams({ keyword: '粤AG18312', limit: '10' })); expect(fetchMock).toHaveBeenCalledWith('/api/statistics/online-vehicles?keyword=%E7%B2%A4AG18312&limit=10', undefined); expect(result.items[0].offlineDurationMinutes).toBe(18); }); test('sourceReadiness reads ops source readiness plan', async () => { const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ data: { totalVehicles: 1033, onlineVehicles: 208, kafkaLag: 0, activeConnections: 178, redisOnlineKeys: 258, platformRelease: 'platform-source-test', sources: [{ protocol: 'GB32960', role: '整车与氢能实时数据主来源', online: 73, total: 340, onlineRate: 21.47, missingVehicles: 693, severity: 'warning', status: '覆盖不足', evidence: '在线 73/340', action: '核对平台转发清单', acceptance: '缺失来源车辆下降', vehiclesHash: '#/vehicles?missingProtocol=GB32960', realtimeHash: '#/realtime?protocol=GB32960', historyHash: '#/history-query?protocol=GB32960&tab=raw', alertHash: '#/alert-events?protocol=GB32960' }] }, traceId: 'trace-test', timestamp: 1783094400000 }) } as Response); const result = await api.sourceReadiness(); expect(fetchMock).toHaveBeenCalledWith('/api/ops/source-readiness', undefined); expect(result.platformRelease).toBe('platform-source-test'); expect(result.sources[0].protocol).toBe('GB32960'); }); test('api errors include backend message, detail, and trace id', async () => { vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: false, status: 500, json: async () => ({ error: { code: 'INTERNAL', message: '服务处理失败', detail: 'TDengine timeout' }, traceId: 'trace-error', timestamp: 1783094400000 }) } as Response); await expect(api.opsHealth()).rejects.toThrow('服务处理失败: TDengine timeout (traceId: trace-error)'); });