tracreport/src/reportGen.ts
2025-07-09 17:35:27 +01:00

67 lines
1.9 KiB
TypeScript

interface ReportSummary {
totalReports: number;
firstTimestamp: Date;
lastTimestamp: Date;
reportsPerUnit: Record<string, number>;
}
interface Report {
unitNumber: string;
reported: string;
comments: string;
utcTimestamp: string;
faults: string[];
}
export async function organiseReports(): Promise<ReportSummary> {
try {
const res = await fetch('https://rep.fjla.uk/fetch');
if (!res.ok) throw new Error(`Fetch failed: ${res.statusText}`);
const reports: Report[] = await res.json();
if (reports.length === 0) {
return {
totalReports: 0,
firstTimestamp: new Date(0), // Epoch
lastTimestamp: new Date(0),
reportsPerUnit: {},
};
}
// Sort by string utcTimestamp (lexical sort works fine for ISO strings)
reports.sort((a, b) => a.utcTimestamp.localeCompare(b.utcTimestamp));
const firstTimestamp = reports[0].utcTimestamp;
const lastTimestamp = reports[reports.length - 1].utcTimestamp;
const totalReports = reports.length;
const reportsPerUnit: Record<string, number> = {};
for (const report of reports) {
const unit = report.unitNumber;
reportsPerUnit[unit] = (reportsPerUnit[unit] || 0) + 1;
}
return {
totalReports,
firstTimestamp: new Date(firstTimestamp),
lastTimestamp: new Date(lastTimestamp),
reportsPerUnit,
};
} catch (err) {
console.error('Error organising reports:', err);
throw err;
}
}
(async () => {
try {
const summary = await organiseReports();
console.log("Total reports:", summary.totalReports);
console.log("First report:", summary.firstTimestamp.toISOString());
console.log("Last report:", summary.lastTimestamp.toISOString());
console.log("Reports per unit:", summary.reportsPerUnit);
} catch (err) {
console.error("Failed to organise reports:", err);
}
})();