diff --git a/apps/edr-passenger-api/src/modules/reports/reports.controller.ts b/apps/edr-passenger-api/src/modules/reports/reports.controller.ts index a4da5b208..74bad3514 100644 --- a/apps/edr-passenger-api/src/modules/reports/reports.controller.ts +++ b/apps/edr-passenger-api/src/modules/reports/reports.controller.ts @@ -18,6 +18,18 @@ export class ReportsController { return this.service.generateReport(dto); } + @Get('schedules') + @ApiOperation({ summary: 'List schedules for the passengers report picker' }) + listSchedulesForPicker() { + return this.service.listSchedulesForPicker(); + } + + @Get('passengers/list') + @ApiOperation({ summary: 'Flat passenger list for a specific schedule' }) + getPassengerList(@Query('scheduleId') scheduleId: string) { + return this.service.getPassengerList(scheduleId); + } + @Get('passengers') @ApiOperation({ summary: 'Passengers report for a specific schedule' }) getOccupancyReport(@Query('scheduleId') scheduleId: string) { diff --git a/apps/edr-passenger-api/src/modules/reports/reports.service.ts b/apps/edr-passenger-api/src/modules/reports/reports.service.ts index f4141ecb6..785bf3c17 100644 --- a/apps/edr-passenger-api/src/modules/reports/reports.service.ts +++ b/apps/edr-passenger-api/src/modules/reports/reports.service.ts @@ -286,6 +286,51 @@ export class ReportsService { }; } + async listSchedulesForPicker() { + const schedules = await this.prisma.trainSchedule.findMany({ + select: { + id: true, + departureAt: true, + train: { select: { number: true } }, + originStation: { select: { name: true } }, + destinationStation: { select: { name: true } }, + }, + orderBy: { departureAt: 'desc' }, + take: 200, + }); + return schedules.map(s => ({ + id: s.id, + label: `${s.train.number} · ${s.originStation.name} → ${s.destinationStation.name} · ${new Date(s.departureAt).toLocaleString('en-GB', { dateStyle: 'medium', timeStyle: 'short' })}`, + })); + } + + async getPassengerList(scheduleId: string) { + const seats = await this.prisma.bookingSeat.findMany({ + where: { + scheduleId, + booking: { status: { in: ['CONFIRMED', 'BOARDED'] } }, + }, + include: { + booking: { select: { bookingRef: true, status: true } }, + seat: { include: { coach: { select: { number: true, coachType: { select: { name: true } } } } } }, + }, + orderBy: [{ seat: { coach: { number: 'asc' } } }], + }); + return seats.map(bs => ({ + bookingRef: bs.booking.bookingRef, + bookingStatus: bs.booking.status, + passengerName: bs.passengerName, + passengerCategory: bs.passengerCategory, + idDocumentType: bs.idDocumentType, + idDocumentNumber: bs.idDocumentNumber, + passportNumber: bs.passportNumber, + passportCountry: bs.passportCountry, + seatLabel: bs.seatLabelSnapshot, + coachNumber: bs.seat?.coach?.number ?? null, + coachType: (bs.seat?.coach as any)?.coachType?.name ?? null, + })); + } + async getReport(reportId: string) { return this.prisma.operationalReport.findUnique({ where: { id: reportId } }); } diff --git a/apps/edr-passenger-web/backoffice/src/app/reports/passengers/page.tsx b/apps/edr-passenger-web/backoffice/src/app/reports/passengers/page.tsx index 8b7ef240f..8c6958565 100644 --- a/apps/edr-passenger-web/backoffice/src/app/reports/passengers/page.tsx +++ b/apps/edr-passenger-web/backoffice/src/app/reports/passengers/page.tsx @@ -7,15 +7,10 @@ import { apiClient } from '@/lib/api-client'; import ActionButton from '@/components/ui/ActionButton'; import { formatDateTime } from '@/lib/utils'; +interface ScheduleOption { id: string; label: string; } + interface PassengersReport { - schedule: { - id: string; - trainName: string; - origin: string; - destination: string; - departureAt: string; - arrivalAt: string; - }; + schedule: { id: string; trainName: string; origin: string; destination: string; departureAt: string; arrivalAt: string; }; summary: { totalSeats: number; totalPassengers: number; occupancyRate: number }; byCoach: { coachNumber: string; coachType: string; totalSeats: number; booked: number; occupancyRate: number }[]; byClass: { className: string; totalSeats: number; booked: number; occupancyRate: number }[]; @@ -23,30 +18,79 @@ interface PassengersReport { byDestination: { stationName: string; passengers: number }[]; } +interface PassengerRow { + bookingRef: string; + bookingStatus: string; + passengerName: string; + passengerCategory: string; + idDocumentType: string | null; + idDocumentNumber: string | null; + passportNumber: string | null; + passportCountry: string | null; + seatLabel: string | null; + coachNumber: string | null; + coachType: string | null; +} + +type Tab = 'occupancy' | 'list'; + export default function PassengersReportPage() { const [scheduleId, setScheduleId] = useState(''); - const [submittedId, setSubmittedId] = useState(''); + const [tab, setTab] = useState('occupancy'); + const [listSearch, setListSearch] = useState(''); + + const { data: schedulesRaw, isLoading: loadingSchedules } = useQuery({ + queryKey: ['report-schedules'], + queryFn: () => apiClient.get('/reports/schedules'), + }); + const schedules = schedulesRaw ?? []; const { data, isLoading, isError } = useQuery({ - queryKey: ['passengers-report', submittedId], - queryFn: () => apiClient.get(`/reports/passengers?scheduleId=${submittedId}`), - enabled: !!submittedId, + queryKey: ['passengers-report', scheduleId], + queryFn: () => apiClient.get(`/reports/passengers?scheduleId=${scheduleId}`), + enabled: !!scheduleId, }); - const doExport = () => { - if (!data) return; - const rows = data.byCoach.map((c) => [c.coachNumber, c.coachType, String(c.totalSeats), String(c.booked), `${c.occupancyRate}%`]); - const headers = ['Coach', 'Type', 'Total Seats', 'Booked', 'Occupancy']; - const csv = [headers.join(','), ...rows.map((r) => r.join(','))].join('\n'); + const { data: passengerList = [], isLoading: listLoading } = useQuery({ + queryKey: ['passengers-list', scheduleId], + queryFn: () => apiClient.get(`/reports/passengers/list?scheduleId=${scheduleId}`), + enabled: !!scheduleId, + }); + + const filteredList = listSearch.trim() + ? passengerList.filter(p => + p.passengerName.toLowerCase().includes(listSearch.toLowerCase()) || + p.bookingRef.toLowerCase().includes(listSearch.toLowerCase()) || + (p.idDocumentNumber ?? '').toLowerCase().includes(listSearch.toLowerCase()) || + (p.passportNumber ?? '').toLowerCase().includes(listSearch.toLowerCase()), + ) + : passengerList; + + const downloadCsv = (csv: string, filename: string) => { const blob = new Blob([csv], { type: 'text/csv' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); - a.href = url; - a.download = `passengers-report-${submittedId}.csv`; - a.click(); + a.href = url; a.download = filename; a.click(); URL.revokeObjectURL(url); }; + const doExportOccupancy = () => { + if (!data) return; + const rows = data.byCoach.map(c => [c.coachNumber, c.coachType, String(c.totalSeats), String(c.booked), `${c.occupancyRate}%`]); + downloadCsv([['Coach', 'Type', 'Total Seats', 'Booked', 'Occupancy'].join(','), ...rows.map(r => r.join(','))].join('\n'), `occupancy-${scheduleId}.csv`); + }; + + const doExportList = () => { + if (!passengerList.length) return; + const headers = ['Booking Ref', 'Status', 'Name', 'Category', 'ID Type', 'ID Number', 'Passport', 'Country', 'Seat', 'Coach', 'Class']; + const rows = passengerList.map(p => [ + p.bookingRef, p.bookingStatus, p.passengerName, p.passengerCategory, + p.idDocumentType ?? '', p.idDocumentNumber ?? '', p.passportNumber ?? '', + p.passportCountry ?? '', p.seatLabel ?? '', p.coachNumber ?? '', p.coachType ?? '', + ].map(v => `"${String(v).replace(/"/g, '""')}"`)); + downloadCsv([headers.join(','), ...rows.map(r => r.join(','))].join('\n'), `passengers-${scheduleId}.csv`); + }; + return (
@@ -54,30 +98,32 @@ export default function PassengersReportPage() {

Occupancy and passenger breakdown for a schedule

- {/* Schedule ID input */} + {/* Schedule selector */}
-
- - + +
- setSubmittedId(scheduleId)} disabled={!scheduleId.trim() || isLoading}> - Load Report - - {data && ( - - Export CSV - + {data && tab === 'occupancy' && ( + Export CSV + )} + {passengerList.length > 0 && tab === 'list' && ( + Export CSV )}
- {isLoading &&

Loading…

} - {isError &&

Failed to load report. Check the schedule ID.

} + {(isLoading || listLoading) &&

Loading…

} + {isError &&

Failed to load report.

}
{data && ( @@ -92,121 +138,194 @@ export default function PassengersReportPage() {
- {/* Summary cards */} -
-
-
-

Total Seats

-
-
-

{data.summary.totalSeats}

-
-
-
-

Passengers

-
-
-

{data.summary.totalPassengers}

-
-
-
-

Occupancy Rate

-
-
-

{data.summary.occupancyRate}%

-
-
-
-
+ {/* Tabs */} +
+ +
- {/* By Coach */} -
-

By Coach

-
- - - - - - - - - - - - {data.byCoach.map((c) => ( - - - - - - - - ))} - -
CoachTypeSeatsBookedOccupancy
{c.coachNumber}{c.coachType}{c.totalSeats}{c.booked} + {/* Occupancy tab */} + {tab === 'occupancy' && ( +
+
+
+
+

Total Seats

+
+
+

{data.summary.totalSeats}

+
+
+
+

Passengers

+
+
+

{data.summary.totalPassengers}

+
+
+
+

Occupancy Rate

+
+
+

{data.summary.occupancyRate}%

+
+
+
+
+
+ +
+

By Coach

+
+ + + + + + + + + + + + {data.byCoach.map(c => ( + + + + + + + + ))} + +
CoachTypeSeatsBookedOccupancy
{c.coachNumber}{c.coachType}{c.totalSeats}{c.booked} +
+
+
+
+ {c.occupancyRate}% +
+
+
+
+ +
+
+

By Class

+
+ {data.byClass.map(c => ( +
+
+ {c.className} + {c.booked}/{c.totalSeats} +
-
+
- {c.occupancyRate}% + {c.occupancyRate}%
-
-
-
- - {/* By Class + By Origin/Destination */} -
- {/* By Class */} -
-

By Class

-
- {data.byClass.map((c) => ( -
-
- {c.className} - {c.booked}/{c.totalSeats} -
-
-
-
- {c.occupancyRate}% -
+ ))}
- ))} +
+
+

By Boarding Station

+
+ {data.byOrigin.map(o => ( +
+ {o.stationName} + {o.passengers} +
+ ))} + {data.byOrigin.length === 0 &&

No data

} +
+
+
+

By Alighting Station

+
+ {data.byDestination.map(d => ( +
+ {d.stationName} + {d.passengers} +
+ ))} + {data.byDestination.length === 0 &&

No data

} +
+
+ )} - {/* By Origin */} -
-

By Boarding Station

-
- {data.byOrigin.map((o) => ( -
- {o.stationName} - {o.passengers} -
- ))} - {data.byOrigin.length === 0 &&

No data

} + {/* Passenger List tab */} + {tab === 'list' && ( +
+ setListSearch(e.target.value)} + /> +
+ + + + + + + + + + + + + + + {filteredList.map((p, i) => ( + + + + + + + + + + + ))} + {filteredList.length === 0 && ( + + )} + +
#NameCategoryID / PassportSeatCoachBooking RefStatus
{i + 1}{p.passengerName} + + {p.passengerCategory} + + + {p.idDocumentNumber ?? p.passportNumber ?? '—'} + {p.passportCountry && ({p.passportCountry})} + {p.seatLabel ?? '—'} + {p.coachNumber ?? '—'} + {p.coachType && ({p.coachType})} + {p.bookingRef} + + {p.bookingStatus} + +
No passengers found
- - {/* By Destination */} -
-

By Alighting Station

-
- {data.byDestination.map((d) => ( -
- {d.stationName} - {d.passengers} -
- ))} - {data.byDestination.length === 0 &&

No data

} -
-
-
+ )} )}