Compete provisional report generation code

This commit is contained in:
Fred Boniface 2025-07-09 19:17:10 +01:00
parent 5b9da3adce
commit 84530f7a1f
4 changed files with 287 additions and 0 deletions

View File

@ -5,6 +5,19 @@ interface ReportSummary {
reportsPerUnit: Record<string, number>; reportsPerUnit: Record<string, number>;
} }
interface vehicleDetails {
vehicleNumber: string;
reportCount: number;
cabFront: boolean;
cabRear: boolean;
}
interface ReportsByUnit {
unitNumber: string;
vehicles: vehicleDetails[];
comments: string[];
}
interface Report { interface Report {
unitNumber: string; unitNumber: string;
reported: string; reported: string;
@ -54,6 +67,10 @@ export async function organiseReports(): Promise<ReportSummary> {
} }
} }
// Fetch all unit numbers.
// Group reports by unit number.
// Build HTML for each report.
(async () => { (async () => {
try { try {
const summary = await organiseReports(); const summary = await organiseReports();

167
src/reports/reportHtml.ts Normal file
View File

@ -0,0 +1,167 @@
import { GroupedUnitReport, VehicleReport } from "./reports";
export function generateHTMLReport(units: GroupedUnitReport[], startDate: Date, endDate: Date): string {
const unitsWithReports = units.filter(unit =>
unit.vehicles.some(
v => v.saloonReports > 0 || v.cabReports > 0
)
);
const body = unitsWithReports.map(renderUnitSection).join('\n');
return wrapHtml(body, startDate, endDate);
}
function renderUnitSection(unit: GroupedUnitReport): string {
const total = unit.vehicles.length;
return `
<div class="train-container">
<h1 class="unit-number">${unit.unitNumber}</h1>
<div class="vehicle-container">
${unit.vehicles.map((v, i) => renderCoach(v, i, total)).join('\n')}
</div>
${renderComments(unit.comments)}
</div>`;
}
function renderCoach(vehicle: VehicleReport, index: number, total: number): string {
const cabMarkerHTML = vehicle.hasCabZone
? `<div class="cab-marker">${vehicle.cabReports}</div>`
: '';
const cabAbove = index === 0;
const cabBelow = index === total -1;
return `
<div class="coach">
<div class="vehicle-number">${vehicle.vehicleNumber}</div>
<div class="vehicle-box">
${cabAbove ? cabMarkerHTML : ''}
<div class="report-count">${vehicle.saloonReports}</div>
${cabBelow && !cabAbove ? cabMarkerHTML : ''}
</div>
</div>
`;
}
function renderComments(comments: string[]): string {
const renderedComments = comments.length
? comments.map(c => `<p>${c}</p>`).join('\n')
: '<p>No comments submitted.</p>';
return `
<div class="comments-box">
<h2>Comments</h2>
${renderedComments}
</div>
`;
}
function wrapHtml(content: string, startDate: Date, endDate: Date): string {
const formatDate = (d: Date) => d.toISOString().split('T')[0];
return `
<!DOCTYPE html>
<html lang="en">
<head>
<title>TrACreport - Report Output</title>
<style>
body {
font-family: sans-serif;
}
.preface {
text-align: center;
font-size: 0.9em;
}
.train-container {
width: 75%;
margin: 2em auto;
padding: 1em;
border-radius: 8px;
}
.unit-number {
text-align: center;
margin-bottom: 1em;
font-size: 1.5em;
}
.vehicle-container {
display: flex;
justify-content: space-between;
gap: 0.5em;
}
.coach {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
}
.vehicle-number {
margin-bottom: 0.5em;
font-weight: bold;
}
.vehicle-box {
width: 100%;
height: 50px;
background-color: #e0e0e0;
border: 2px solid black;
border-radius: 6px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 6px;
font-size: 1.2em;
box-sizing: border-box;
}
.cab-marker {
width: 1.5em;
text-align: center;
font-weight: bold;
background-color: #d0d0f0;
border-radius: 4px;
padding: 2px;
}
.report-count {
flex: 1;
text-align: center;
}
.comments-box {
margin-top: 1.5em;
padding: 1em;
background-color: #f9f9f9;
border: 1px solid #aaa;
border-radius: 6px;
}
.comments-box h2 {
margin-top: 0;
font-size: 1.2em;
border-bottom: 1px solid #ccc;
padding-bottom: 0.5em;
}
.comments-box p {
margin: 0.5em 0;
}
</style>
</head>
<body>
<div class="preface">
<h1>TrACreport</h1>
<h2>Report period: ${formatDate(startDate)} - ${formatDate(endDate)}</h2>
<p>Total reports received for each vehicle in the West fleet</p>
<p>158 cabs are not recorded as cab cooling is disabled for Guards</p>
</div>
${content}
</body>
</html>`
}

103
src/reports/reports.ts Normal file
View File

@ -0,0 +1,103 @@
interface BaseReport {
unitNumber: string;
reported: string;
comments?: string;
utcTimestamp: Date;
faults: Fault[];
}
interface Fault {
coach: string;
zone: string;
}
export interface GroupedUnitReport {
unitNumber: string;
vehicles: VehicleReport[];
comments: string[];
}
export interface VehicleReport {
vehicleNumber: string;
cabReports: number;
saloonReports: number;
hasCabZone: boolean;
}
async function fetchReports(): Promise<BaseReport[]> {
try {
const res = await fetch('https://rep.fjla.uk/fetch');
if (!res.ok) throw new Error(`Fetch failed: ${res.status} ${res.statusText}`);
const rawData = await res.json();
const reports: BaseReport[] = rawData.map((item: any) => ({
unitNumber: item.unitNumber,
reported: item.reported,
comments: item.comments && item.comments.trim().toLowerCase() !== 'none'
? item.comments
: undefined,
utcTimestamp: new Date(item.utcTimestamp),
faults: item.faults,
}));
return reports;
} catch (err) {
console.error('Error fetching reports:', err);
throw err;
}
}
async function fetchUnitLayout(): Promise<Record<string, { id: string; zones: string[] }[]>> {
const res = await fetch('https://rep.fjla.uk/units.converted.json');
if (!res.ok) throw new Error(`Failed to fetch unit layout: ${res.statusText}`);
return await res.json();
}
function buildInitialReportStructure(
unitLayout: Record<string, { id: string; zones: string[] }[]>
): GroupedUnitReport[] {
return Object.entries(unitLayout).map(([unitNumber, vehicles]) => ({
unitNumber,
comments: [],
vehicles: vehicles.map(v => ({
vehicleNumber: v.id,
saloonReports: 0,
cabReports: 0,
hasCabZone: v.zones.includes('cab'),
}))
}));
};
function populateFaultReports(
grouped: GroupedUnitReport[],
reports: BaseReport[]
): GroupedUnitReport[] {
const unitMap = new Map(grouped.map(u => [u.unitNumber, u]));
for (const report of reports) {
const unit = unitMap.get(report.unitNumber);
if (!unit) continue;
if (report.comments) unit.comments.push(report.comments);
for (const fault of report.faults) {
const vehicle = unit.vehicles.find(v => v.vehicleNumber === fault.coach);
if (!vehicle) continue;
const zone = fault.zone.toLowerCase();
if (zone === 'cab') vehicle.cabReports++;
else vehicle.saloonReports++;
}
}
return grouped;
}
/* USAGE:
const unitLayout = await fetchUnitLayout();
const reports = await fetchReports();
const grouped = buildInitialReportStructure(unitLayout);
const finalReport = populateFaultReports(grouped, reports);
*/