From 1e97f46813f60d9213d3a2794268268161c11aaf Mon Sep 17 00:00:00 2001 From: Abubeker Yasin Date: Thu, 13 Aug 2026 12:20:27 +0300 Subject: [PATCH 01/14] fix: ( notifications ) stop group-booking SMS greeting the wrong passenger --- .../common/utils/booking-sms.utils.spec.ts | 153 ++++++++++++++++++ .../src/common/utils/booking-sms.utils.ts | 115 +++++++++++++ .../notifications/notifications.service.ts | 24 +-- 3 files changed, 275 insertions(+), 17 deletions(-) create mode 100644 apps/edr-passenger-api/src/common/utils/booking-sms.utils.spec.ts create mode 100644 apps/edr-passenger-api/src/common/utils/booking-sms.utils.ts diff --git a/apps/edr-passenger-api/src/common/utils/booking-sms.utils.spec.ts b/apps/edr-passenger-api/src/common/utils/booking-sms.utils.spec.ts new file mode 100644 index 000000000..93fa94b50 --- /dev/null +++ b/apps/edr-passenger-api/src/common/utils/booking-sms.utils.spec.ts @@ -0,0 +1,153 @@ +import { buildSeatSummary } from './booking-sms.utils'; + +const seat = (passengerName: string, seatNumber: string, leg = 1, coachType = 'VIP Bed') => ({ + passengerName, + leg, + seat: { seatNumber, coach: { number: 'VIP-0001 (DJ)', coachType: { name: coachType } } }, +}); + +describe('buildSeatSummary', () => { + it('greets a solo traveller by name and omits the name from the seat line', () => { + const { passengerName, trainSeatLines } = buildSeatSummary([seat('Yanet', '9')], 'ONE_WAY'); + + expect(passengerName).toBe('Yanet'); + expect(trainSeatLines).toBe('VIP-0001 (DJ) VIP Bed, seat no. 9'); + expect(trainSeatLines).not.toContain('Train/Seat'); + expect(trainSeatLines).not.toContain('Yanet'); + }); + + it('greets a group collectively and names each seat', () => { + const { passengerName, trainSeatLines } = buildSeatSummary( + [seat('Yanet', '4'), seat('Abebe', '6'), seat('Sara', '9'), seat('Helen', '10')], + 'ONE_WAY', + ); + + expect(passengerName).toBe('Passengers'); + expect(trainSeatLines).toBe( + [ + 'Yanet, VIP-0001 (DJ) VIP Bed, seat no. 4', + 'Abebe, VIP-0001 (DJ) VIP Bed, seat no. 6', + 'Sara, VIP-0001 (DJ) VIP Bed, seat no. 9', + 'Helen, VIP-0001 (DJ) VIP Bed, seat no. 10', + ].join('\n'), + ); + }); + + // The reported bug: the seats query had no orderBy, so Postgres heap order put the LAST + // passenger first and the SMS greeted them while texting the first passenger's phone. + it('is immune to seat rows arriving in an arbitrary order', () => { + const rows = [seat('Yanet', '9'), seat('Helen', '10'), seat('Abebe', '6'), seat('Sara', '4')]; + + const { passengerName, trainSeatLines } = buildSeatSummary(rows, 'ONE_WAY'); + + expect(passengerName).toBe('Passengers'); + // Every line pairs the right person with their own seat, regardless of input order. + expect(trainSeatLines).toBe( + [ + 'Sara, VIP-0001 (DJ) VIP Bed, seat no. 4', + 'Abebe, VIP-0001 (DJ) VIP Bed, seat no. 6', + 'Yanet, VIP-0001 (DJ) VIP Bed, seat no. 9', + 'Helen, VIP-0001 (DJ) VIP Bed, seat no. 10', + ].join('\n'), + ); + }); + + it('sorts seat numbers numerically, not lexicographically', () => { + const { trainSeatLines } = buildSeatSummary( + [seat('A', '9'), seat('B', '10'), seat('C', '6'), seat('D', '4')], + 'ONE_WAY', + ); + + expect(trainSeatLines.match(/seat no\. \d+/g)).toEqual([ + 'seat no. 4', + 'seat no. 6', + 'seat no. 9', + 'seat no. 10', + ]); + }); + + it('labels round-trip legs as Outbound/Return, listing each passenger once per leg', () => { + const { passengerName, trainSeatLines } = buildSeatSummary( + [seat('Yanet', '9', 1), seat('Abebe', '10', 1), seat('Yanet', '3', 2), seat('Abebe', '4', 2)], + 'ROUND_TRIP', + ); + + expect(passengerName).toBe('Passengers'); + expect(trainSeatLines).toBe( + [ + 'Outbound:', + 'Yanet, VIP-0001 (DJ) VIP Bed, seat no. 9', + 'Abebe, VIP-0001 (DJ) VIP Bed, seat no. 10', + 'Return:', + 'Yanet, VIP-0001 (DJ) VIP Bed, seat no. 3', + 'Abebe, VIP-0001 (DJ) VIP Bed, seat no. 4', + ].join('\n'), + ); + }); + + // TRANSIT leg 2 is a connecting segment of the same outbound journey — never a return. + it('labels transit legs as Leg 1/Leg 2, never Return', () => { + const { trainSeatLines } = buildSeatSummary( + [seat('Yanet', '9', 1), seat('Abebe', '10', 1), seat('Yanet', '3', 2), seat('Abebe', '4', 2)], + 'TRANSIT', + ); + + expect(trainSeatLines).toContain('Leg 1:'); + expect(trainSeatLines).toContain('Leg 2:'); + expect(trainSeatLines).not.toContain('Return'); + expect(trainSeatLines).not.toContain('Outbound'); + }); + + it('labels all four round-trip-transit legs', () => { + const { trainSeatLines } = buildSeatSummary( + [1, 2, 3, 4].map((leg) => seat('Yanet', String(leg), leg)), + 'ROUND_TRIP_TRANSIT', + ); + + expect(trainSeatLines).toBe( + [ + 'Outbound leg 1:', + 'VIP-0001 (DJ) VIP Bed, seat no. 1', + 'Outbound leg 2:', + 'VIP-0001 (DJ) VIP Bed, seat no. 2', + 'Return leg 1:', + 'VIP-0001 (DJ) VIP Bed, seat no. 3', + 'Return leg 2:', + 'VIP-0001 (DJ) VIP Bed, seat no. 4', + ].join('\n'), + ); + }); + + it('greets a solo round-trip traveller by name (same person on both legs)', () => { + const { passengerName } = buildSeatSummary( + [seat('Yanet', '9', 1), seat('Yanet', '3', 2)], + 'ROUND_TRIP', + ); + + expect(passengerName).toBe('Yanet'); + }); + + it('trims a trailing space on the coach type instead of emitting "Bed , seat"', () => { + const { trainSeatLines } = buildSeatSummary([seat('Yanet', '9', 1, 'VIP Bed ')], 'ONE_WAY'); + + expect(trainSeatLines).toBe('VIP-0001 (DJ) VIP Bed, seat no. 9'); + }); + + it('falls back safely on empty or malformed input', () => { + expect(buildSeatSummary([], 'ONE_WAY')).toEqual({ passengerName: 'Passenger', trainSeatLines: '' }); + + const { passengerName, trainSeatLines } = buildSeatSummary([{ leg: 1 }], 'ONE_WAY'); + expect(passengerName).toBe('Passenger'); + expect(trainSeatLines).toBe('-, seat no. -'); + }); + + it('falls back to a generic leg heading for an unknown booking type', () => { + const { trainSeatLines } = buildSeatSummary( + [seat('Yanet', '9', 1), seat('Yanet', '3', 2)], + 'SOMETHING_NEW', + ); + + expect(trainSeatLines).toContain('Leg 1:'); + expect(trainSeatLines).toContain('Leg 2:'); + }); +}); diff --git a/apps/edr-passenger-api/src/common/utils/booking-sms.utils.ts b/apps/edr-passenger-api/src/common/utils/booking-sms.utils.ts new file mode 100644 index 000000000..18b1db9ac --- /dev/null +++ b/apps/edr-passenger-api/src/common/utils/booking-sms.utils.ts @@ -0,0 +1,115 @@ +/** + * Builds the two passenger-facing values the `booking.created` SMS/email template needs: + * the `{{passengerName}}` salutation and the `{{trainSeatLines}}` block. + * + * Why this is a shared pure helper rather than inline logic: the salutation used to be + * `seats[0]?.passengerName`, and the query loading those seats had no `orderBy`. Postgres + * returns heap order for an unordered SELECT, and an UPDATE relocates a row to the end of + * the heap — so a group booking regularly greeted the LAST passenger while texting the + * first one's phone. Deriving both values from the whole seat set, sorted deterministically, + * removes the dependency on row order entirely, and keeps the formatting unit-testable + * without a Nest testing module. + * + * Group bookings send ONE SMS to Booking.contactPhone by design — BookingSeat has no + * phone/email column, so there is no per-passenger recipient. Hence 2+ passengers are + * greeted collectively and each seat line names its own occupant. + */ + +export interface SeatSummary { + /** Salutation: the traveller's name when solo, otherwise 'Passengers'. */ + passengerName: string; + /** One line per booked seat, newline-joined, with a heading per leg on multi-leg bookings. */ + trainSeatLines: string; +} + +/** + * Seat numbers are stored as strings of digits (Seat.seatNumber), so they must be compared + * numerically — a plain string compare orders '10' before '9'. Non-numeric labels sort last, + * then alphabetically among themselves. + */ +function compareSeatNumber(a: string, b: string): number { + const na = Number.parseInt(a, 10); + const nb = Number.parseInt(b, 10); + const aNum = Number.isNaN(na); + const bNum = Number.isNaN(nb); + if (aNum && bNum) return a.localeCompare(b); + if (aNum) return 1; + if (bNum) return -1; + return na - nb || a.localeCompare(b); +} + +const str = (v: unknown): string => (typeof v === 'string' ? v.trim() : v == null ? '' : String(v).trim()); + +const ROUND_TRIP_TRANSIT_LEGS: Record = { + 1: 'Outbound leg 1', + 2: 'Outbound leg 2', + 3: 'Return leg 1', + 4: 'Return leg 2', +}; + +/** + * Leg numbering means different things per booking type — see the enum documented on + * TicketsController.validate. TRANSIT's leg 2 is a connecting segment of the SAME outbound + * journey, so it must never be labelled 'Return'. + */ +function legLabel(bookingType: string | undefined, leg: number): string { + switch (bookingType) { + case 'ROUND_TRIP': + return leg === 1 ? 'Outbound' : leg === 2 ? 'Return' : `Leg ${leg}`; + case 'TRANSIT': + return `Leg ${leg}`; + case 'ROUND_TRIP_TRANSIT': + return ROUND_TRIP_TRANSIT_LEGS[leg] ?? `Leg ${leg}`; + default: + // Unknown or newly added booking type — degrade to a generic heading rather than guessing. + return `Leg ${leg}`; + } +} + +export function buildSeatSummary(seats: any[], bookingType?: string): SeatSummary { + const rows = [...(seats ?? [])].sort( + (a, b) => + (a?.leg ?? 1) - (b?.leg ?? 1) || + str(a?.seat?.coach?.number).localeCompare(str(b?.seat?.coach?.number)) || + compareSeatNumber(str(a?.seat?.seatNumber), str(b?.seat?.seatNumber)), + ); + + // Distinct travellers. A round-trip/transit booking has one row per passenger PER LEG, so + // the same name legitimately repeats — count people, not rows. + const names: string[] = []; + for (const row of rows) { + const name = str(row?.passengerName); + if (name && !names.includes(name)) names.push(name); + } + const isGroup = names.length > 1; + + const line = (row: any): string => { + const coach = str(row?.seat?.coach?.number) || '-'; + const coachType = str(row?.seat?.coach?.coachType?.name); + const seatNo = str(row?.seat?.seatNumber) || '-'; + // Trim each part before joining: the coach-type name carries a trailing space in some + // records, which a `.replace(/ +/g, ' ')` collapse cannot remove (it shrinks runs of + // spaces but leaves a single one), and it surfaced as 'VIP Bed , seat no. 9'. + const where = [coach, coachType].filter(Boolean).join(' '); + const who = isGroup ? `${str(row?.passengerName) || 'Passenger'}, ` : ''; + return `${who}${where}, seat no. ${seatNo}`; + }; + + const legs = [...new Set(rows.map((row) => row?.leg ?? 1))]; + const trainSeatLines = + legs.length > 1 + ? legs + .map((leg) => + [ + `${legLabel(bookingType, leg)}:`, + ...rows.filter((row) => (row?.leg ?? 1) === leg).map(line), + ].join('\n'), + ) + .join('\n') + : rows.map(line).join('\n'); + + return { + passengerName: isGroup ? 'Passengers' : (names[0] || 'Passenger'), + trainSeatLines, + }; +} diff --git a/apps/edr-passenger-api/src/modules/notifications/notifications.service.ts b/apps/edr-passenger-api/src/modules/notifications/notifications.service.ts index 9ef922bb3..3b7e7be2f 100644 --- a/apps/edr-passenger-api/src/modules/notifications/notifications.service.ts +++ b/apps/edr-passenger-api/src/modules/notifications/notifications.service.ts @@ -8,6 +8,7 @@ import { EmailClientService } from './email-client.service'; import { SmsClientService } from './sms-client.service'; import { CreateTemplateDto, UpdateTemplateDto } from './notifications.dto'; import { resolveBookingSegment } from '../../common/utils/segment-resolver.utils'; +import { buildSeatSummary } from '../../common/utils/booking-sms.utils'; export type NotificationChannelType = 'EMAIL' | 'SMS' | 'PUSH' | 'IN_APP'; @@ -305,7 +306,7 @@ export class NotificationsService { where: { id: bookingId }, include: { schedule: { include: { originStation: true, destinationStation: true, train: true, stopTimes: { include: { station: true } } } }, - seats: { include: { seat: { include: { coach: { include: { coachType: true } } } } } }, + seats: { include: { seat: { include: { coach: { include: { coachType: true } } } } }, orderBy: { leg: 'asc' } }, }, }); @@ -367,30 +368,19 @@ export class NotificationsService { } /** - * Builds the interpolation context for the `booking.created` template. `trainSeatLines` is a - * pre-joined block of one "Train/Seat: …" line per booked seat (multi-passenger bookings get - * several lines). + * Builds the interpolation context for the `booking.created` template. `passengerName` and + * `trainSeatLines` both come from buildSeatSummary — a solo booking is greeted by name with + * bare "coach, seat no." lines, while a group is greeted as "Passengers" and each line names + * its own occupant (one SMS goes to Booking.contactPhone for the whole party). */ private buildBookingCreatedContext(booking: any, ref: string): Record { const s = booking?.schedule ?? {}; - const trainName = s.train?.name ?? s.train?.number ?? ''; const fmtDate = (d: any) => d ? new Date(d).toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' }) : 'TBD'; const fmtTime = (d: any) => d ? new Date(d).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true }) : 'TBD'; - const seats = booking?.seats ?? []; - const trainSeatLines = seats - .map((bs: any) => { - const coach = bs.seat?.coach?.number ?? '-'; - const cls = bs.seat?.coach?.coachType?.name ?? ''; - const seatNo = bs.seat?.seatNumber ?? '-'; - return `Train/Seat: Train ${trainName}, ${coach} ${cls}, seat no. ${seatNo}`.replace(/ +/g, ' ').trim(); - }) - .join('\n'); - - // Lead passenger (leg-1 seat). Booking has no contactName; the traveller name lives on the seat. - const passengerName = seats[0]?.passengerName ?? 'Passenger'; + const { passengerName, trainSeatLines } = buildSeatSummary(booking?.seats ?? [], booking?.bookingType); const payLink = `${process.env.PORTAL_URL ?? 'http://localhost:5174'}/booking/detail?ref=${ref}`; const segment = resolveBookingSegment(s, booking?.originStationId, booking?.destinationStationId); From aabf58320ac7ad02a95be2735d15f93d6ed15ca9 Mon Sep 17 00:00:00 2001 From: Abubeker Yasin Date: Thu, 13 Aug 2026 15:32:56 +0300 Subject: [PATCH 02/14] feat: ( reports ) add fleet seat overview to seat status landing page --- .../src/modules/reports/reports.controller.ts | 17 + .../src/modules/reports/reports.service.ts | 381 ++++++++++++++ .../backoffice/src/app/reports/seats/page.tsx | 12 +- .../components/reports/FleetSeatOverview.tsx | 469 ++++++++++++++++++ 4 files changed, 872 insertions(+), 7 deletions(-) create mode 100644 apps/edr-passenger-web/backoffice/src/components/reports/FleetSeatOverview.tsx 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 1eea923fd..adf6ccb9e 100644 --- a/apps/edr-passenger-api/src/modules/reports/reports.controller.ts +++ b/apps/edr-passenger-api/src/modules/reports/reports.controller.ts @@ -60,6 +60,23 @@ export class ReportsController { return this.service.getSeatStatusReport(scheduleId); } + // Two segments, so `@Get(":reportId")` below cannot shadow it whatever the order. + @Get("seat-status/overview") + @ApiOperation({ + summary: "Fleet-wide seat status across a departure window", + description: + "Landing view for the seat status report, shown before a schedule is picked. Returns the same four " + + "counters as the per-schedule report (paid, unpaid, expired holds, blocked) rolled up over a window of " + + "departures, plus per-day buckets and one row per schedule.\n\n" + + "The window is forward-looking — the next `days` days. If nothing is departing in that window, it falls " + + "back to the most recent `days` of departures on record and says so via `window.direction`.\n\n" + + "Counts apply the same rules as `GET /reports/seat-status`, so a schedule's row here equals what the " + + "drill-down shows after selecting it.", + }) + getSeatStatusOverview(@Query('days') days?: string) { + return this.service.getSeatStatusOverview(days ? Number(days) : undefined); + } + @Get("boarding") @ApiOperation({ summary: "Boarding report for a schedule — boarded vs not-boarded passengers" }) getBoardingReport(@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 e899fdb4b..7a4fde4cb 100644 --- a/apps/edr-passenger-api/src/modules/reports/reports.service.ts +++ b/apps/edr-passenger-api/src/modules/reports/reports.service.ts @@ -1,6 +1,7 @@ import { Injectable, Logger } from "@nestjs/common"; import { InjectDataSource } from "@nestjs/typeorm"; import { DataSource } from "typeorm"; +import { BookingStatus } from "@prisma/client"; import { BlockedSeatRevenueLossReport, UNCATEGORIZED_REASON_CATEGORY, @@ -35,6 +36,43 @@ const FARE_QUOTE_CONCURRENCY = 4; /** CSV export is not paginated, but still needs an upper bound. */ const CSV_EXPORT_MAX_SCHEDULES = 5000; +// ── Fleet seat-status overview (landing view of the seat status report) ────── +const MS_PER_DAY_OVERVIEW = 24 * 60 * 60 * 1000; +const OVERVIEW_DEFAULT_DAYS = 7; +const OVERVIEW_MAX_DAYS = 31; +/** Upper bound on schedules charted at once. Signalled back as `window.truncated`. */ +const OVERVIEW_MAX_SCHEDULES = 60; +/** The booking statuses that put a seat on a schedule — same set as the drill-down. */ +const OVERVIEW_ACTIVE_BOOKING_STATUSES: BookingStatus[] = [ + 'CONFIRMED', + 'BOARDED', + 'PENDING_PAYMENT', +]; + +const EMPTY_OVERVIEW_TOTALS = { + scheduleCount: 0, + sellableSeats: 0, + paidCount: 0, + unpaidCount: 0, + expiredHoldCount: 0, + blockedCount: 0, + availableCount: 0, + loadFactorPercent: 0, +}; + +function emptyDayBucket(date: string) { + return { + date, + scheduleCount: 0, + sellableSeats: 0, + paid: 0, + unpaid: 0, + expiredHolds: 0, + blocked: 0, + available: 0, + }; +} + const EMPTY_LOSS_INPUT: LossCalculatorInput = { schedules: [], seatsById: new Map(), @@ -728,6 +766,349 @@ export class ReportsService { }; } + /** + * Fleet-wide seat status across a departure window — the landing view for the seat + * status report, shown before a schedule is picked. + * + * Deliberately a separate method from {@link getSeatStatusReport}: that one answers + * "this schedule, row by row" and its response shape is consumed by the drill-down UI. + * This one answers "the whole window, counts only". They share no code path, but they + * *do* share predicates — every filter below is the same rule the drill-down applies + * (the three-branch seat `OR`, the dining-coach exclusion, the counted-block + * resolution), so a schedule's row here always equals what you see after clicking it. + * Change one and the other must change with it. + */ + async getSeatStatusOverview(daysRaw?: number) { + const days = Math.min( + Math.max(Math.trunc(daysRaw || OVERVIEW_DEFAULT_DAYS), 1), + OVERVIEW_MAX_DAYS, + ); + const now = new Date(); + + // Forward-looking by default. But a database whose schedules are all in the past + // would render an empty chart, which reads as a broken page rather than an honest + // "nothing departing" — so fall back to the most recent window that has departures. + let from = now; + let to = new Date(now.getTime() + days * MS_PER_DAY_OVERVIEW); + let direction: 'UPCOMING' | 'RECENT' = 'UPCOMING'; + + const upcomingCount = await this.prisma.trainSchedule.count({ + where: { departureAt: { gte: from, lte: to }, status: { not: 'CANCELLED' } }, + }); + + if (upcomingCount === 0) { + const latest = await this.prisma.trainSchedule.findFirst({ + where: { departureAt: { lt: now }, status: { not: 'CANCELLED' } }, + orderBy: { departureAt: 'desc' }, + select: { departureAt: true }, + }); + if (latest) { + direction = 'RECENT'; + to = latest.departureAt; + from = new Date(to.getTime() - days * MS_PER_DAY_OVERVIEW); + } + } + + const schedules = await this.prisma.trainSchedule.findMany({ + where: { departureAt: { gte: from, lte: to }, status: { not: 'CANCELLED' } }, + select: { + id: true, + departureAt: true, + isPackageOnly: true, + train: { select: { number: true } }, + originStation: { select: { name: true } }, + destinationStation: { select: { name: true } }, + }, + orderBy: { departureAt: 'asc' }, + take: OVERVIEW_MAX_SCHEDULES, + }); + + if (schedules.length === 0) { + return { + window: { from, to, days, direction, truncated: false }, + totals: EMPTY_OVERVIEW_TOTALS, + byDay: [], + schedules: [], + }; + } + + const scheduleIds = schedules.map((s) => s.id); + const since24h = new Date(now.getTime() - MS_PER_DAY_OVERVIEW); + + const [assignments, bookingSeats, holds, blockRows] = await Promise.all([ + this.prisma.coachAssignment.findMany({ + where: { scheduleId: { in: scheduleIds } }, + select: { + scheduleId: true, + coachId: true, + coach: { + select: { + coachType: { select: { name: true, type: true } }, + seats: { select: { seatNumber: true } }, + }, + }, + }, + }), + // Same three-branch OR as the drill-down (`getSeatStatusReport`): a seat reaches a + // schedule by its own `scheduleId`, by being leg 2 of a return booking, or — on + // older rows with no `scheduleId` — by its booking's outbound schedule. A plain + // `groupBy scheduleId` would silently drop the last two. + this.prisma.bookingSeat.findMany({ + where: { + OR: [ + { + scheduleId: { in: scheduleIds }, + booking: { status: { in: OVERVIEW_ACTIVE_BOOKING_STATUSES } }, + }, + { + leg: 2, + booking: { + returnScheduleId: { in: scheduleIds }, + status: { in: OVERVIEW_ACTIVE_BOOKING_STATUSES }, + }, + }, + { + scheduleId: null, + leg: 1, + booking: { + scheduleId: { in: scheduleIds }, + status: { in: OVERVIEW_ACTIVE_BOOKING_STATUSES }, + }, + }, + ], + }, + select: { + scheduleId: true, + leg: true, + booking: { + select: { status: true, scheduleId: true, returnScheduleId: true }, + }, + seat: { + select: { + coach: { select: { coachType: { select: { name: true, type: true } } } }, + }, + }, + }, + }), + this.prisma.seatHold.findMany({ + where: { + scheduleId: { in: scheduleIds }, + expiresAt: { lt: now, gte: since24h }, + }, + select: { scheduleId: true }, + }), + this.prisma.seatBlock.findMany({ + where: { + OR: [{ scheduleId: { in: scheduleIds } }, { scheduleId: null }], + NOT: [ + { reason: { startsWith: 'MAINTENANCE:' } }, + { reason: { startsWith: TICKETING_BLOCK_REASON_PREFIX } }, + ], + }, + select: { + scheduleId: true, + blockedAt: true, + unblockAt: true, + seat: { + select: { + id: true, + coachId: true, + seatNumber: true, + coach: { select: { coachType: { select: { name: true, type: true } } } }, + }, + }, + }, + orderBy: { blockedAt: 'desc' }, + }), + ]); + + // ── Sellable seats and assigned coaches, per schedule ─────────────────────── + // Sellable = every seat on every assigned coach, minus dining coaches and + // placeholder rows — the same denominator the revenue-loss report uses. + const sellableBySchedule = new Map(); + const coachIdsBySchedule = new Map>(); + for (const assignment of assignments) { + const coachIds = + coachIdsBySchedule.get(assignment.scheduleId) ?? new Set(); + coachIds.add(assignment.coachId); + coachIdsBySchedule.set(assignment.scheduleId, coachIds); + + const coachType = assignment.coach?.coachType; + if ( + isDiningCoach({ + coachTypeType: coachType?.type ?? null, + coachTypeName: coachType?.name ?? null, + }) + ) { + continue; + } + const sellable = (assignment.coach?.seats ?? []).filter( + (seat) => !isPlaceholderSeat(seat), + ).length; + sellableBySchedule.set( + assignment.scheduleId, + (sellableBySchedule.get(assignment.scheduleId) ?? 0) + sellable, + ); + } + + // ── Paid / unpaid, per schedule ──────────────────────────────────────────── + const scheduleIdSet = new Set(scheduleIds); + const paidBySchedule = new Map(); + const unpaidBySchedule = new Map(); + for (const bs of bookingSeats) { + // Dining seats only — the drill-down does not drop placeholder rows from the + // passenger seat list, so neither does this. + const coachType = bs.seat?.coach?.coachType; + if ( + isDiningCoach({ + coachTypeType: coachType?.type ?? null, + coachTypeName: coachType?.name ?? null, + }) + ) { + continue; + } + + // Mirrors the OR branches, in the same order: an explicit `scheduleId` inside the + // window wins, then the return leg, then the booking's outbound schedule. + const scheduleId = + bs.scheduleId && scheduleIdSet.has(bs.scheduleId) + ? bs.scheduleId + : bs.leg === 2 + ? bs.booking.returnScheduleId + : bs.booking.scheduleId; + if (!scheduleId || !scheduleIdSet.has(scheduleId)) continue; + + const target = + bs.booking.status === 'PENDING_PAYMENT' ? unpaidBySchedule : paidBySchedule; + target.set(scheduleId, (target.get(scheduleId) ?? 0) + 1); + } + + // ── Expired holds, per schedule ──────────────────────────────────────────── + const holdsBySchedule = new Map(); + for (const hold of holds) { + holdsBySchedule.set( + hold.scheduleId, + (holdsBySchedule.get(hold.scheduleId) ?? 0) + 1, + ); + } + + // ── Blocked seats, per schedule ──────────────────────────────────────────── + // One counted block per seat, resolved exactly as the drill-down resolves it: a + // schedule-scoped block beats a global one, and rows arrive newest-first so the + // first of a kind seen for a seat is already the most recent. + const blockedBySchedule = new Map(); + for (const schedule of schedules) { + const assignedCoachIds = coachIdsBySchedule.get(schedule.id) ?? new Set(); + const countedSeatIds = new Map(); + + for (const block of blockRows) { + const seat = block.seat; + if (!seat || isPlaceholderSeat(seat)) continue; + + const coachType = seat.coach?.coachType; + if ( + isDiningCoach({ + coachTypeType: coachType?.type ?? null, + coachTypeName: coachType?.name ?? null, + }) + ) { + continue; + } + + if (block.scheduleId !== null) { + if (block.scheduleId !== schedule.id) continue; + } else { + if (!assignedCoachIds.has(seat.coachId)) continue; + if (!isGlobalBlockInEffectAt(block, schedule.departureAt)) continue; + } + + const existing = countedSeatIds.get(seat.id); + if (existing === undefined || (existing === null && block.scheduleId !== null)) { + countedSeatIds.set(seat.id, block.scheduleId); + } + } + + if (countedSeatIds.size > 0) { + blockedBySchedule.set(schedule.id, countedSeatIds.size); + } + } + + // ── Assemble ─────────────────────────────────────────────────────────────── + const scheduleRows = schedules.map((s) => { + const sellableSeats = sellableBySchedule.get(s.id) ?? 0; + const paid = paidBySchedule.get(s.id) ?? 0; + const unpaid = unpaidBySchedule.get(s.id) ?? 0; + const expiredHolds = holdsBySchedule.get(s.id) ?? 0; + const blocked = blockedBySchedule.get(s.id) ?? 0; + // Floored at zero: a seat can be both sold and blocked, so the parts can + // over-subtract. Never render a negative slice. + const available = Math.max(0, sellableSeats - paid - unpaid - blocked); + + return { + scheduleId: s.id, + trainNumber: s.train.number, + originStation: s.originStation.name, + destinationStation: s.destinationStation.name, + departureAt: s.departureAt, + isPackage: s.isPackageOnly, + sellableSeats, + paid, + unpaid, + expiredHolds, + blocked, + available, + loadFactorPercent: + sellableSeats > 0 ? +((paid / sellableSeats) * 100).toFixed(1) : 0, + }; + }); + + // Day buckets keyed on the UTC calendar date of departure, so the chart's axis and + // its bars are derived from one value and cannot disagree with each other. + const byDayMap = new Map>(); + for (const row of scheduleRows) { + const date = row.departureAt.toISOString().slice(0, 10); + const bucket = byDayMap.get(date) ?? emptyDayBucket(date); + bucket.scheduleCount += 1; + bucket.sellableSeats += row.sellableSeats; + bucket.paid += row.paid; + bucket.unpaid += row.unpaid; + bucket.expiredHolds += row.expiredHolds; + bucket.blocked += row.blocked; + bucket.available += row.available; + byDayMap.set(date, bucket); + } + const byDay = [...byDayMap.values()].sort((a, b) => a.date.localeCompare(b.date)); + + const sum = (pick: (r: (typeof scheduleRows)[number]) => number) => + scheduleRows.reduce((total, row) => total + pick(row), 0); + + const totalSellable = sum((r) => r.sellableSeats); + const totalPaid = sum((r) => r.paid); + + return { + window: { + from, + to, + days, + direction, + truncated: schedules.length === OVERVIEW_MAX_SCHEDULES, + }, + totals: { + scheduleCount: scheduleRows.length, + sellableSeats: totalSellable, + paidCount: totalPaid, + unpaidCount: sum((r) => r.unpaid), + expiredHoldCount: sum((r) => r.expiredHolds), + blockedCount: sum((r) => r.blocked), + availableCount: sum((r) => r.available), + loadFactorPercent: + totalSellable > 0 ? +((totalPaid / totalSellable) * 100).toFixed(1) : 0, + }, + byDay, + schedules: scheduleRows, + }; + } + async getPaymentDiscrepancyReport(params: { from?: string; to?: string; diff --git a/apps/edr-passenger-web/backoffice/src/app/reports/seats/page.tsx b/apps/edr-passenger-web/backoffice/src/app/reports/seats/page.tsx index 2f5611f80..ef36ef741 100644 --- a/apps/edr-passenger-web/backoffice/src/app/reports/seats/page.tsx +++ b/apps/edr-passenger-web/backoffice/src/app/reports/seats/page.tsx @@ -2,8 +2,9 @@ import { useState } from "react"; import { useQuery } from "@tanstack/react-query"; -import { CheckCircle, Clock, AlertCircle, Ban, Armchair, Download } from "lucide-react"; +import { CheckCircle, Clock, AlertCircle, Ban, Download } from "lucide-react"; import { apiClient } from "@/lib/api-client"; +import FleetSeatOverview from "@/components/reports/FleetSeatOverview"; import Badge from "@/components/ui/Badge"; import ActionButton from "@/components/ui/ActionButton"; import { formatDateTime, formatCurrency } from "@/lib/utils"; @@ -165,12 +166,9 @@ export default function SeatStatusReportPage() { {isError &&

Failed to load report.

} - {!scheduleId && ( -
- -

Select a schedule above to load the seat status report

-
- )} + {/* Landing state only. Unmounts the moment a schedule is selected, leaving the + per-schedule report below untouched. */} + {!scheduleId && } {data && ( <> diff --git a/apps/edr-passenger-web/backoffice/src/components/reports/FleetSeatOverview.tsx b/apps/edr-passenger-web/backoffice/src/components/reports/FleetSeatOverview.tsx new file mode 100644 index 000000000..2febaa00b --- /dev/null +++ b/apps/edr-passenger-web/backoffice/src/components/reports/FleetSeatOverview.tsx @@ -0,0 +1,469 @@ +"use client"; + +/** + * Fleet seat overview — the landing state of the Seat Status Report, shown only while + * no schedule is selected. Once a schedule is picked this component unmounts and the + * per-schedule drill-down takes over unchanged. + * + * Its numbers come from `/reports/seat-status/overview`, which applies the same counting + * rules as `/reports/seat-status`, so a schedule's row here equals what the drill-down + * shows after clicking it. + */ + +import { useMemo } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { + Bar, + BarChart, + CartesianGrid, + Cell, + ResponsiveContainer, + Tooltip, + XAxis, + YAxis, +} from "recharts"; +import { Armchair, CalendarClock, TrendingUp } from "lucide-react"; +import { apiClient } from "@/lib/api-client"; +import { categoricalColor, getChartPalette } from "@/lib/chart-palette"; +import { useTheme } from "@/lib/theme-store"; + +interface OverviewScheduleRow { + scheduleId: string; + trainNumber: string; + originStation: string; + destinationStation: string; + departureAt: string; + isPackage: boolean; + sellableSeats: number; + paid: number; + unpaid: number; + expiredHolds: number; + blocked: number; + available: number; + loadFactorPercent: number; +} + +interface OverviewDayBucket { + date: string; + scheduleCount: number; + sellableSeats: number; + paid: number; + unpaid: number; + expiredHolds: number; + blocked: number; + available: number; +} + +interface SeatStatusOverview { + window: { + from: string; + to: string; + days: number; + direction: "UPCOMING" | "RECENT"; + truncated: boolean; + }; + totals: { + scheduleCount: number; + sellableSeats: number; + paidCount: number; + unpaidCount: number; + expiredHoldCount: number; + blockedCount: number; + availableCount: number; + loadFactorPercent: number; + }; + byDay: OverviewDayBucket[]; + schedules: OverviewScheduleRow[]; +} + +/** + * Fixed domain order for the inventory series, matching the left-to-right order of the + * drill-down's summary cards. Colour is keyed by position here and never by rank in the + * data, so a quiet day does not repaint the series. + * + * Expired holds are deliberately absent: a hold that has expired no longer occupies a + * seat, so stacking it against sellable capacity would double-count. It is reported as a + * standalone counter instead. + */ +const INVENTORY_SERIES = [ + { key: "paid", label: "Paid", slot: 0 }, + { key: "unpaid", label: "Unpaid", slot: 1 }, + { key: "blocked", label: "Blocked", slot: 3 }, + { key: "available", label: "Available", slot: -1 }, +] as const; + +const MAX_SCHEDULE_BARS = 12; + +/** `YYYY-MM-DD` → `05 Mar`, parsed by parts so no timezone can shift the label. */ +function formatDayLabel(date: string): string { + const [, month, day] = date.split("-"); + const monthName = [ + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", + ][Number(month) - 1]; + return `${day} ${monthName}`; +} + +function formatWindow(from: string, to: string): string { + const opts: Intl.DateTimeFormatOptions = { day: "2-digit", month: "short" }; + return `${new Date(from).toLocaleDateString("en-GB", opts)} – ${new Date( + to, + ).toLocaleDateString("en-GB", opts)}`; +} + +export interface FleetSeatOverviewProps { + /** Selecting a schedule from a chart hands control to the drill-down. */ + onSelectSchedule: (scheduleId: string) => void; +} + +export default function FleetSeatOverview({ onSelectSchedule }: FleetSeatOverviewProps) { + const isDark = useTheme((s) => s.isDark); + const palette = getChartPalette(isDark); + + const { data, isLoading, isError } = useQuery({ + queryKey: ["seat-status-overview"], + queryFn: () => apiClient.get("/reports/seat-status/overview"), + }); + + const seriesColor = (slot: number) => + slot < 0 ? palette.grid : categoricalColor(palette, slot); + + const dayRows = useMemo( + () => (data?.byDay ?? []).map((d) => ({ ...d, label: formatDayLabel(d.date) })), + [data], + ); + + // Busiest departures first — a 12-bar chart of the whole window would be unreadable, + // and the ones carrying the most seats are the ones worth looking at. + const scheduleRows = useMemo( + () => + (data?.schedules ?? []) + .slice() + .sort((a, b) => b.sellableSeats - a.sellableSeats) + .slice(0, MAX_SCHEDULE_BARS) + .map((s) => ({ + ...s, + label: `${s.trainNumber} · ${new Date(s.departureAt).toLocaleDateString("en-GB", { + day: "2-digit", + month: "short", + })}`, + })), + [data], + ); + + if (isLoading) { + return ( +
+

Loading fleet seat overview…

+
+ ); + } + + if (isError) { + return ( +
+

Failed to load the fleet seat overview.

+

+ Select a schedule above to load its report directly. +

+
+ ); + } + + if (!data || data.totals.scheduleCount === 0) { + return ( +
+ +

No departures on record to summarise

+

Select a schedule above to load its seat status report

+
+ ); + } + + const { window: win, totals } = data; + + return ( +
+ {/* Window banner — the report is fleet-wide until a schedule is chosen, and the + window may be historic, so both facts are stated rather than implied. */} +
+
+
+ +
+

+ All schedules · {formatWindow(win.from, win.to)} +

+

+ {win.direction === "UPCOMING" + ? `Next ${win.days} days — ${totals.scheduleCount} departure${totals.scheduleCount === 1 ? "" : "s"}` + : `No upcoming departures — showing the most recent ${win.days} days (${totals.scheduleCount} departure${totals.scheduleCount === 1 ? "" : "s"})`} + {win.truncated && " · truncated to the first 60 departures"} +

+
+
+
+ + Load factor + + {totals.loadFactorPercent}% + +
+
+
+ + {/* Window totals. Distinct wording from the per-schedule summary cards so the two + are never mistaken for each other. */} +
+ {[ + { label: "Paid", value: totals.paidCount, hint: "Payment confirmed", slot: 0 }, + { label: "Unpaid", value: totals.unpaidCount, hint: "Awaiting payment", slot: 1 }, + { label: "Blocked", value: totals.blockedCount, hint: "Withheld from sale", slot: 3 }, + { label: "Available", value: totals.availableCount, hint: "Still sellable", slot: -1 }, + { + label: "Expired Holds", + value: totals.expiredHoldCount, + hint: "Last 24h, seats released", + slot: -2, + }, + ].map((tile) => ( +
+
+ {tile.slot !== -2 && ( + + )} +
+

{tile.label}

+

+ {tile.value} +

+

{tile.hint}

+
+
+
+ ))} +
+ + {/* Seat mix per departure day */} +
+
+

+ Seat mix by departure day +

+ + {totals.sellableSeats} sellable seats in window + +
+

+ Every seat running on each day, split by what happened to it — paid, waiting on + payment, blocked, or still on sale. The whole bar is that day's capacity. +

+ + {/* Legend carries visible text labels — the palette's light-mode contrast is + validated only with that relief in place. */} +
+ {INVENTORY_SERIES.map((s) => ( +
+ + {s.label} +
+ ))} +
+ + + + + + + + {INVENTORY_SERIES.map((s) => ( + + ))} + + +
+ + {/* Load factor per schedule — doubles as the picker */} +
+

+ Load factor by departure +

+

+ How full each train is — paid seats as a share of the seats it can sell, so 100% + means sold out. Showing the {scheduleRows.length} busiest departure + {scheduleRows.length === 1 ? "" : "s"}; click a bar to open that train's + report. +

+ + + + + + + [ + `${value}% · ${entry?.payload?.paid ?? 0} of ${entry?.payload?.sellableSeats ?? 0} seats`, + "Load factor", + ]} + /> + { + const id = entry?.payload?.scheduleId ?? entry?.scheduleId; + if (id) onSelectSchedule(id); + }} + > + {scheduleRows.map((row) => ( + + ))} + + + +
+ + {/* The same numbers as a table — required relief for the palette's light-mode + contrast, and the only place the per-schedule detail is readable exactly. */} +
+
+

+ Schedules in window +

+

+ The exact numbers behind the charts, one row per departure. Click a row to + open that train's full seat status report. +

+
+
+ + + + {[ + "Departure", + "Train", + "Route", + "Sellable", + "Paid", + "Unpaid", + "Blocked", + "Available", + "Load", + ].map((h) => ( + + ))} + + + + {data.schedules.map((s) => ( + onSelectSchedule(s.scheduleId)} + className="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors cursor-pointer" + > + + + + + + + + + + + ))} + +
+ {h} +
+ {new Date(s.departureAt).toLocaleString("en-GB", { + dateStyle: "medium", + timeStyle: "short", + })} + + {s.trainNumber} + {s.isPackage && ( + (package) + )} + + {s.originStation} → {s.destinationStation} + + {s.sellableSeats} + {s.paid}{s.unpaid}{s.blocked} + {s.available} + + {s.loadFactorPercent}% +
+
+
+
+ ); +} From 62b2080aaf228c66ca4b755a1f4a1410fe72baed Mon Sep 17 00:00:00 2001 From: Abubeker Yasin Date: Thu, 13 Aug 2026 16:20:21 +0300 Subject: [PATCH 03/14] feat: ( reports ) add fleet passenger overview to passengers landing page --- .../src/modules/reports/reports.controller.ts | 18 + .../src/modules/reports/reports.service.ts | 259 +++++++++ .../src/app/reports/passengers/page.tsx | 10 +- .../reports/FleetPassengerOverview.tsx | 499 ++++++++++++++++++ 4 files changed, 780 insertions(+), 6 deletions(-) create mode 100644 apps/edr-passenger-web/backoffice/src/components/reports/FleetPassengerOverview.tsx 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 adf6ccb9e..55f19dae0 100644 --- a/apps/edr-passenger-api/src/modules/reports/reports.controller.ts +++ b/apps/edr-passenger-api/src/modules/reports/reports.controller.ts @@ -37,6 +37,24 @@ export class ReportsController { return this.service.getPassengerList(scheduleId); } + // Two segments, so `@Get(":reportId")` below cannot shadow it whatever the order. + @Get("passengers/overview") + @ApiOperation({ + summary: "Fleet-wide passenger mix across a departure window", + description: + "Landing view for the passengers report, shown before a schedule is picked. Returns passenger volume per " + + "departure day, nationality split, passenger-category mix and the busiest origin→destination pairs across " + + "the window, plus one row per schedule.\n\n" + + "The window is forward-looking — the next `days` days. If nothing is departing in that window, it falls " + + "back to the most recent `days` of departures on record and says so via `window.direction`.\n\n" + + "Counts CONFIRMED and BOARDED seats only, matching `GET /reports/passengers`. Carries no occupancy figure " + + "by design: this report and the seat status report measure capacity differently, so a shared occupancy " + + "number would contradict one of them.", + }) + getPassengerOverview(@Query('days') days?: string) { + return this.service.getPassengerOverview(days ? Number(days) : undefined); + } + @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 7a4fde4cb..89a01dd0d 100644 --- a/apps/edr-passenger-api/src/modules/reports/reports.service.ts +++ b/apps/edr-passenger-api/src/modules/reports/reports.service.ts @@ -49,6 +49,11 @@ const OVERVIEW_ACTIVE_BOOKING_STATUSES: BookingStatus[] = [ 'PENDING_PAYMENT', ]; +/** The passengers report counts people, so a seat awaiting payment does not qualify. */ +const PASSENGER_ACTIVE_BOOKING_STATUSES: BookingStatus[] = ['CONFIRMED', 'BOARDED']; +/** Route pairs are long-tailed; only the busiest are legible in a chart. */ +const TOP_ROUTES_LIMIT = 8; + const EMPTY_OVERVIEW_TOTALS = { scheduleCount: 0, sellableSeats: 0, @@ -1109,6 +1114,260 @@ export class ReportsService { }; } + /** + * Fleet-wide passenger mix across a departure window — the landing view for the + * passengers report, shown before a schedule is picked. + * + * Answers "who travelled", not "how full were the trains". Occupancy is deliberately + * absent: this report and the seat status report count capacity differently (this one + * includes dining and placeholder seats in `totalSeats`, the other does not), so an + * occupancy figure here would either contradict the table below it or the seats page. + * That pre-existing difference is left alone rather than silently reconciled. + * + * Counts CONFIRMED and BOARDED only, matching {@link getOccupancyBySchedule} — a seat + * awaiting payment has no passenger on it yet. + */ + async getPassengerOverview(daysRaw?: number) { + const days = Math.min( + Math.max(Math.trunc(daysRaw || OVERVIEW_DEFAULT_DAYS), 1), + OVERVIEW_MAX_DAYS, + ); + const now = new Date(); + + // Window resolution is intentionally a copy of the one in getSeatStatusOverview + // rather than a shared helper: the two reports are free to diverge on what window + // makes sense for them, and a shared helper would couple them for ~20 lines. + let from = now; + let to = new Date(now.getTime() + days * MS_PER_DAY_OVERVIEW); + let direction: 'UPCOMING' | 'RECENT' = 'UPCOMING'; + + const upcomingCount = await this.prisma.trainSchedule.count({ + where: { departureAt: { gte: from, lte: to }, status: { not: 'CANCELLED' } }, + }); + + if (upcomingCount === 0) { + const latest = await this.prisma.trainSchedule.findFirst({ + where: { departureAt: { lt: now }, status: { not: 'CANCELLED' } }, + orderBy: { departureAt: 'desc' }, + select: { departureAt: true }, + }); + if (latest) { + direction = 'RECENT'; + to = latest.departureAt; + from = new Date(to.getTime() - days * MS_PER_DAY_OVERVIEW); + } + } + + const schedules = await this.prisma.trainSchedule.findMany({ + where: { departureAt: { gte: from, lte: to }, status: { not: 'CANCELLED' } }, + select: { + id: true, + departureAt: true, + isPackageOnly: true, + originStationId: true, + destinationStationId: true, + train: { select: { number: true } }, + originStation: { select: { name: true } }, + destinationStation: { select: { name: true } }, + }, + orderBy: { departureAt: 'asc' }, + take: OVERVIEW_MAX_SCHEDULES, + }); + + if (schedules.length === 0) { + return { + window: { from, to, days, direction, truncated: false }, + totals: { scheduleCount: 0, totalPassengers: 0, groupPassengers: 0 }, + byDay: [], + byNationality: [], + byCategory: [], + topRoutes: [], + schedules: [], + }; + } + + const scheduleIds = schedules.map((s) => s.id); + + // Same three-branch OR as the per-schedule report: own scheduleId, return leg, or a + // legacy null-scheduleId row reached through the booking's outbound schedule. + const bookingSeats = await this.prisma.bookingSeat.findMany({ + where: { + OR: [ + { + scheduleId: { in: scheduleIds }, + booking: { status: { in: PASSENGER_ACTIVE_BOOKING_STATUSES } }, + }, + { + leg: 2, + booking: { + returnScheduleId: { in: scheduleIds }, + status: { in: PASSENGER_ACTIVE_BOOKING_STATUSES }, + }, + }, + { + scheduleId: null, + leg: 1, + booking: { + scheduleId: { in: scheduleIds }, + status: { in: PASSENGER_ACTIVE_BOOKING_STATUSES }, + }, + }, + ], + }, + select: { + scheduleId: true, + leg: true, + bookingId: true, + passengerCategory: true, + passportCountry: true, + idDocumentType: true, + booking: { + select: { + scheduleId: true, + returnScheduleId: true, + originStationId: true, + destinationStationId: true, + }, + }, + }, + }); + + // Station names for the route pairs. Bookings that never recorded a station fall back + // to the schedule's own endpoints, the same fallback getOccupancyBySchedule applies. + const stationIds = [ + ...new Set( + [ + ...bookingSeats.flatMap((bs) => [ + bs.booking.originStationId, + bs.booking.destinationStationId, + ]), + ...schedules.flatMap((s) => [s.originStationId, s.destinationStationId]), + ].filter((id): id is string => Boolean(id)), + ), + ]; + const stations = stationIds.length + ? await this.prisma.station.findMany({ + where: { id: { in: stationIds } }, + select: { id: true, name: true }, + }) + : []; + const stationName = new Map(stations.map((s) => [s.id, s.name])); + + const scheduleById = new Map(schedules.map((s) => [s.id, s])); + const scheduleIdSet = new Set(scheduleIds); + + const passengersBySchedule = new Map(); + const nationalityCounts = new Map(); + const categoryCounts = new Map(); + const routeCounts = new Map(); + // A booking contributing more than one seat to the window is a group booking. + const seatsPerBooking = new Map(); + + for (const bs of bookingSeats) { + const scheduleId = + bs.scheduleId && scheduleIdSet.has(bs.scheduleId) + ? bs.scheduleId + : bs.leg === 2 + ? bs.booking.returnScheduleId + : bs.booking.scheduleId; + if (!scheduleId || !scheduleIdSet.has(scheduleId)) continue; + + const schedule = scheduleById.get(scheduleId); + passengersBySchedule.set( + scheduleId, + (passengersBySchedule.get(scheduleId) ?? 0) + 1, + ); + seatsPerBooking.set(bs.bookingId, (seatsPerBooking.get(bs.bookingId) ?? 0) + 1); + + // Same derivation as getPassengerList, so the chart and the drill-down list agree + // on what a passenger's nationality is. + const nationality = bs.passportCountry + ? bs.passportCountry === 'Djibouti' + ? 'Djiboutian' + : bs.passportCountry + : bs.idDocumentType === 'NATIONAL_ID' + ? 'Ethiopian' + : 'Unknown'; + nationalityCounts.set(nationality, (nationalityCounts.get(nationality) ?? 0) + 1); + + const category = bs.passengerCategory ?? 'ADULT'; + categoryCounts.set(category, (categoryCounts.get(category) ?? 0) + 1); + + const originId = bs.booking.originStationId ?? schedule?.originStationId ?? null; + const destinationId = + bs.booking.destinationStationId ?? schedule?.destinationStationId ?? null; + if (originId && destinationId) { + const key = `${originId}|${destinationId}`; + const existing = routeCounts.get(key); + if (existing) { + existing.passengers += 1; + } else { + routeCounts.set(key, { + origin: stationName.get(originId) ?? originId, + destination: stationName.get(destinationId) ?? destinationId, + passengers: 1, + }); + } + } + } + + const groupPassengers = [...seatsPerBooking.values()] + .filter((count) => count > 1) + .reduce((sum, count) => sum + count, 0); + + const scheduleRows = schedules.map((s) => ({ + scheduleId: s.id, + trainNumber: s.train.number, + originStation: s.originStation.name, + destinationStation: s.destinationStation.name, + departureAt: s.departureAt, + isPackage: s.isPackageOnly, + passengers: passengersBySchedule.get(s.id) ?? 0, + })); + + const byDayMap = new Map(); + for (const row of scheduleRows) { + const date = row.departureAt.toISOString().slice(0, 10); + const bucket = byDayMap.get(date) ?? { date, scheduleCount: 0, passengers: 0 }; + bucket.scheduleCount += 1; + bucket.passengers += row.passengers; + byDayMap.set(date, bucket); + } + + const rank = (rows: T[]) => + rows.sort((a, b) => b.passengers - a.passengers); + + return { + window: { + from, + to, + days, + direction, + truncated: schedules.length === OVERVIEW_MAX_SCHEDULES, + }, + totals: { + scheduleCount: scheduleRows.length, + totalPassengers: scheduleRows.reduce((sum, r) => sum + r.passengers, 0), + groupPassengers, + }, + byDay: [...byDayMap.values()].sort((a, b) => a.date.localeCompare(b.date)), + byNationality: rank( + [...nationalityCounts.entries()].map(([nationality, passengers]) => ({ + nationality, + passengers, + })), + ), + byCategory: rank( + [...categoryCounts.entries()].map(([category, passengers]) => ({ + category, + passengers, + })), + ), + topRoutes: rank([...routeCounts.values()]).slice(0, TOP_ROUTES_LIMIT), + schedules: scheduleRows, + }; + } + async getPaymentDiscrepancyReport(params: { from?: string; to?: string; 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 ca6a2c2f8..0ed48c17b 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 @@ -4,6 +4,7 @@ import { useState } from "react"; import { useQuery } from "@tanstack/react-query"; import { Users, Armchair, BarChart3, Train, Download } from "lucide-react"; import { apiClient } from "@/lib/api-client"; +import FleetPassengerOverview from "@/components/reports/FleetPassengerOverview"; import { formatDateTime } from "@/lib/utils"; import ActionButton from "@/components/ui/ActionButton"; import Pagination from "@/components/ui/Pagination"; @@ -585,12 +586,9 @@ export default function PassengersReportPage() { )} - {!scheduleId && ( -
- -

Select a schedule above to load the occupancy report

-
- )} + {/* Landing state only. Unmounts the moment a schedule is selected, leaving the + per-schedule report above untouched. */} + {!scheduleId && } ); } diff --git a/apps/edr-passenger-web/backoffice/src/components/reports/FleetPassengerOverview.tsx b/apps/edr-passenger-web/backoffice/src/components/reports/FleetPassengerOverview.tsx new file mode 100644 index 000000000..c59121005 --- /dev/null +++ b/apps/edr-passenger-web/backoffice/src/components/reports/FleetPassengerOverview.tsx @@ -0,0 +1,499 @@ +"use client"; + +/** + * Fleet passenger overview — the landing state of the Passengers Report, shown only + * while no schedule is selected. Once a schedule is picked this component unmounts and + * the per-schedule occupancy/list tabs take over unchanged. + * + * Carries no occupancy figure by design. This report and the seat status report measure + * capacity differently (this one counts dining and placeholder seats toward `totalSeats`, + * the other does not), so an occupancy number here would contradict one of them. This + * view answers "who travelled" and leaves "how full" to the seat status report. + */ + +import { useMemo } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { + Bar, + BarChart, + CartesianGrid, + LabelList, + ResponsiveContainer, + Tooltip, + XAxis, + YAxis, +} from "recharts"; +import { CalendarClock, Users } from "lucide-react"; +import { apiClient } from "@/lib/api-client"; +import { categoricalColor, getChartPalette } from "@/lib/chart-palette"; +import { useTheme } from "@/lib/theme-store"; + +interface OverviewScheduleRow { + scheduleId: string; + trainNumber: string; + originStation: string; + destinationStation: string; + departureAt: string; + isPackage: boolean; + passengers: number; +} + +interface PassengerOverview { + window: { + from: string; + to: string; + days: number; + direction: "UPCOMING" | "RECENT"; + truncated: boolean; + }; + totals: { + scheduleCount: number; + totalPassengers: number; + groupPassengers: number; + }; + byDay: { date: string; scheduleCount: number; passengers: number }[]; + byNationality: { nationality: string; passengers: number }[]; + byCategory: { category: string; passengers: number }[]; + topRoutes: { origin: string; destination: string; passengers: number }[]; + schedules: OverviewScheduleRow[]; +} + +/** + * Fixed colour domain for passenger category. Keyed by position in this list rather than + * by rank in the data, so a day with no children does not repaint the adult segment. + */ +const CATEGORY_ORDER = ["ADULT", "CHILD"] as const; +const CATEGORY_LABELS: Record = { ADULT: "Adult", CHILD: "Child" }; + +const MAX_NATIONALITY_BARS = 8; + +/** `YYYY-MM-DD` → `05 Mar`, parsed by parts so no timezone can shift the label. */ +function formatDayLabel(date: string): string { + const [, month, day] = date.split("-"); + const monthName = [ + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", + ][Number(month) - 1]; + return `${day} ${monthName}`; +} + +function formatWindow(from: string, to: string): string { + const opts: Intl.DateTimeFormatOptions = { day: "2-digit", month: "short" }; + return `${new Date(from).toLocaleDateString("en-GB", opts)} – ${new Date( + to, + ).toLocaleDateString("en-GB", opts)}`; +} + +export interface FleetPassengerOverviewProps { + /** Selecting a schedule from a chart or row hands control to the drill-down. */ + onSelectSchedule: (scheduleId: string) => void; +} + +export default function FleetPassengerOverview({ + onSelectSchedule, +}: FleetPassengerOverviewProps) { + const isDark = useTheme((s) => s.isDark); + const palette = getChartPalette(isDark); + + const { data, isLoading, isError } = useQuery({ + queryKey: ["passenger-overview"], + queryFn: () => apiClient.get("/reports/passengers/overview"), + }); + + const dayRows = useMemo( + () => (data?.byDay ?? []).map((d) => ({ ...d, label: formatDayLabel(d.date) })), + [data], + ); + + const nationalityRows = useMemo( + () => (data?.byNationality ?? []).slice(0, MAX_NATIONALITY_BARS), + [data], + ); + + const routeRows = useMemo( + () => + (data?.topRoutes ?? []).map((r) => ({ + ...r, + label: `${r.origin} → ${r.destination}`, + })), + [data], + ); + + // One row, one bar, stacked by category — a two-value composition reads better as a + // single bar than as a chart with two lonely columns. + const categoryRow = useMemo(() => { + const row: Record = { name: "mix" }; + for (const c of data?.byCategory ?? []) row[c.category] = c.passengers; + return [row]; + }, [data]); + + const categoriesPresent = useMemo(() => { + const seen = new Set((data?.byCategory ?? []).map((c) => c.category)); + const known = CATEGORY_ORDER.filter((c) => seen.has(c)); + const unknown = [...seen].filter( + (c) => !CATEGORY_ORDER.includes(c as (typeof CATEGORY_ORDER)[number]), + ); + return [...known, ...unknown]; + }, [data]); + + const categoryColor = (category: string) => { + const index = CATEGORY_ORDER.indexOf(category as (typeof CATEGORY_ORDER)[number]); + return categoricalColor(palette, index >= 0 ? index : CATEGORY_ORDER.length); + }; + + const tooltipStyle = { + background: palette.tooltipBg, + border: `1px solid ${palette.tooltipBorder}`, + borderRadius: 8, + fontSize: 12, + }; + + if (isLoading) { + return ( +
+

Loading fleet passenger overview…

+
+ ); + } + + if (isError) { + return ( +
+

Failed to load the fleet passenger overview.

+

+ Select a schedule above to load its report directly. +

+
+ ); + } + + if (!data || data.totals.scheduleCount === 0) { + return ( +
+ +

No departures on record to summarise

+

+ Select a schedule above to load its passengers report +

+
+ ); + } + + const { window: win, totals } = data; + const groupShare = + totals.totalPassengers > 0 + ? Math.round((totals.groupPassengers / totals.totalPassengers) * 100) + : 0; + + return ( +
+ {/* Window banner — the view is fleet-wide until a schedule is chosen, and the + window may be historic, so both facts are stated rather than implied. */} +
+
+
+ +
+

+ All schedules · {formatWindow(win.from, win.to)} +

+

+ {win.direction === "UPCOMING" + ? `Next ${win.days} days — ${totals.scheduleCount} departure${totals.scheduleCount === 1 ? "" : "s"}` + : `No upcoming departures — showing the most recent ${win.days} days (${totals.scheduleCount} departure${totals.scheduleCount === 1 ? "" : "s"})`} + {win.truncated && " · truncated to the first 60 departures"} +

+
+
+
+
+ + {/* Window totals */} +
+
+

Passengers

+

+ {totals.totalPassengers} +

+

Confirmed and boarded

+
+
+

Departures

+

+ {totals.scheduleCount} +

+

In this window

+
+
+

Travelling in groups

+

+ {totals.groupPassengers} +

+

+ {groupShare}% of passengers, on multi-seat bookings +

+
+
+ + {/* 1 — Passengers per departure day */} +
+

+ Passengers by departure day +

+

+ How many people travelled each day across every train in the window. +

+ + + + + + + + + +
+ +
+ {/* 2 — Nationality split */} +
+

+ Passengers by nationality +

+

+ Taken from passport country, or Ethiopian where a national ID was used. + “Unknown” means neither was recorded. +

+ + + + + + + + {/* Values printed on the bars — the palette's light-mode contrast is + validated only with numeric relief in place. */} + + + + +
+ + {/* 4 — Busiest origin → destination pairs */} +
+

+ Busiest routes +

+

+ Where people actually travelled from and to — not the train's own + endpoints, but each booking's. +

+ + + + + + + + + + + +
+
+ + {/* 3 — Passenger category mix */} +
+

+ Adult and child mix +

+

+ The whole bar is every passenger in the window, split by fare category. +

+ +
+ {categoriesPresent.map((category) => { + const count = + data.byCategory.find((c) => c.category === category)?.passengers ?? 0; + return ( +
+ + + {CATEGORY_LABELS[category] ?? category} · {count} + +
+ ); + })} +
+ + + + + + + {categoriesPresent.map((category) => ( + + ))} + + +
+ + {/* The same numbers as exact figures, and the picker */} +
+
+

+ Schedules in window +

+

+ The exact numbers behind the charts, one row per departure. Click a row to + open that train's full passengers report. +

+
+
+ + + + {["Departure", "Train", "Route", "Passengers"].map((h) => ( + + ))} + + + + {data.schedules.map((s) => ( + onSelectSchedule(s.scheduleId)} + className="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors cursor-pointer" + > + + + + + + ))} + +
+ {h} +
+ {new Date(s.departureAt).toLocaleString("en-GB", { + dateStyle: "medium", + timeStyle: "short", + })} + + {s.trainNumber} + {s.isPackage && ( + (package) + )} + + {s.originStation} → {s.destinationStation} + + {s.passengers} +
+
+
+
+ ); +} From 449dea78ab75bbdbe01a2422f88c25499ccda96c Mon Sep 17 00:00:00 2001 From: Abubeker Yasin Date: Thu, 13 Aug 2026 23:31:20 +0300 Subject: [PATCH 04/14] feat: ( dashboard ) add booking charts --- .../modules/dashboard/dashboard.controller.ts | 23 +- .../modules/dashboard/dashboard.service.ts | 108 +++++ .../backoffice/src/app/dashboard/page.tsx | 4 + .../dashboard/DashboardBookingCharts.tsx | 403 ++++++++++++++++++ 4 files changed, 537 insertions(+), 1 deletion(-) create mode 100644 apps/edr-passenger-web/backoffice/src/components/dashboard/DashboardBookingCharts.tsx diff --git a/apps/edr-passenger-api/src/modules/dashboard/dashboard.controller.ts b/apps/edr-passenger-api/src/modules/dashboard/dashboard.controller.ts index eb7bd33b6..6f74ab412 100644 --- a/apps/edr-passenger-api/src/modules/dashboard/dashboard.controller.ts +++ b/apps/edr-passenger-api/src/modules/dashboard/dashboard.controller.ts @@ -1,4 +1,4 @@ -import { Controller, Get, Param, SetMetadata, UseGuards } from '@nestjs/common'; +import { Controller, Get, Param, Query, SetMetadata, UseGuards } from '@nestjs/common'; import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger'; import { DashboardService } from './dashboard.service'; import { JwtGuard } from '../../common/jwt.guard'; @@ -16,6 +16,27 @@ export class DashboardController { @ApiOperation({ summary: 'Backoffice summary: totals and revenue by currency' }) getBackofficeStats() { return this.service.getBackofficeStats(); } + // Two segments, so the single-segment `@Get(':passengerId')` below cannot swallow it + // however the routes are ordered. Staff-guarded like backoffice-stats, not JwtGuard. + @Get('analytics/bookings') + @PassengerStaff([PASSENGER_PERMS.dashboard.view, PASSENGER_PERMS.admin]) + @ApiBearerAuth('IAM-auth') + @ApiOperation({ + summary: 'Booking analytics for the dashboard charts', + description: + 'Revenue trend, daily confirmed bookings, booking status distribution and payment-method split over the ' + + 'last `days` days (default 30), bucketed by booking creation date.\n\n' + + 'Revenue and the daily count cover CONFIRMED and BOARDED bookings; the status and payment-method ' + + 'breakdowns cover every booking in range — the same asymmetry the /reports/overall page applies, kept so ' + + 'the two agree.\n\n' + + 'Revenue is returned per currency and unconverted; the caller applies its own exchange rates. These ' + + 'figures answer "what was booked" and will not match the Revenue Breakdown card, which requires a ' + + 'SUCCEEDED payment intent and answers "what was collected".', + }) + getBookingAnalytics(@Query('days') days?: string) { + return this.service.getBookingAnalytics(days ? Number(days) : undefined); + } + @Get(':passengerId') @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth') diff --git a/apps/edr-passenger-api/src/modules/dashboard/dashboard.service.ts b/apps/edr-passenger-api/src/modules/dashboard/dashboard.service.ts index f7e015e11..79891a023 100644 --- a/apps/edr-passenger-api/src/modules/dashboard/dashboard.service.ts +++ b/apps/edr-passenger-api/src/modules/dashboard/dashboard.service.ts @@ -3,6 +3,11 @@ import { InjectDataSource } from '@nestjs/typeorm'; import { DataSource } from 'typeorm'; import { PrismaService } from '../../common/prisma.service'; +// ── Booking analytics (backoffice dashboard charts) ────────────────────────── +const MS_PER_DAY_ANALYTICS = 24 * 60 * 60 * 1000; +const ANALYTICS_DEFAULT_DAYS = 30; +const ANALYTICS_MAX_DAYS = 365; + @Injectable() export class DashboardService { constructor( @@ -63,6 +68,109 @@ export class DashboardService { }; } + /** + * Booking analytics for the backoffice dashboard charts — revenue trend, daily + * confirmed bookings, status distribution and payment-method split. + * + * Ported from the client-side computation on `/reports/overall`, which pulled up to + * 5000 bookings into the browser and grouped them there. The dashboard is the landing + * page and refetches on an interval, so the grouping happens here instead. + * + * Two asymmetries are inherited from that report on purpose, so the dashboard and the + * report show the same figures: + * - Revenue and the daily count use CONFIRMED and BOARDED only; the status and + * payment-method breakdowns use every booking in range. + * - Everything buckets on `createdAt` — when the booking was made, not when the + * train departs. + * + * Revenue here will NOT equal the dashboard's Revenue Breakdown card, which + * additionally requires a SUCCEEDED PaymentIntent and prefers the display amounts + * (see getBackofficeStats). Different question, deliberately not reconciled: this is + * "what was booked", that is "what was collected". + */ + async getBookingAnalytics(daysRaw?: number) { + const days = Math.min( + Math.max(Math.trunc(daysRaw || ANALYTICS_DEFAULT_DAYS), 1), + ANALYTICS_MAX_DAYS, + ); + const to = new Date(); + const from = new Date(to.getTime() - days * MS_PER_DAY_ANALYTICS); + + const bookings = await this.prisma.booking.findMany({ + where: { createdAt: { gte: from, lte: to } }, + select: { + createdAt: true, + status: true, + totalMinor: true, + currency: true, + paymentIntent: { select: { method: true } }, + }, + }); + + const isConfirmed = (status: string) => status === 'CONFIRMED' || status === 'BOARDED'; + + // Day buckets keyed on the UTC calendar date, so the axis and the bars derive from + // one value and cannot disagree. + const byDayMap = new Map< + string, + { date: string; bookings: number; revenueByCurrency: Map } + >(); + const statusCounts = new Map(); + const methodCounts = new Map(); + + for (const booking of bookings) { + // Status and payment method count every booking in range. + const status = booking.status ?? 'UNKNOWN'; + statusCounts.set(status, (statusCounts.get(status) ?? 0) + 1); + + const method = booking.paymentIntent?.method ?? 'UNKNOWN'; + methodCounts.set(method, (methodCounts.get(method) ?? 0) + 1); + + // Revenue and the daily count are confirmed travel only. + if (!isConfirmed(booking.status)) continue; + + const date = booking.createdAt.toISOString().slice(0, 10); + const bucket = + byDayMap.get(date) ?? { date, bookings: 0, revenueByCurrency: new Map() }; + bucket.bookings += 1; + + const currency = booking.currency ?? 'ETB'; + bucket.revenueByCurrency.set( + currency, + (bucket.revenueByCurrency.get(currency) ?? 0) + (booking.totalMinor ?? 0), + ); + byDayMap.set(date, bucket); + } + + const byDay = [...byDayMap.values()] + .sort((a, b) => a.date.localeCompare(b.date)) + .map((bucket) => ({ + date: bucket.date, + bookings: bucket.bookings, + revenueByCurrency: [...bucket.revenueByCurrency.entries()].map( + ([currency, totalMinor]) => ({ currency, totalMinor }), + ), + })); + + const rank = (rows: T[]) => + rows.sort((a, b) => b.count - a.count); + + return { + window: { from, to, days }, + totals: { + bookings: bookings.length, + confirmedBookings: bookings.filter((b) => isConfirmed(b.status)).length, + }, + byDay, + statusDistribution: rank( + [...statusCounts.entries()].map(([status, count]) => ({ status, count })), + ), + paymentMethods: rank( + [...methodCounts.entries()].map(([method, count]) => ({ method, count })), + ), + }; + } + async getHomeDashboard(passengerId: string) { const now = new Date(); const [passenger, upcomingBooking, wallet, promos, weatherAlerts, stationSignals, savedRoutes] = await Promise.all([ diff --git a/apps/edr-passenger-web/backoffice/src/app/dashboard/page.tsx b/apps/edr-passenger-web/backoffice/src/app/dashboard/page.tsx index 7eede0089..cd1bbe131 100644 --- a/apps/edr-passenger-web/backoffice/src/app/dashboard/page.tsx +++ b/apps/edr-passenger-web/backoffice/src/app/dashboard/page.tsx @@ -12,6 +12,7 @@ import { ScanLine, } from "lucide-react"; import { dashboardApi } from "@/lib/api/dashboard"; +import DashboardBookingCharts from "@/components/dashboard/DashboardBookingCharts"; import { apiClient } from "@/lib/api-client"; import { formatCurrency } from "@/lib/utils"; import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer } from "recharts"; @@ -322,6 +323,9 @@ function DashboardPageContent() { + {/* Booking charts — self-contained; degrades to a single line if its endpoint fails. */} + + {/* Revenue breakdown */}

diff --git a/apps/edr-passenger-web/backoffice/src/components/dashboard/DashboardBookingCharts.tsx b/apps/edr-passenger-web/backoffice/src/components/dashboard/DashboardBookingCharts.tsx new file mode 100644 index 000000000..d9c1803f6 --- /dev/null +++ b/apps/edr-passenger-web/backoffice/src/components/dashboard/DashboardBookingCharts.tsx @@ -0,0 +1,403 @@ +"use client"; + +/** + * Booking charts for the backoffice dashboard — revenue trend, daily confirmed + * bookings, status distribution and payment-method split over the last 30 days. + * + * Ported from `/reports/overall`, which computes the same four panels in the browser + * from a 5000-row booking fetch. Here the grouping is done by + * `GET /dashboard/analytics/bookings` so the landing page stays light. + * + * Revenue on this panel answers "what was booked" — CONFIRMED and BOARDED bookings by + * creation date. The Revenue Breakdown card below answers "what was collected" (it also + * requires a SUCCEEDED payment intent). The two will not match, which is why each says + * what it measures in its own heading. + */ + +import { useMemo } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { + Bar, + BarChart, + CartesianGrid, + Cell, + LabelList, + Line, + LineChart, + Pie, + PieChart, + ResponsiveContainer, + Tooltip, + XAxis, + YAxis, +} from "recharts"; +import { apiClient } from "@/lib/api-client"; +import { categoricalColor, getChartPalette } from "@/lib/chart-palette"; +import { useTheme } from "@/lib/theme-store"; +import { formatCurrency } from "@/lib/utils"; + +interface BookingAnalytics { + window: { from: string; to: string; days: number }; + totals: { bookings: number; confirmedBookings: number }; + byDay: { + date: string; + bookings: number; + revenueByCurrency: { currency: string; totalMinor: number }[]; + }[]; + statusDistribution: { status: string; count: number }[]; + paymentMethods: { method: string; count: number }[]; +} + +/** + * Fixed colour domain for booking status. Keyed by position in the enum rather than by + * rank in the data, so a day with no cancellations does not repaint the other slices. + */ +const STATUS_ORDER = [ + "CONFIRMED", + "BOARDED", + "PENDING_PAYMENT", + "CANCELLED", + "REFUNDED", + "NO_SHOW", +] as const; + +const STATUS_LABELS: Record = { + CONFIRMED: "Confirmed", + BOARDED: "Boarded", + PENDING_PAYMENT: "Pending payment", + CANCELLED: "Cancelled", + REFUNDED: "Refunded", + NO_SHOW: "No show", + DRAFT: "Draft", + UNKNOWN: "Unknown", +}; + +const MAX_METHOD_BARS = 6; + +/** `YYYY-MM-DD` → `5 Mar`, parsed by parts so no timezone can shift the label. */ +function formatDayLabel(date: string): string { + const [, month, day] = date.split("-"); + const monthName = [ + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", + ][Number(month) - 1]; + return `${Number(day)} ${monthName}`; +} + +function prettyMethod(method: string): string { + return method + .toLowerCase() + .replace(/_/g, " ") + .replace(/\b\w/g, (c) => c.toUpperCase()); +} + +export default function DashboardBookingCharts() { + const isDark = useTheme((s) => s.isDark); + const palette = getChartPalette(isDark); + + // Same query key the dashboard page already uses, so this shares its cache rather + // than issuing a second request for the rates. + const { data: exchangeRates = [] } = useQuery({ + queryKey: ["currencies"], + queryFn: () => apiClient.get("/currencies"), + select: (d: any) => (Array.isArray(d) ? d : (d?.data ?? d?.items ?? [])), + }); + + const { data, isLoading, isError } = useQuery({ + queryKey: ["dashboard-booking-analytics"], + queryFn: () => apiClient.get("/dashboard/analytics/bookings"), + staleTime: 60_000, + }); + + // Matches the conversion the dashboard page applies to its revenue cards. + const toEtbRate = (currency: string): number | null => { + if (currency === "ETB") return 1; + const r = exchangeRates.find( + (x: any) => x.fromCurrency === "ETB" && x.toCurrency === currency, + ); + return r ? 1 / r.rate : null; + }; + + const dayRows = useMemo( + () => + (data?.byDay ?? []).map((d) => ({ + label: formatDayLabel(d.date), + bookings: d.bookings, + // A currency with no rate on file is left out rather than counted at 1:1. + revenueMinor: d.revenueByCurrency.reduce((sum, r) => { + const rate = toEtbRate(r.currency); + return rate !== null ? sum + Math.round(r.totalMinor * rate) : sum; + }, 0), + })), + // eslint-disable-next-line react-hooks/exhaustive-deps + [data, exchangeRates], + ); + + const statusRows = useMemo( + () => + (data?.statusDistribution ?? []) + .filter((s) => s.count > 0) + .map((s) => ({ + name: STATUS_LABELS[s.status] ?? s.status, + value: s.count, + color: categoricalColor( + palette, + STATUS_ORDER.indexOf(s.status as (typeof STATUS_ORDER)[number]) >= 0 + ? STATUS_ORDER.indexOf(s.status as (typeof STATUS_ORDER)[number]) + : STATUS_ORDER.length, + ), + })), + [data, palette], + ); + + const methodRows = useMemo( + () => + (data?.paymentMethods ?? []).slice(0, MAX_METHOD_BARS).map((m) => ({ + label: prettyMethod(m.method), + count: m.count, + })), + [data], + ); + + const tooltipStyle = { + background: palette.tooltipBg, + border: `1px solid ${palette.tooltipBorder}`, + borderRadius: 8, + fontSize: 12, + }; + + if (isLoading) { + return ( +
+

Loading booking analytics…

+
+ ); + } + + // The dashboard's other cards stand on their own, so a failure here degrades to a + // single quiet line rather than taking the page down. + if (isError || !data) { + return ( +
+

+ Booking analytics are unavailable right now. +

+
+ ); + } + + const hasDays = dayRows.length > 0; + const rangeLabel = `Last ${data.window.days} days`; + + const emptyPanel = ( +
+ No bookings in this range +
+ ); + + return ( +
+ {/* Revenue Trend */} +
+

+ Revenue Trend +

+

+ {rangeLabel} · value of confirmed bookings on the day they were made, in ETB. + Not the same as collected revenue below. +

+ {hasDays ? ( + + + + + Math.round(v / 100).toLocaleString()} + /> + [formatCurrency(value, "ETB"), "Revenue"]} + /> + + + + ) : ( + emptyPanel + )} +
+ + {/* Daily Confirmed Bookings */} +
+

+ Daily Confirmed Bookings +

+

+ {rangeLabel} · how many bookings were confirmed each day. +

+ {hasDays ? ( + + + + + + + + + + ) : ( + emptyPanel + )} +
+ + {/* Booking Status Distribution */} +
+

+ Booking Status Distribution +

+

+ {rangeLabel} · every booking made in the range, by current status. +

+ {statusRows.length > 0 ? ( + <> + {/* Legend with text labels and counts — the palette's light-mode contrast is + validated only with that relief in place. */} +
+ {statusRows.map((s) => ( +
+ + + {s.name} · {s.value} + +
+ ))} +
+ + + + {statusRows.map((s) => ( + + ))} + + + + + + ) : ( + emptyPanel + )} +
+ + {/* Payment Methods */} +
+

+ Payment Methods +

+

+ {rangeLabel} · which method each booking used. “Unknown” means no + payment was started. +

+ {methodRows.length > 0 ? ( + + + + + + + + + + + + ) : ( + emptyPanel + )} +
+
+ ); +} From d952792e1540ef358b685ed8a0b7e3f6ab56e089 Mon Sep 17 00:00:00 2001 From: Abubeker Yasin Date: Fri, 14 Aug 2026 16:37:51 +0300 Subject: [PATCH 05/14] fix: ( portal ) opt out of browser translation to stop booking crash --- apps/edr-passenger-web/portal/src/app/layout.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/edr-passenger-web/portal/src/app/layout.tsx b/apps/edr-passenger-web/portal/src/app/layout.tsx index 7337c18d6..57aad945b 100644 --- a/apps/edr-passenger-web/portal/src/app/layout.tsx +++ b/apps/edr-passenger-web/portal/src/app/layout.tsx @@ -62,6 +62,9 @@ export const metadata: Metadata = { shortcut: '/edr-logo.png', apple: '/edr-logo.png', }, + other: { + google: 'notranslate', + }, }; // viewportFit: 'cover' lets fixed bottom bars (e.g. the payment page's Pay @@ -117,7 +120,7 @@ export default function RootLayout({ }; return ( - + From b9e000729d8926f20d09c71547c931db7408e2cd Mon Sep 17 00:00:00 2001 From: Abubeker Yasin Date: Mon, 17 Aug 2026 09:47:36 +0300 Subject: [PATCH 06/14] fix: ( payments ) restrict force-confirm to tickets:generate permission --- .../src/modules/payments/payments.controller.ts | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/apps/edr-passenger-api/src/modules/payments/payments.controller.ts b/apps/edr-passenger-api/src/modules/payments/payments.controller.ts index 9c1bfa65d..858d108fe 100644 --- a/apps/edr-passenger-api/src/modules/payments/payments.controller.ts +++ b/apps/edr-passenger-api/src/modules/payments/payments.controller.ts @@ -211,17 +211,14 @@ export class PaymentsController { } @Post(":bookingId/force-confirm") - @PassengerStaff([ - PASSENGER_PERMS.payments.manage, - PASSENGER_PERMS.payments.manageMethods, - PASSENGER_PERMS.admin, - ]) + @PassengerStaff([PASSENGER_PERMS.tickets.generate, PASSENGER_PERMS.admin]) @ApiBearerAuth("IAM-auth") @ApiOperation({ - summary: "Force-confirm payment & generate ticket (back-office only)", + summary: "Force-confirm payment & generate ticket (ticket-generate permission)", description: "Marks the payment as SUCCEEDED, confirms the booking, and generates the ticket. " + - "Use when a vendor payment completed but the webhook was never delivered. Idempotent.", + "Use when a vendor payment completed but the webhook was never delivered. Idempotent. " + + "Requires `edr_passenger_app:tickets:generate` (admins bypass).", }) forceConfirm( @Param("bookingId") bookingId: string, From b453b81ff530ee6536ee49451094c42fc905a909 Mon Sep 17 00:00:00 2001 From: Abubeker Yasin Date: Mon, 17 Aug 2026 09:55:02 +0300 Subject: [PATCH 07/14] feat: ( backoffice ) hide Generate Ticket action without tickets:generate --- apps/edr-passenger-web/backoffice/src/app/bookings/page.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/edr-passenger-web/backoffice/src/app/bookings/page.tsx b/apps/edr-passenger-web/backoffice/src/app/bookings/page.tsx index a1909d6e8..fffe3722c 100644 --- a/apps/edr-passenger-web/backoffice/src/app/bookings/page.tsx +++ b/apps/edr-passenger-web/backoffice/src/app/bookings/page.tsx @@ -31,6 +31,9 @@ const SectionHeader = ({ title }: { title: string }) => ( function BookingsPageContent() { const canManage = usePermission(PERMS.bookings.manage); + // Mirrors the API guard on POST /payments/:bookingId/force-confirm — + // tickets:generate, with the usual super-admin / org-admin bypass. + const canGenerateTicket = usePermission(PERMS.tickets.generate); const [filters, setFilters] = useState({ page: 1, pageSize: 20, search: '', status: '' }); const [extraFilters, setExtraFilters] = useState({ bookingType: '', dateFrom: '', dateTo: '', paymentStatus: '', providerTxnId: '' }); const [showExtraFilters, setShowExtraFilters] = useState(false); @@ -298,7 +301,7 @@ function BookingsPageContent() { const actions = [ { label: 'View Details', onClick: (b: any) => setSelectedBooking(b), variant: 'secondary' as const, icon: Eye }, - { label: 'Generate Ticket', onClick: (b: any) => { setGenerateTicketForm({ paymentReference: '', paymentMethod: '', notes: '' }); setGenerateTicketTouched({ paymentReference: false, paymentMethod: false }); setGenerateTicketBooking(b); }, variant: 'secondary' as const, icon: Ticket, show: (b: any) => !(b.status === 'CONFIRMED' && b.paymentIntent?.status === 'SUCCEEDED') }, + { label: 'Generate Ticket', onClick: (b: any) => { setGenerateTicketForm({ paymentReference: '', paymentMethod: '', notes: '' }); setGenerateTicketTouched({ paymentReference: false, paymentMethod: false }); setGenerateTicketBooking(b); }, variant: 'secondary' as const, icon: Ticket, show: (b: any) => canGenerateTicket && !(b.status === 'CONFIRMED' && b.paymentIntent?.status === 'SUCCEEDED') }, { label: 'Delete', onClick: (b: any) => { setDeleteError(null); setDeleteCascade(false); setDeleteCascadeChecked(false); setBookingToDelete(b); setDeleteConfirmOpen(true); }, variant: 'danger' as const, icon: Trash2 }, ]; From 41080c1650f88bd9ca64fedb8b91686d7a7d12cc Mon Sep 17 00:00:00 2001 From: Abubeker Yasin Date: Mon, 17 Aug 2026 10:22:52 +0300 Subject: [PATCH 08/14] feat: ( backoffice ) gate Master Data pages and sidebar on view permissions --- .../backoffice/src/app/classes/page.tsx | 12 +++++++++++- .../backoffice/src/app/coaches/page.tsx | 12 +++++++++++- .../backoffice/src/app/routes/page.tsx | 12 +++++++++++- .../backoffice/src/app/schedules/page.tsx | 12 +++++++++++- .../backoffice/src/app/seats/page.tsx | 11 ++++++++++- .../backoffice/src/app/stations/page.tsx | 12 +++++++++++- .../backoffice/src/app/trains/page.tsx | 12 +++++++++++- .../backoffice/src/components/layout/Sidebar.tsx | 14 +++++++------- 8 files changed, 83 insertions(+), 14 deletions(-) diff --git a/apps/edr-passenger-web/backoffice/src/app/classes/page.tsx b/apps/edr-passenger-web/backoffice/src/app/classes/page.tsx index af2cab29b..ed6f71acb 100644 --- a/apps/edr-passenger-web/backoffice/src/app/classes/page.tsx +++ b/apps/edr-passenger-web/backoffice/src/app/classes/page.tsx @@ -10,8 +10,10 @@ import Modal from '@/components/ui/Modal'; import ConfirmDialog from '@/components/ui/ConfirmDialog'; import { seatClassesApi, apiClient } from '@/lib/api'; import { formatCurrency } from '@/lib/utils'; +import { PermissionGuard } from '@/components/layout/PermissionGuard'; +import { PERMS } from '@/lib/permissions'; -export default function ClassesPage() { +function ClassesPageContent() { const [filters, setFilters] = useState({ search: '' }); const [showModal, setShowModal] = useState(false); const [editingClass, setEditingClass] = useState(null); @@ -352,3 +354,11 @@ export default function ClassesPage() {

); } + +export default function ClassesPage() { + return ( + + + + ); +} diff --git a/apps/edr-passenger-web/backoffice/src/app/coaches/page.tsx b/apps/edr-passenger-web/backoffice/src/app/coaches/page.tsx index acb0deefa..408ebb352 100644 --- a/apps/edr-passenger-web/backoffice/src/app/coaches/page.tsx +++ b/apps/edr-passenger-web/backoffice/src/app/coaches/page.tsx @@ -10,6 +10,8 @@ import ConfirmDialog from '@/components/ui/ConfirmDialog'; import { fleetApi, apiClient } from '@/lib/api'; import Pagination from '@/components/ui/Pagination'; import { usePagination } from '@/lib/use-pagination'; +import { PermissionGuard } from '@/components/layout/PermissionGuard'; +import { PERMS } from '@/lib/permissions'; type Tab = 'types' | 'coaches' | 'utilization'; @@ -142,7 +144,7 @@ const renderBedVisualization = (coach: any) => { ); }; -export default function CoachesPage() { +function CoachesPageContent() { const [activeTab, setActiveTab] = useState('coaches'); const [search, setSearch] = useState(''); const [showModal, setShowModal] = useState(false); @@ -929,3 +931,11 @@ export default function CoachesPage() { ); } + +export default function CoachesPage() { + return ( + + + + ); +} diff --git a/apps/edr-passenger-web/backoffice/src/app/routes/page.tsx b/apps/edr-passenger-web/backoffice/src/app/routes/page.tsx index 251d034b1..a44d78546 100644 --- a/apps/edr-passenger-web/backoffice/src/app/routes/page.tsx +++ b/apps/edr-passenger-web/backoffice/src/app/routes/page.tsx @@ -11,6 +11,8 @@ import ConfirmDialog from '@/components/ui/ConfirmDialog'; import { routesApi } from '@/lib/api/routes'; import { stationsApi, fleetApi, routeCoachTemplatesApi } from '@/lib/api'; import { eatLocalToISO, isoToEATLocal } from '@/lib/timezone'; +import { PermissionGuard } from '@/components/layout/PermissionGuard'; +import { PERMS } from '@/lib/permissions'; interface RouteStop { stationId: string; @@ -166,7 +168,7 @@ function RouteCoachesTab({ routes }: { routes: any[] }) { ); } -export default function RoutesPage() { +function RoutesPageContent() { const [activeTab, setActiveTab] = useState('routes'); const [showModal, setShowModal] = useState(false); const [editingRoute, setEditingRoute] = useState(null); @@ -922,3 +924,11 @@ export default function RoutesPage() { ); } + +export default function RoutesPage() { + return ( + + + + ); +} diff --git a/apps/edr-passenger-web/backoffice/src/app/schedules/page.tsx b/apps/edr-passenger-web/backoffice/src/app/schedules/page.tsx index 35d0290ea..7738f4b71 100644 --- a/apps/edr-passenger-web/backoffice/src/app/schedules/page.tsx +++ b/apps/edr-passenger-web/backoffice/src/app/schedules/page.tsx @@ -14,6 +14,8 @@ import { usePagination } from '@/lib/use-pagination'; import { formatDateTime } from '@/lib/utils'; import { eatLocalToISO, isoToEATLocal } from '@/lib/timezone'; import DateTimePicker from '@/components/ui/DateTimePicker'; +import { PermissionGuard } from '@/components/layout/PermissionGuard'; +import { PERMS } from '@/lib/permissions'; interface Schedule { id: string; @@ -52,7 +54,7 @@ interface Coach { coachType?: { name: string }; } -export default function SchedulesPage() { +function SchedulesPageContent() { const [showModal, setShowModal] = useState(false); const [showAddModal, setShowAddModal] = useState(false); const [showEditModal, setShowEditModal] = useState(false); @@ -1248,3 +1250,11 @@ export default function SchedulesPage() { ); } + +export default function SchedulesPage() { + return ( + + + + ); +} diff --git a/apps/edr-passenger-web/backoffice/src/app/seats/page.tsx b/apps/edr-passenger-web/backoffice/src/app/seats/page.tsx index c2d3ef2db..86d61eff0 100644 --- a/apps/edr-passenger-web/backoffice/src/app/seats/page.tsx +++ b/apps/edr-passenger-web/backoffice/src/app/seats/page.tsx @@ -6,6 +6,7 @@ import { seatsApi, schedulesApi, fleetApi, routeCoachTemplatesApi, bookingsApi } import { routesApi } from '@/lib/api/routes'; import { usePermissionStrict } from '@/lib/use-permission'; import { PERMS } from '@/lib/permissions'; +import { PermissionGuard } from '@/components/layout/PermissionGuard'; import Modal from '@/components/ui/Modal'; import ActionButton from '@/components/ui/ActionButton' import { Armchair, Lock, Unlock, Bed, X, RotateCcw, ChevronDown, Train, Wrench, Ticket as TicketIcon } from 'lucide-react'; @@ -15,7 +16,7 @@ import { SeatBlockReasonCategory, } from '@edr/types'; -export default function SeatsPage() { +function SeatsPageContent() { const [activeTab, setActiveTab] = useState<'route' | 'schedule'>('route'); const [selectedSchedule, setSelectedSchedule] = useState(''); const [selectedRoute, setSelectedRoute] = useState(''); @@ -1491,3 +1492,11 @@ function SeatIcon({ ); } + +export default function SeatsPage() { + return ( + + + + ); +} diff --git a/apps/edr-passenger-web/backoffice/src/app/stations/page.tsx b/apps/edr-passenger-web/backoffice/src/app/stations/page.tsx index 032a978a4..420bc3434 100644 --- a/apps/edr-passenger-web/backoffice/src/app/stations/page.tsx +++ b/apps/edr-passenger-web/backoffice/src/app/stations/page.tsx @@ -11,8 +11,10 @@ import ConfirmDialog from '@/components/ui/ConfirmDialog'; import { stationsApi } from '@/lib/api'; import Pagination from '@/components/ui/Pagination'; import { usePagination } from '@/lib/use-pagination'; +import { PermissionGuard } from '@/components/layout/PermissionGuard'; +import { PERMS } from '@/lib/permissions'; -export default function StationsPage() { +function StationsPageContent() { const [filters, setFilters] = useState({ search: '', country: '', operational: '' }); const [showModal, setShowModal] = useState(false); const [editingStation, setEditingStation] = useState(null); @@ -379,3 +381,11 @@ export default function StationsPage() { ); } + +export default function StationsPage() { + return ( + + + + ); +} diff --git a/apps/edr-passenger-web/backoffice/src/app/trains/page.tsx b/apps/edr-passenger-web/backoffice/src/app/trains/page.tsx index 527aebdc7..e1be87ff3 100644 --- a/apps/edr-passenger-web/backoffice/src/app/trains/page.tsx +++ b/apps/edr-passenger-web/backoffice/src/app/trains/page.tsx @@ -13,8 +13,10 @@ import Pagination from '@/components/ui/Pagination'; import { usePagination } from '@/lib/use-pagination'; import { Train as TrainType } from '@/types'; import { formatDate } from '@/lib/utils'; +import { PermissionGuard } from '@/components/layout/PermissionGuard'; +import { PERMS } from '@/lib/permissions'; -export default function TrainsPage() { +function TrainsPageContent() { const [showModal, setShowModal] = useState(false); const [editingTrain, setEditingTrain] = useState(null); const [search, setSearch] = useState(''); @@ -366,3 +368,11 @@ export default function TrainsPage() { ); } + +export default function TrainsPage() { + return ( + + + + ); +} diff --git a/apps/edr-passenger-web/backoffice/src/components/layout/Sidebar.tsx b/apps/edr-passenger-web/backoffice/src/components/layout/Sidebar.tsx index 616488917..1f33c417e 100644 --- a/apps/edr-passenger-web/backoffice/src/components/layout/Sidebar.tsx +++ b/apps/edr-passenger-web/backoffice/src/components/layout/Sidebar.tsx @@ -81,13 +81,13 @@ const navigationSections: { title: string; items: NavItem[] }[] = [ { title: 'Master Data', items: [ - { name: 'Stations', href: '/stations', icon: MapPin }, - { name: 'Trains', href: '/trains', icon: Train }, - { name: 'Coaches', href: '/coaches', icon: Grid3x3 }, - { name: 'Seats', href: '/seats', icon: Armchair }, - { name: 'Classes', href: '/classes', icon: Settings }, - { name: 'Routes', href: '/routes', icon: Route }, - { name: 'Schedules', href: '/schedules', icon: Calendar }, + { name: 'Stations', href: '/stations', icon: MapPin, permission: PERMS.stations.view }, + { name: 'Trains', href: '/trains', icon: Train, permission: PERMS.trains.view }, + { name: 'Coaches', href: '/coaches', icon: Grid3x3, permission: PERMS.coaches.view }, + { name: 'Seats', href: '/seats', icon: Armchair, permission: PERMS.seats.view }, + { name: 'Classes', href: '/classes', icon: Settings, permission: PERMS.classes.view }, + { name: 'Routes', href: '/routes', icon: Route, permission: PERMS.routes.view }, + { name: 'Schedules', href: '/schedules', icon: Calendar, permission: PERMS.schedules.view }, ] }, { From fa16087a4a373ad1c5522b7e119fbcb47b376c8a Mon Sep 17 00:00:00 2001 From: Abubeker Yasin Date: Mon, 17 Aug 2026 15:33:43 +0300 Subject: [PATCH 09/14] fix: ( excess-baggage ) pay in the selected method's currency and record settlement --- .../excess-baggage-currency.spec.ts | 451 ++++++++++++++++++ .../excess-baggage.controller.ts | 48 +- .../excess-baggage/excess-baggage.dto.ts | 29 +- .../excess-baggage/excess-baggage.module.ts | 9 +- .../excess-baggage/excess-baggage.service.ts | 235 ++++++++- .../payments/internal-payments.controller.ts | 7 + .../modules/payments/payments.service.spec.ts | 196 ++++++++ .../src/modules/payments/payments.service.ts | 142 ++++++ .../test/money-integrity.e2e-spec.ts | 12 +- .../app/excess-baggage/pay/[token]/page.tsx | 421 +++++++++++++++- 10 files changed, 1522 insertions(+), 28 deletions(-) create mode 100644 apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage-currency.spec.ts diff --git a/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage-currency.spec.ts b/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage-currency.spec.ts new file mode 100644 index 000000000..abc79c798 --- /dev/null +++ b/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage-currency.spec.ts @@ -0,0 +1,451 @@ +import { BadRequestException } from '@nestjs/common'; +import { PaymentMethodType } from '@prisma/client'; +import { ExcessBaggageService } from './excess-baggage.service'; +import { CurrencyService } from '../currency/currency.service'; + +/** + * An excess baggage charge is always booked in ETB, but each payment method settles in its own + * currency and the payment microservice forwards whatever it is given straight to the gateway. + * These cover the ETB→settlement conversion that has to happen here — and that the quote shown to + * the payer is computed from the same code path as the amount actually charged. + */ +describe('ExcessBaggageService — charge currency', () => { + const CHARGE_ID = 'charge-1'; + const TOKEN = 'tok-1'; + + // 350.00 ETB owed for 7kg at 50.00 ETB/kg. + const charge = { + id: CHARGE_ID, + totalMinor: 35_000, + currency: 'ETB', + status: 'PENDING', + expiresAt: new Date(Date.now() + 10 * 60 * 1000), + booking: { bookingRef: 'BAG-001', scheduleId: 'sched-1' }, + }; + + let prisma: Record; + let paymentClient: { + initiate: jest.Mock; + getIntentByReference: jest.Mock; + confirmOtp: jest.Mock; + }; + let service: ExcessBaggageService; + + const build = (rate?: { rate: number }) => { + prisma = { + excessBaggageCharge: { + findUnique: jest.fn().mockResolvedValue(charge), + update: jest.fn().mockResolvedValue({ ...charge, status: 'PAID' }), + }, + paymentMethod: { findUnique: jest.fn() }, + currencyExchangeRate: { + findFirst: jest.fn().mockResolvedValue(rate ?? null), + }, + }; + paymentClient = { + initiate: jest.fn().mockResolvedValue({ + status: 'REQUIRES_ACTION', + clientAction: { type: 'REDIRECT', url: 'https://gateway.test/pay' }, + merchantOrderId: 'MO-1', + }), + getIntentByReference: jest.fn(), + confirmOtp: jest.fn(), + }; + service = new ExcessBaggageService( + prisma as any, + { log: jest.fn() } as any, // auditService + new CurrencyService(prisma as any), + paymentClient as any, + {} as any, // notifications + {} as any, // smsClient + {} as any, // emailClient + ); + }; + + const withMethod = (type: string, currency: string) => + prisma.paymentMethod.findUnique.mockResolvedValue({ type, currency }); + + it('charges an Ethiopian wallet in ETB, unconverted', async () => { + build(); + withMethod(PaymentMethodType.TELEBIRR, 'ETB'); + + const quote = await service.quoteAmount(TOKEN, PaymentMethodType.TELEBIRR); + + expect(quote).toMatchObject({ currency: 'ETB', amount: 350 }); + expect(prisma.currencyExchangeRate.findFirst).not.toHaveBeenCalled(); + }); + + it('converts to DJF for Waafi and rounds to whole francs', async () => { + build({ rate: 3.2 }); // 1 ETB = 3.2 DJF + withMethod(PaymentMethodType.WAAFI, 'DJF'); + + const quote = await service.quoteAmount(TOKEN, PaymentMethodType.WAAFI); + + // 350.00 ETB × 3.2 = 1120 DJF — DJF has no minor unit. + expect(quote).toMatchObject({ currency: 'DJF', amount: 1120 }); + expect(Number.isInteger(quote.amount)).toBe(true); + }); + + it('sends the provider the converted amount and its own currency, not the stored ETB total', async () => { + build({ rate: 3.2 }); + withMethod(PaymentMethodType.WAAFI, 'DJF'); + + await service.initiatePayment(TOKEN, { + method: PaymentMethodType.WAAFI, + platform: 'web', + } as any); + + expect(paymentClient.initiate).toHaveBeenCalledWith( + expect.objectContaining({ + referenceType: 'EXCESS_BAGGAGE', + referenceId: CHARGE_ID, + amountMinor: 1120, + currency: 'DJF', + provider: PaymentMethodType.WAAFI, + }), + ); + }); + + it('quotes and charges the same figure for the same method', async () => { + build({ rate: 0.0175 }); // 1 ETB = 0.0175 USD + withMethod(PaymentMethodType.CARD, 'USD'); + + const quote = await service.quoteAmount(TOKEN, PaymentMethodType.CARD); + await service.initiatePayment(TOKEN, { + method: PaymentMethodType.CARD, + platform: 'web', + } as any); + + const sent = paymentClient.initiate.mock.calls[0][0]; + expect(quote.amount).toBe(sent.amountMinor); + expect(quote.currency).toBe(sent.currency); + expect(sent.amountMinor).toBe(6.13); // 350 × 0.0175 = 6.125 → 6.13 USD + }); + + it('forces ETB for CBE_BILL, which settles ETB only', async () => { + build({ rate: 3.2 }); + withMethod(PaymentMethodType.CBE_BILL, 'DJF'); // misconfigured row must not win + + const quote = await service.quoteAmount(TOKEN, PaymentMethodType.CBE_BILL); + + expect(quote).toMatchObject({ currency: 'ETB', amount: 350 }); + }); + + it('refuses WALLET, which has no excess-baggage path', async () => { + build(); + + await expect( + service.quoteAmount(TOKEN, PaymentMethodType.WALLET), + ).rejects.toBeInstanceOf(BadRequestException); + await expect( + service.initiatePayment(TOKEN, { + method: PaymentMethodType.WALLET, + } as any), + ).rejects.toBeInstanceOf(BadRequestException); + expect(paymentClient.initiate).not.toHaveBeenCalled(); + }); + + it('fails closed when no exchange rate is configured — never charges at parity', async () => { + build(); // no rate rows at all + withMethod(PaymentMethodType.WAAFI, 'DJF'); + + await expect( + service.initiatePayment(TOKEN, { + method: PaymentMethodType.WAAFI, + } as any), + ).rejects.toBeInstanceOf(BadRequestException); + expect(paymentClient.initiate).not.toHaveBeenCalled(); + }); +}); + +/** + * CAC Bank is an OTP debit: the bank SMSes a one-time password to a mobile number it must be given + * at initiate, and the payment only settles once that password is submitted back. + */ +describe('ExcessBaggageService — CAC Bank OTP debit', () => { + const CHARGE_ID = 'charge-1'; + const TOKEN = 'tok-1'; + + const charge = { + id: CHARGE_ID, + totalMinor: 25_000, + currency: 'ETB', + status: 'PENDING', + expiresAt: new Date(Date.now() + 10 * 60 * 1000), + booking: { bookingRef: 'BAG-001', scheduleId: 'sched-1' }, + }; + + let prisma: Record; + let paymentClient: { + initiate: jest.Mock; + getIntentByReference: jest.Mock; + confirmOtp: jest.Mock; + }; + let service: ExcessBaggageService; + + beforeEach(() => { + prisma = { + excessBaggageCharge: { + findUnique: jest.fn().mockResolvedValue(charge), + update: jest.fn().mockResolvedValue({ ...charge, status: 'PAID' }), + }, + paymentMethod: { + findUnique: jest + .fn() + .mockResolvedValue({ type: 'CAC_BANK', currency: 'DJF' }), + }, + currencyExchangeRate: { + findFirst: jest.fn().mockResolvedValue({ rate: 3.25 }), + }, + }; + paymentClient = { + initiate: jest.fn().mockResolvedValue({ + intentId: 'intent-1', + status: 'REQUIRES_ACTION', + clientAction: { + type: 'COLLECT_OTP', + message: 'Enter the OTP sent to 77****56', + }, + merchantOrderId: 'MO-1', + }), + getIntentByReference: jest + .fn() + .mockResolvedValue({ intentId: 'intent-1', status: 'REQUIRES_ACTION' }), + confirmOtp: jest.fn().mockResolvedValue({ + intentId: 'intent-1', + status: 'SUCCEEDED', + providerTxnId: 'CAC-TXN-9', + }), + }; + service = new ExcessBaggageService( + prisma as any, + { log: jest.fn() } as any, + new CurrencyService(prisma as any), + paymentClient as any, + {} as any, + {} as any, + {} as any, + ); + }); + + it('rejects initiate without a payer mobile — the bank has nowhere to send the OTP', async () => { + await expect( + service.initiatePayment(TOKEN, { + method: PaymentMethodType.CAC_BANK, + platform: 'web', + } as any), + ).rejects.toBeInstanceOf(BadRequestException); + expect(paymentClient.initiate).not.toHaveBeenCalled(); + }); + + it('forwards the payer mobile and returns the OTP client action', async () => { + const result = await service.initiatePayment(TOKEN, { + method: PaymentMethodType.CAC_BANK, + platform: 'web', + payerAccount: ' 77123456 ', + } as any); + + expect(paymentClient.initiate).toHaveBeenCalledWith( + expect.objectContaining({ + payerAccount: '77123456', // trimmed + currency: 'DJF', + amountMinor: 813, // 250.00 ETB × 3.25, whole francs + }), + ); + expect(result.clientAction).toMatchObject({ type: 'COLLECT_OTP' }); + }); + + it('submits the OTP against the charge’s active intent and marks it paid', async () => { + const result = await service.confirmOtp(TOKEN, '4530'); + + expect(paymentClient.getIntentByReference).toHaveBeenCalledWith( + 'EXCESS_BAGGAGE', + CHARGE_ID, + ); + expect(paymentClient.confirmOtp).toHaveBeenCalledWith('intent-1', '4530'); + expect(prisma.excessBaggageCharge.update).toHaveBeenCalledWith( + expect.objectContaining({ + where: { id: CHARGE_ID }, + data: expect.objectContaining({ status: 'PAID' }), + }), + ); + expect(result).toMatchObject({ status: 'SUCCEEDED', alreadyPaid: false }); + }); + + it('leaves the charge unpaid when the OTP does not settle', async () => { + paymentClient.confirmOtp.mockResolvedValue({ + intentId: 'intent-1', + status: 'REQUIRES_ACTION', + }); + + const result = await service.confirmOtp(TOKEN, '0000'); + + expect(prisma.excessBaggageCharge.update).not.toHaveBeenCalled(); + expect(result).toMatchObject({ status: 'REQUIRES_ACTION' }); + }); + + it('confirms an OTP even after the link TTL lapsed — the debit is already in flight', async () => { + prisma.excessBaggageCharge.findUnique.mockResolvedValue({ + ...charge, + expiresAt: new Date(Date.now() - 60_000), + }); + + await expect(service.confirmOtp(TOKEN, '4530')).resolves.toMatchObject({ + status: 'SUCCEEDED', + }); + }); + + it('is idempotent once the charge is already paid', async () => { + prisma.excessBaggageCharge.findUnique.mockResolvedValue({ + ...charge, + status: 'PAID', + }); + + const result = await service.confirmOtp(TOKEN, '4530'); + + expect(result).toMatchObject({ alreadyPaid: true }); + expect(paymentClient.confirmOtp).not.toHaveBeenCalled(); + }); +}); + +/** + * CBE bill payment is inbound-only: no provider session is opened, a bill reference is minted and + * the payer settles it at a branch/app hours later. The expiry handed to the payment service is + * therefore the charge's own deadline, never the 30-minute link TTL — a short one would have the + * reconciliation sweep kill the intent within the hour (CBE plan §6.4). + */ +describe('ExcessBaggageService — CBE bill', () => { + const CHARGE_ID = 'charge-1'; + const TOKEN = 'tok-1'; + const THIRTY_MIN = 30 * 60 * 1000; + + let prisma: Record; + let paymentClient: { initiate: jest.Mock }; + let service: ExcessBaggageService; + let charge: any; + + beforeEach(() => { + charge = { + id: CHARGE_ID, + bookingId: 'booking-1', + totalMinor: 25_000, + currency: 'ETB', + status: 'PENDING', + // A freshly created charge: the short browser-session TTL. + expiresAt: new Date(Date.now() + THIRTY_MIN), + booking: { bookingRef: 'BAG-001' }, + }; + prisma = { + excessBaggageCharge: { + findUnique: jest.fn().mockResolvedValue(charge), + update: jest.fn().mockResolvedValue(charge), + }, + booking: { + findUnique: jest.fn().mockResolvedValue({ + seats: [{ leg: 1, passengerName: 'Abebe Kebede' }], + passenger: { user: { fullName: 'Account Holder' } }, + }), + }, + paymentMethod: { + findUnique: jest + .fn() + .mockResolvedValue({ type: 'CBE_BILL', currency: 'ETB' }), + }, + currencyExchangeRate: { findFirst: jest.fn().mockResolvedValue(null) }, + }; + paymentClient = { + initiate: jest.fn().mockResolvedValue({ + intentId: 'intent-1', + status: 'REQUIRES_ACTION', + clientAction: { + type: 'SHOW_BILL_REFERENCE', + billReference: '900123456', + }, + merchantOrderId: 'MO-1', + }), + }; + service = new ExcessBaggageService( + prisma as any, + { log: jest.fn() } as any, + new CurrencyService(prisma as any), + paymentClient as any, + {} as any, + {} as any, + {} as any, + ); + }); + + const initiate = () => + service.initiatePayment(TOKEN, { + method: PaymentMethodType.CBE_BILL, + platform: 'web', + } as any); + + it('extends the charge deadline past the 30-minute link TTL', async () => { + await initiate(); + + expect(prisma.excessBaggageCharge.update).toHaveBeenCalledWith( + expect.objectContaining({ + where: { id: CHARGE_ID }, + data: expect.objectContaining({ expiresAt: expect.any(Date) }), + }), + ); + const written = + prisma.excessBaggageCharge.update.mock.calls[0][0].data.expiresAt; + // Comfortably beyond the session TTL — a payer has to reach a branch. + expect(written.getTime()).toBeGreaterThan(Date.now() + 2 * THIRTY_MIN); + }); + + it('hands the payment service that deadline as the intent expiry, in ETB', async () => { + await initiate(); + + const sent = paymentClient.initiate.mock.calls[0][0]; + expect(sent.currency).toBe('ETB'); + expect(sent.amountMinor).toBe(250); + expect(new Date(sent.expiresAt).getTime()).toBeGreaterThan( + Date.now() + 2 * THIRTY_MIN, + ); + }); + + it('sends the lead passenger as Full_Name, which CBE requires', async () => { + await initiate(); + + expect(paymentClient.initiate.mock.calls[0][0].payerName).toBe( + 'Abebe Kebede', + ); + }); + + it('never shortens a deadline the payer already has', async () => { + const farFuture = new Date(Date.now() + 90 * 60 * 60 * 1000); + charge.expiresAt = farFuture; + + await initiate(); + + expect(prisma.excessBaggageCharge.update).not.toHaveBeenCalled(); + expect(paymentClient.initiate.mock.calls[0][0].expiresAt).toBe( + farFuture.toISOString(), + ); + }); + + it('returns the bill reference to the caller', async () => { + const result = await initiate(); + expect(result.clientAction).toMatchObject({ + type: 'SHOW_BILL_REFERENCE', + billReference: '900123456', + }); + }); + + it('reports a paid charge through getStatus without the payability gate', async () => { + prisma.excessBaggageCharge.findUnique.mockResolvedValue({ + ...charge, + status: 'PAID', + paidAt: new Date(), + }); + + // getByToken would throw "already paid" here; the poll must simply report it. + await expect(service.getStatus(TOKEN)).resolves.toMatchObject({ + status: 'PAID', + paid: true, + }); + }); +}); diff --git a/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.controller.ts b/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.controller.ts index 40a44f36b..b246566e4 100644 --- a/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.controller.ts +++ b/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.controller.ts @@ -1,11 +1,12 @@ import { Body, Controller, Delete, Get, Param, Patch, Post, Query, Request, UseGuards, SetMetadata } from '@nestjs/common'; -import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger'; +import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger'; import { IsInt, IsOptional, IsPositive, IsString } from 'class-validator'; import { ExcessBaggageService } from './excess-baggage.service'; import { LogExcessBaggageDto, WaiveChargeDto, InitiateExcessPaymentDto, + ConfirmExcessOtpDto, } from './excess-baggage.dto'; import { JwtGuard as IamJwtGuard } from '@tria-plc/api-common/modules/auth/services/jwt.guard'; import { PassengerAdmin } from '../../common/passenger-guards'; @@ -118,6 +119,37 @@ export class ExcessBaggagePublicController { return this.service.getByToken(token); } + @Get('pay/:token/amount') + @ApiOperation({ + summary: 'Quote the charge in a payment method’s settlement currency', + description: + 'Returns what the given method would debit, converted from the charge’s stored ETB total ' + + 'to that method’s settlement currency (WAAFI/DMONEY settle in DJF, CARD in USD, Ethiopian ' + + 'wallets in ETB) at the latest exchange rate. The pay page quotes this before the payer ' + + 'commits; initiating a payment recomputes it identically.', + }) + @ApiQuery({ + name: 'method', + required: true, + example: 'WAAFI', + description: 'Payment method type the payer has selected', + }) + quoteAmount(@Param('token') token: string, @Query('method') method: string) { + return this.service.quoteAmount(token, method); + } + + @Get('pay/:token/status') + @ApiOperation({ + summary: 'Poll the charge’s settlement status (public)', + description: + 'Reports the charge’s current status without the payability gate on GET /pay/:token, so a ' + + 'page can watch for settlement. Used while a CBE bill is outstanding and after a redirect ' + + 'payment returns — both settle server-side, out of band from the browser.', + }) + getStatus(@Param('token') token: string) { + return this.service.getStatus(token); + } + @Post('pay/:token/initiate') @ApiOperation({ summary: 'Passenger initiates payment for excess baggage charge' }) initiatePayment( @@ -126,4 +158,18 @@ export class ExcessBaggagePublicController { ) { return this.service.initiatePayment(token, dto); } + + @Post('pay/:token/confirm') + @ApiOperation({ + summary: 'Confirm an OTP-debit excess baggage payment (CAC Bank)', + description: + 'Submits the one-time password the payer received by SMS. A wrong or expired OTP returns ' + + '400 and the payment stays open for retry.', + }) + confirmOtp( + @Param('token') token: string, + @Body() dto: ConfirmExcessOtpDto, + ) { + return this.service.confirmOtp(token, dto.otp); + } } diff --git a/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.dto.ts b/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.dto.ts index df0abd8be..4b06e906e 100644 --- a/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.dto.ts +++ b/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.dto.ts @@ -20,7 +20,34 @@ export class WaiveChargeDto { } export class InitiateExcessPaymentDto { - @ApiProperty({ enum: ['TELEBIRR', 'CBE_BIRR', 'EBIRR', 'WAAFI', 'DMONEY', 'CARD'] }) + @ApiProperty({ + enum: [ + 'TELEBIRR', + 'CBE_BIRR', + 'EBIRR', + 'WAAFI', + 'DMONEY', + 'CARD', + 'CAC_BANK', + 'CBE_BILL', + ], + }) @IsString() method: string; @ApiPropertyOptional({ enum: ['web', 'mobile'] }) @IsOptional() platform?: string; + @ApiPropertyOptional({ + description: + 'Payer account / mobile number. Required for the push-debit methods: CAC_BANK (the bank ' + + 'SMSes a one-time password to this number) and EBIRR (the wallet pushes a USSD PIN prompt ' + + 'to it). Normalised server-side by the payment service.', + example: '77123456', + }) + @IsOptional() @IsString() payerAccount?: string; +} + +export class ConfirmExcessOtpDto { + @ApiProperty({ + description: 'One-time password the payer received by SMS (CAC Bank).', + example: '4530', + }) + @IsString() otp: string; } diff --git a/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.module.ts b/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.module.ts index e734d4fb4..e9c648ca8 100644 --- a/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.module.ts +++ b/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.module.ts @@ -6,11 +6,18 @@ import { ExcessBaggagePublicController, } from './excess-baggage.controller'; import { PaymentsModule } from '../payments/payments.module'; +import { CurrencyModule } from '../currency/currency.module'; import { NotificationsModule } from '../notifications/notifications.module'; import { AuditModule } from '../../common/audit.module'; @Module({ - imports: [HttpModule, PaymentsModule, NotificationsModule, AuditModule], + imports: [ + HttpModule, + PaymentsModule, + CurrencyModule, + NotificationsModule, + AuditModule, + ], controllers: [ExcessBaggageAgentController, ExcessBaggagePublicController], providers: [ExcessBaggageService], exports: [ExcessBaggageService], diff --git a/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.service.ts b/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.service.ts index 32fc06c13..d70c823e5 100644 --- a/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.service.ts +++ b/apps/edr-passenger-api/src/modules/excess-baggage/excess-baggage.service.ts @@ -6,6 +6,7 @@ import { } from '@nestjs/common'; import { PrismaService } from '../../common/prisma.service'; import { AuditService } from '../../common/audit.service'; +import { CurrencyService } from '../currency/currency.service'; import { PaymentClientService } from '../payments/payment-client.service'; import { NotificationsService } from '../notifications/notifications.service'; import { SmsClientService } from '../notifications/sms-client.service'; @@ -25,6 +26,41 @@ import { PaymentMethodType, PaymentIntentStatus } from '@prisma/client'; const CHARGE_TTL_MS = 30 * 60 * 1000; // 30 minutes +/** + * WALLET is an internal balance debit handled entirely inside this app (PaymentsService + * .initiateWalletPayment) — it is not a provider and the payment microservice rejects it as one. + * Excess baggage has no wallet path, so it is refused up front with a message a payer can act on + * rather than a 502 from the gateway layer. + */ +const UNSUPPORTED_METHODS = new Set([PaymentMethodType.WALLET]); + +/** + * Push-debit methods charge an account we must be told up front — CAC Bank SMSes a one-time + * password to it, eBirr pushes a USSD PIN prompt to it. Neither opens a hosted page that could + * collect the number later, so initiate is rejected without it (mirrors PaymentsService). + */ +const METHODS_REQUIRING_PAYER_ACCOUNT = new Set([ + PaymentMethodType.CAC_BANK, + PaymentMethodType.EBIRR, +]); + +/** + * How long an excess baggage charge stays payable once a CBE bill has been issued for it. + * + * The 30-minute link TTL is a browser-session window: it assumes the payer is sitting in front of + * the page. A CBE bill is the opposite — the payer walks to a branch, or opens CBE Birr later, and + * the bill reference may already be written on a slip of paper. Handing the payment service a + * 30-minute `expiresAt` would also make the reconciliation sweep expire the intent and emit + * payment.failed within the hour (CBE_IMPLEMENTATION_PLAN.md §6.4 calls this the single most + * important detail of the integration). + * + * So issuing a bill EXTENDS the charge's own deadline to this window. `charge.expiresAt` stays the + * single source of truth for both the pay link and the bill. + */ +const CBE_BILL_WINDOW_HOURS = Number( + process.env.EXCESS_BAGGAGE_CBE_BILL_HOURS ?? 24, +); + @Injectable() export class ExcessBaggageService { private readonly logger = new Logger(ExcessBaggageService.name); @@ -32,6 +68,7 @@ export class ExcessBaggageService { constructor( private prisma: PrismaService, private auditService: AuditService, + private currencyService: CurrencyService, private paymentClient: PaymentClientService, private notifications: NotificationsService, private smsClient: SmsClientService, @@ -165,21 +202,103 @@ export class ExcessBaggageService { return charge; } + /** + * What the payer is actually charged when paying this charge with `method`. + * + * The charge itself is always booked in ETB (`ExcessBaggageCharge.currency` defaults to ETB and + * nothing overrides it), but the selected method settles in its own currency — WAAFI/DMONEY in + * DJF, CARD in USD, the Ethiopian wallets in ETB — recorded on the PaymentMethod row. The payment + * microservice is currency-agnostic and hands whatever it is given straight to the gateway + * verbatim, so the ETB→settlement conversion has to happen here or the provider is asked to debit + * an ETB number labelled as its own currency. + * + * Both the quote shown to the payer and the amount sent to the provider come through this one + * method, so the price on the button and the price debited cannot drift apart. + */ + private async resolveChargeAmount( + charge: { totalMinor: number; currency: string }, + method: string, + ): Promise<{ amount: number; currency: string }> { + if (UNSUPPORTED_METHODS.has(method)) { + throw new BadRequestException( + `${method} is not available for excess baggage payments`, + ); + } + + const paymentMethod = await this.prisma.paymentMethod.findUnique({ + where: { type: method as PaymentMethodType }, + }); + // CBE settles ETB only (docs/cbe/CBE_IMPLEMENTATION_PLAN.md D8) — never converted. Every other + // method charges in its configured settlement currency, falling back to the charge's own. + const chargeCurrency = + method === PaymentMethodType.CBE_BILL + ? 'ETB' + : (paymentMethod?.currency ?? charge.currency).toUpperCase(); + + // Applies the target currency's own precision — DJF rounds to whole francs, ETB/USD to cents. + const amount = await this.currencyService.convertMinorToChargeMajor( + charge.totalMinor, + charge.currency, + chargeCurrency, + ); + return { amount, currency: chargeCurrency }; + } + + /** + * Price quote for the pay page: what `method` would debit, in that method's settlement currency. + * The payer sees this before committing, and `initiatePayment` recomputes it the same way. + */ + async quoteAmount(token: string, method: string) { + const charge = await this.getByToken(token); + const { amount, currency } = await this.resolveChargeAmount(charge, method); + return { chargeId: charge.id, method, currency, amount }; + } + async initiatePayment(token: string, dto: InitiateExcessPaymentDto) { const charge = await this.getByToken(token); + if ( + METHODS_REQUIRING_PAYER_ACCOUNT.has(dto.method) && + !dto.payerAccount?.trim() + ) { + throw new BadRequestException( + `payerAccount (mobile number) is required for ${dto.method}`, + ); + } + const portalUrl = process.env.PORTAL_URL ?? 'http://localhost:5174'; const returnUrl = `${portalUrl}/excess-baggage/pay/${token}/result`; + const { amount, currency } = await this.resolveChargeAmount( + charge, + dto.method, + ); + + // CBE_BILL is inbound-only: no provider session is opened, the bill simply sits in CBE's + // system until someone pays it. It therefore needs a real deadline and a payer name (Full_Name + // is mandatory in CBE's envelope) rather than the redirect flow's session semantics. + let payerName: string | undefined; + let expiresAt: string | undefined; + if (dto.method === PaymentMethodType.CBE_BILL) { + const deadline = await this.extendForCbeBill(charge); + expiresAt = deadline.toISOString(); + payerName = (await this.resolvePayerName(charge.bookingId)) ?? undefined; + } + const snapshot = await this.paymentClient.initiate({ service: PaymentServiceEnum.PASSENGER, referenceType: 'EXCESS_BAGGAGE' as PaymentReferenceType, referenceId: charge.id, orderRef: `EXB-${charge.id.substring(0, 8).toUpperCase()}`, - amountMinor: charge.totalMinor / 100, - currency: charge.currency, + // `amountMinor` is the contract's name but its value is MAJOR units — the provider layer + // charges it verbatim at the currency's own precision (see PaymentIntentSnapshot). + amountMinor: amount, + currency, provider: dto.method as unknown as ProviderMethod, platform: dto.platform as any, + payerAccount: dto.payerAccount?.trim() || undefined, + payerName, + expiresAt, returnUrl, failureUrl: returnUrl, }); @@ -196,6 +315,118 @@ export class ExcessBaggageService { }; } + /** + * Pushes the charge's deadline out to the CBE bill window and returns it. Only ever extends — + * a charge that already has longer left (a re-issued bill, an agent's resend) keeps it, so + * re-initiating a bill can never shorten a window the payer was already given. + */ + private async extendForCbeBill(charge: { + id: string; + expiresAt: Date; + }): Promise { + const target = new Date(Date.now() + CBE_BILL_WINDOW_HOURS * 60 * 60 * 1000); + if (charge.expiresAt >= target) return charge.expiresAt; + + await this.prisma.excessBaggageCharge.update({ + where: { id: charge.id }, + data: { expiresAt: target }, + }); + this.logger.log( + `charge ${charge.id}: expiry extended to ${target.toISOString()} for CBE bill`, + ); + return target; + } + + /** + * Full_Name for CBE's confirmation screen — mandatory in its envelope. The passenger the + * baggage belongs to: lead traveller on the booking, falling back to the account holder. + */ + private async resolvePayerName(bookingId: string): Promise { + const booking = await this.prisma.booking.findUnique({ + where: { id: bookingId }, + include: { seats: true, passenger: { include: { user: true } } }, + }); + if (!booking) return null; + return ( + booking.seats?.find((s: any) => s.leg === 1)?.passengerName ?? + booking.seats?.[0]?.passengerName ?? + booking.passenger?.user?.fullName ?? + null + ); + } + + /** + * Bare status for the pay/result pages to poll. Unlike getByToken this does NOT reject a paid, + * expired or waived charge — the whole point is to report those states. A CBE bill can settle + * long after the payer closed the tab, and the redirect methods only converge when the + * settlement event lands, so the page needs something it can watch. + */ + async getStatus(token: string) { + const charge = await this.prisma.excessBaggageCharge.findUnique({ + where: { paymentToken: token }, + select: { + id: true, + status: true, + paidAt: true, + totalMinor: true, + currency: true, + expiresAt: true, + }, + }); + if (!charge) throw new NotFoundException('Payment link not found'); + return { + chargeId: charge.id, + status: charge.status, + paid: charge.status === 'PAID' || charge.status === 'CASH_COLLECTED', + paidAt: charge.paidAt, + totalMinor: charge.totalMinor, + currency: charge.currency, + expiresAt: charge.expiresAt, + }; + } + + /** + * Submit the one-time password for a COLLECT_OTP provider (CAC Bank). The bank SMSed it to the + * payerAccount given at initiate; this forwards it to the payment service and marks the charge + * paid when the debit settles. A wrong or expired OTP bubbles up as a 400 and the intent stays + * open, so the payer can simply re-enter it. + * + * Deliberately reads the charge directly rather than through getByToken: the bank is already + * holding a debit against this payer, and refusing to submit their OTP because the 30-minute + * link TTL lapsed while they were reading the SMS would strand a payment that is mid-flight. + */ + async confirmOtp(token: string, otp: string) { + const charge = await this.prisma.excessBaggageCharge.findUnique({ + where: { paymentToken: token }, + }); + if (!charge) throw new NotFoundException('Payment link not found'); + if (charge.status === 'PAID' || charge.status === 'CASH_COLLECTED') { + return { chargeId: charge.id, status: 'SUCCEEDED', alreadyPaid: true }; + } + + const snapshot = await this.paymentClient.getIntentByReference( + 'EXCESS_BAGGAGE' as PaymentReferenceType, + charge.id, + ); + if (!snapshot) { + throw new NotFoundException('No active payment to confirm for this charge'); + } + + const confirmed = await this.paymentClient.confirmOtp( + snapshot.intentId, + otp, + ); + if (confirmed.status === ProviderPaymentStatus.SUCCEEDED) { + await this.markPaid(charge.id, confirmed.providerTxnId); + } + + return { + chargeId: charge.id, + status: confirmed.status, + alreadyPaid: false, + }; + } + async markPaid(chargeId: string, providerTxnId?: string) { const charge = await this.prisma.excessBaggageCharge.findUnique({ where: { id: chargeId } }); if (!charge) throw new NotFoundException('Charge not found'); diff --git a/apps/edr-passenger-api/src/modules/payments/internal-payments.controller.ts b/apps/edr-passenger-api/src/modules/payments/internal-payments.controller.ts index df5949bde..be46135a1 100644 --- a/apps/edr-passenger-api/src/modules/payments/internal-payments.controller.ts +++ b/apps/edr-passenger-api/src/modules/payments/internal-payments.controller.ts @@ -8,6 +8,7 @@ import { UseGuards, } from "@nestjs/common"; import { ApiOperation, ApiTags } from "@nestjs/swagger"; +import { PaymentReferenceType } from "@edr/types"; import { ServiceAuthGuard } from "../../common/guards/service-auth.guard"; import { PaymentEventDto, @@ -51,6 +52,12 @@ export class InternalPaymentsController { async billQuery( @Body() request: BillQueryRequestDto, ): Promise { + // Routed on referenceType: the passenger app issues CBE bills for bookings AND for excess + // baggage charges, and they live in different tables. Treating every referenceId as a + // bookingId would report a perfectly payable baggage bill as NOT_FOUND to the teller. + if (request.referenceType === PaymentReferenceType.EXCESS_BAGGAGE) { + return this.paymentsService.billQueryExcessBaggage(request.referenceId); + } return this.paymentsService.billQuery(request.referenceId); } } diff --git a/apps/edr-passenger-api/src/modules/payments/payments.service.spec.ts b/apps/edr-passenger-api/src/modules/payments/payments.service.spec.ts index 9b94053b6..36b062261 100644 --- a/apps/edr-passenger-api/src/modules/payments/payments.service.spec.ts +++ b/apps/edr-passenger-api/src/modules/payments/payments.service.spec.ts @@ -46,6 +46,10 @@ describe("PaymentsService", () => { paymentMethod: { findUnique: jest.fn(), }, + excessBaggageCharge: { + findUnique: jest.fn(), + update: jest.fn(), + }, currencyExchangeRate: { findFirst: jest.fn(), }, @@ -562,4 +566,196 @@ describe("PaymentsService", () => { ); }); }); + + /** + * Excess baggage settles through the same outbox → RabbitMQ path as bookings. Before this + * existed the consumer dropped every EXCESS_BAGGAGE event as "foreign-reference", so a charge + * the payer had genuinely paid stayed PENDING until its TTL flipped it to EXPIRED. + */ + describe("handlePaymentEvent — excess baggage", () => { + const CHARGE_ID = "charge-1"; + + const succeededEvent = (overrides: Record = {}) => + ({ + eventId: "evt-1", + eventType: "payment.succeeded", + service: PaymentServiceEnum.PASSENGER, + referenceType: PaymentReferenceType.EXCESS_BAGGAGE, + referenceId: CHARGE_ID, + amountMinor: 500, + currency: "ETB", + providerTxnId: "TXN-9", + ...overrides, + }) as any; + + it("marks a pending charge PAID", async () => { + mockPrisma.excessBaggageCharge.findUnique.mockResolvedValue({ + id: CHARGE_ID, + status: "PENDING", + }); + + const result = await service.handlePaymentEvent(succeededEvent()); + + expect(mockPrisma.excessBaggageCharge.update).toHaveBeenCalledWith( + expect.objectContaining({ + where: { id: CHARGE_ID }, + data: expect.objectContaining({ status: "PAID" }), + }), + ); + expect(result).toEqual({ processed: true }); + }); + + it("marks an EXPIRED charge PAID — the TTL governs starting a payment, not receiving one", async () => { + mockPrisma.excessBaggageCharge.findUnique.mockResolvedValue({ + id: CHARGE_ID, + status: "EXPIRED", + }); + + await service.handlePaymentEvent(succeededEvent()); + + expect(mockPrisma.excessBaggageCharge.update).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ status: "PAID" }), + }), + ); + }); + + it("does not re-pay an already PAID charge", async () => { + mockPrisma.excessBaggageCharge.findUnique.mockResolvedValue({ + id: CHARGE_ID, + status: "PAID", + }); + + const result = await service.handlePaymentEvent(succeededEvent()); + + expect(mockPrisma.excessBaggageCharge.update).not.toHaveBeenCalled(); + expect(result).toEqual({ processed: true, alreadyFinalized: true }); + }); + + it("accepts a foreign-currency settlement without a short-pay comparison", async () => { + mockPrisma.excessBaggageCharge.findUnique.mockResolvedValue({ + id: CHARGE_ID, + status: "PENDING", + }); + + // 500.00 ETB charge settled as 1625 DJF — numerically unlike the stored total. + await service.handlePaymentEvent( + succeededEvent({ amountMinor: 1625, currency: "DJF" }), + ); + + expect(mockPrisma.excessBaggageCharge.update).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ status: "PAID" }), + }), + ); + }); + + it("acks a failure event without touching the charge", async () => { + const result = await service.handlePaymentEvent( + succeededEvent({ eventType: "payment.failed" }), + ); + + expect(mockPrisma.excessBaggageCharge.update).not.toHaveBeenCalled(); + expect(result).toEqual({ processed: true }); + }); + + it("acks an event for a charge that no longer exists", async () => { + mockPrisma.excessBaggageCharge.findUnique.mockResolvedValue(null); + + const result = await service.handlePaymentEvent(succeededEvent()); + + expect(result).toEqual({ + processed: false, + reason: "charge-not-found", + }); + }); + }); + + /** + * The live hop CBE makes while a teller is on the line, for a baggage bill. This is the + * double-payment guard: anything other than stillPayable=true makes CBE refuse the debit. + */ + describe("billQueryExcessBaggage", () => { + const payable = { + id: "charge-1", + excessWeightKg: 7, + totalMinor: 25_000, + status: "PENDING", + expiresAt: new Date(Date.now() + 60 * 60 * 1000), + booking: { + bookingRef: "BAG-001", + seats: [{ leg: 1, passengerName: "Abebe Kebede" }], + passenger: { user: { fullName: "Account Holder" } }, + }, + }; + + it("reports a pending charge as payable, in ETB, with the passenger name", async () => { + mockPrisma.excessBaggageCharge.findUnique.mockResolvedValue(payable); + + const result = await service.billQueryExcessBaggage("charge-1"); + + expect(result).toMatchObject({ + stillPayable: true, + currency: "ETB", + currentAmountMinor: 250, + payerName: "Abebe Kebede", + }); + expect(result.paymentReason).toContain("BAG-001"); + }); + + it("refuses a charge already paid at the counter in cash", async () => { + mockPrisma.excessBaggageCharge.findUnique.mockResolvedValue({ + ...payable, + status: "CASH_COLLECTED", + }); + + await expect( + service.billQueryExcessBaggage("charge-1"), + ).resolves.toMatchObject({ + stillPayable: false, + reason: "ALREADY_PAID", + }); + }); + + it("refuses a waived charge", async () => { + mockPrisma.excessBaggageCharge.findUnique.mockResolvedValue({ + ...payable, + status: "WAIVED", + }); + + await expect( + service.billQueryExcessBaggage("charge-1"), + ).resolves.toMatchObject({ stillPayable: false, reason: "CANCELLED" }); + }); + + it("refuses a charge whose deadline has passed", async () => { + mockPrisma.excessBaggageCharge.findUnique.mockResolvedValue({ + ...payable, + expiresAt: new Date(Date.now() - 1000), + }); + + await expect( + service.billQueryExcessBaggage("charge-1"), + ).resolves.toMatchObject({ stillPayable: false, reason: "EXPIRED" }); + }); + + it("refuses within the settle margin, so a debit cannot land after expiry", async () => { + mockPrisma.excessBaggageCharge.findUnique.mockResolvedValue({ + ...payable, + expiresAt: new Date(Date.now() + 5_000), // inside the 60s margin + }); + + await expect( + service.billQueryExcessBaggage("charge-1"), + ).resolves.toMatchObject({ stillPayable: false, reason: "EXPIRED" }); + }); + + it("reports NOT_FOUND for a bill whose charge is gone", async () => { + mockPrisma.excessBaggageCharge.findUnique.mockResolvedValue(null); + + await expect( + service.billQueryExcessBaggage("charge-1"), + ).resolves.toEqual({ stillPayable: false, reason: "NOT_FOUND" }); + }); + }); }); diff --git a/apps/edr-passenger-api/src/modules/payments/payments.service.ts b/apps/edr-passenger-api/src/modules/payments/payments.service.ts index 5cd483830..1415c1dcc 100644 --- a/apps/edr-passenger-api/src/modules/payments/payments.service.ts +++ b/apps/edr-passenger-api/src/modules/payments/payments.service.ts @@ -533,6 +533,73 @@ export class PaymentsService { return { ...base, stillPayable: true, reason: null }; } + /** + * Bill-query for an excess baggage charge — the same live "still payable?" hop as bookings, + * against `ExcessBaggageCharge` instead. This is the double-payment guard for baggage bills: + * once the charge is paid, waived or lapsed, CBE is told to refuse the debit. + * + * The charge's own `expiresAt` is the deadline (extended to the CBE bill window when the bill + * was issued), so there is no separate schedule-derived deadline to compute as there is for a + * booking. + */ + async billQueryExcessBaggage( + chargeId: string, + ): Promise { + const charge = await this.prisma.excessBaggageCharge.findUnique({ + where: { id: chargeId }, + include: { + booking: { + include: { seats: true, passenger: { include: { user: true } } }, + }, + }, + }); + // A bill reference we issued whose charge has since been deleted — a data problem, not a + // customer-facing cancellation. + if (!charge) return { stillPayable: false, reason: "NOT_FOUND" }; + + const base = { + payerName: + charge.booking?.seats?.find((s) => s.leg === 1)?.passengerName ?? + charge.booking?.seats?.[0]?.passengerName ?? + charge.booking?.passenger?.user?.fullName ?? + null, + // The charge is always booked in ETB and CBE settles ETB only, so no conversion applies. + currentAmountMinor: this.currencyService.displayMinorToChargeMajor( + charge.totalMinor, + "ETB", + ), + currency: "ETB", + // Rendered beside the amount on CBE's confirmation screen. The weight and booking ref are + // both on the agent's slip, so the payer can match the two before confirming. + paymentReason: `Excess baggage ${charge.excessWeightKg}kg — booking ${ + charge.booking?.bookingRef ?? "" + }`.trim(), + }; + + // Paid first: a charge settled by any method (including cash at the counter) must be reported + // as already paid, never as merely "not payable". + if (charge.status === "PAID" || charge.status === "CASH_COLLECTED") { + return { ...base, stillPayable: false, reason: "ALREADY_PAID" }; + } + // A supervisor wrote the charge off; from the payer's side the debt is gone. + if (charge.status === "WAIVED") { + return { ...base, stillPayable: false, reason: "CANCELLED" }; + } + // Confirmed CBE debits land in seconds, but must not be accepted so close to the deadline + // that the sweep expires the intent before the capture is registered. + if ( + charge.status === "EXPIRED" || + charge.expiresAt.getTime() - PAYMENT_SETTLE_MARGIN_SECONDS * 1000 < + Date.now() + ) { + return { ...base, stillPayable: false, reason: "EXPIRED" }; + } + if (charge.status !== "PENDING") { + return { ...base, stillPayable: false, reason: "NOT_PAYABLE" }; + } + return { ...base, stillPayable: true, reason: null }; + } + /** * The booking's payment deadline, resolved exactly like the auto-cancel job: the booking's * origin-segment time and that stop's own check-in window, falling back to the route default. @@ -1396,6 +1463,77 @@ export class PaymentsService { return { processed: true }; } + /** + * Settlement for an excess baggage charge paid through the passenger portal link. + * + * Deliberately has NO short-payment amount guard, unlike the booking path: the charge is stored + * in ETB while `event.amountMinor` arrives in the provider's settlement currency (DJF for + * Waafi/D-Money/CAC, USD for card), so comparing the two directly would reject every legitimate + * cross-currency payment. The amount actually charged was computed server-side at initiate. + * + * An EXPIRED charge is still marked PAID. The link TTL only governs whether a NEW payment may be + * started; once a provider has captured the money the charge is paid, and leaving it EXPIRED + * would hide a real settlement from the agent who has to reconcile it. + */ + private async handleExcessBaggageChargeEvent( + event: PaymentEventDto, + ): Promise { + if (event.eventType === "payment.failed") { + this.logger.warn( + `excess baggage charge ${event.referenceId} payment failed`, + ); + return { processed: true }; + } + + const charge = await this.prisma.excessBaggageCharge.findUnique({ + where: { id: event.referenceId }, + }); + if (!charge) { + // Ack — a missing charge will not appear on redelivery; needs investigation. + this.logger.error( + `mark-paid: no excess baggage charge for reference ${event.referenceId}`, + ); + return { processed: false, reason: "charge-not-found" }; + } + if (charge.status === "PAID" || charge.status === "CASH_COLLECTED") { + return { processed: true, alreadyFinalized: true }; + } + // Money arrived against a charge nobody expected to be paid — record it as PAID (that is the + // truth) but say so loudly: a waived charge that settles anyway needs a refund decision. + if (charge.status !== "PENDING") { + this.logger.warn( + `mark-paid: excess baggage charge ${charge.id} settled while ${charge.status} ` + + `(${event.amountMinor} ${event.currency}) — marking PAID; needs review`, + ); + } + + await this.prisma.excessBaggageCharge.update({ + where: { id: charge.id }, + data: { + status: "PAID", + // The provider's own capture time, not when this event happened to be processed — a + // replayed or dead-lettered event must not backdate the money to the wrong minute. + paidAt: event.paidAt ? new Date(event.paidAt) : new Date(), + }, + }); + await this.auditService.log({ + action: "UPDATE", + entityType: "ExcessBaggageCharge", + entityId: charge.id, + oldData: { status: charge.status }, + newData: { + status: "PAID", + providerTxnId: event.providerTxnId, + settledAmount: event.amountMinor, + settledCurrency: event.currency, + }, + }); + this.logger.log( + `excess baggage charge ${charge.id} marked PAID (${event.amountMinor} ${event.currency}, txn ${event.providerTxnId ?? "n/a"})`, + ); + return { processed: true }; + } + async handlePaymentEvent( event: PaymentEventDto, ): Promise { @@ -1410,6 +1548,10 @@ export class PaymentsService { return this.handleSupplementaryChargeEvent(event); } + if (event.referenceType === PaymentReferenceType.EXCESS_BAGGAGE) { + return this.handleExcessBaggageChargeEvent(event); + } + if (event.referenceType !== PaymentReferenceType.BOOKING) { this.logger.warn( `mark-paid: ignoring unknown referenceType ${event.referenceType}`, diff --git a/apps/edr-passenger-api/test/money-integrity.e2e-spec.ts b/apps/edr-passenger-api/test/money-integrity.e2e-spec.ts index dace45843..91b0a4f2f 100644 --- a/apps/edr-passenger-api/test/money-integrity.e2e-spec.ts +++ b/apps/edr-passenger-api/test/money-integrity.e2e-spec.ts @@ -130,11 +130,12 @@ describe("Money integrity (Tier-2 direct instantiation)", () => { const service = new ExcessBaggageService( prisma as any, - asyncStub(), - asyncStub(), - asyncStub(), - asyncStub(), - asyncStub(), + asyncStub(), // auditService + asyncStub(), // currencyService + asyncStub(), // paymentClient + asyncStub(), // notifications + asyncStub(), // smsClient + asyncStub(), // emailClient ); const charge: any = await service.logCharge({ @@ -174,6 +175,7 @@ describe("Money integrity (Tier-2 direct instantiation)", () => { const service = new ExcessBaggageService( prisma as any, asyncStub(), // auditService + asyncStub(), // currencyService asyncStub(), // paymentClient asyncStub(), // notifications asyncStub(), // smsClient diff --git a/apps/edr-passenger-web/portal/src/app/excess-baggage/pay/[token]/page.tsx b/apps/edr-passenger-web/portal/src/app/excess-baggage/pay/[token]/page.tsx index 209651756..73976fcda 100644 --- a/apps/edr-passenger-web/portal/src/app/excess-baggage/pay/[token]/page.tsx +++ b/apps/edr-passenger-web/portal/src/app/excess-baggage/pay/[token]/page.tsx @@ -1,14 +1,17 @@ "use client"; -import { useMemo, useState } from "react"; +import { useEffect, useMemo, useState } from "react"; import { useParams, useRouter } from "next/navigation"; import { useQuery, useMutation } from "@tanstack/react-query"; import { apiClient } from "@/lib/api-client"; import { PaymentMethod } from "@/types"; import { AlertCircle, + Check, CheckCircle, + Copy, CreditCard, + KeyRound, Landmark, Loader2, Smartphone, @@ -22,6 +25,28 @@ const getIconForMethod = (methodId: string) => { return Smartphone; }; +// WALLET is an internal balance debit with no excess-baggage path — the API refuses it, so it is +// never offered here. +const UNSUPPORTED_METHODS = ["WALLET"]; + +// Push-debit methods charge an account we must know before initiating: CAC Bank SMSes a one-time +// password to it, eBirr pushes a USSD PIN prompt to it. Neither opens a hosted page that could +// collect the number afterwards, so it is asked for up front. +const requiresPayerMobile = (method: string | null) => + method === "CAC_BANK" || method === "EBIRR"; + +// DJF has no minor unit; ETB and USD are quoted to cents. Matches the API's charge-side rounding, +// so the quote renders exactly the figure the provider will debit. +const formatAmount = (amount: number, currency: string) => + amount.toFixed(currency.toUpperCase() === "DJF" ? 0 : 2); + +interface AmountQuote { + chargeId: string; + method: string; + currency: string; + amount: number; +} + export default function ExcessBaggagePayPage() { const { token } = useParams<{ token: string }>(); const router = useRouter(); @@ -29,6 +54,26 @@ export default function ExcessBaggagePayPage() { const [isProcessing, setIsProcessing] = useState(false); const [paymentError, setPaymentError] = useState(null); + // Push-debit (CAC Bank / eBirr): collect the payer's mobile before initiating, then — for CAC — + // the OTP the bank SMSes to it. + const [phoneModalOpen, setPhoneModalOpen] = useState(false); + const [payerMobile, setPayerMobile] = useState(""); + const [phoneError, setPhoneError] = useState(null); + const [otpModalOpen, setOtpModalOpen] = useState(false); + const [otpCode, setOtpCode] = useState(""); + const [otpMessage, setOtpMessage] = useState(null); + const [otpError, setOtpError] = useState(null); + const [pushMessage, setPushMessage] = useState(null); + + // CBE bill: no redirect and no OTP — the payer walks away with a bill number and pays it at a + // branch/app later, so the page shows the number and watches for settlement. + const [billAction, setBillAction] = useState<{ + billReference: string; + instructions?: string; + expiresAt?: string; + } | null>(null); + const [billCopied, setBillCopied] = useState(false); + const { data: charge, isLoading: loadingCharge, error: chargeError } = useQuery({ queryKey: ["excessBaggageCharge", token], queryFn: () => apiClient.get(`/excess-baggage/pay/${token}`), @@ -45,24 +90,104 @@ export default function ExcessBaggagePayPage() { enabled: !!charge, }); - const amountDisplay = useMemo(() => { - const amountMinor = Number(charge?.totalMinor ?? charge?.amountMinor ?? 0); - return (amountMinor / 100).toFixed(2); - }, [charge]); + const availableMethods = useMemo( + () => + paymentMethods.filter( + (m) => m.enabled && !UNSUPPORTED_METHODS.includes(m.type), + ), + [paymentMethods], + ); - const currency = charge?.currency ?? charge?.booking?.currency ?? "ETB"; + // The charge is always booked in ETB; this is what it costs before a method is chosen. + const chargeCurrency = charge?.currency ?? charge?.booking?.currency ?? "ETB"; + const chargeAmount = useMemo( + () => Number(charge?.totalMinor ?? charge?.amountMinor ?? 0) / 100, + [charge], + ); + + // Each method settles in its own currency (WAAFI/DMONEY in DJF, CARD in USD, Ethiopian wallets + // in ETB), so the price has to be re-quoted server-side whenever the selection changes — the + // stored ETB total is not what a Djiboutian wallet would debit. + const { + data: quote, + isFetching: fetchingQuote, + error: quoteError, + } = useQuery({ + queryKey: ["excessBaggageAmount", token, selectedMethod], + queryFn: () => + apiClient.get( + `/excess-baggage/pay/${token}/amount?method=${selectedMethod}`, + ), + enabled: !!token && !!selectedMethod, + retry: false, + staleTime: 30_000, + }); + + // A quote is only usable once it belongs to the method currently selected — otherwise it is a + // leftover from the previous selection and would price the payment in the wrong currency. + const quoteReady = !fetchingQuote && quote?.method === selectedMethod; + + const displayCurrency = selectedMethod + ? (quote?.currency ?? "") + : chargeCurrency; + const displayAmount = selectedMethod ? quote?.amount : chargeAmount; + const amountLabel = + quoteReady && displayAmount != null + ? `${displayCurrency} ${formatAmount(displayAmount, displayCurrency)}` + : !selectedMethod && displayAmount != null + ? `${chargeCurrency} ${formatAmount(displayAmount, chargeCurrency)}` + : null; + + // Never let Pay fire against a price the payer has not been shown. + const awaitingQuote = !!selectedMethod && !quoteReady; const payMutation = useMutation({ - mutationFn: (method: string) => + mutationFn: (vars: { method: string; payerAccount?: string }) => apiClient.post(`/excess-baggage/pay/${token}/initiate`, { - method, + method: vars.method, platform: "web", + ...(vars.payerAccount ? { payerAccount: vars.payerAccount } : {}), }), onSuccess: (data: any) => { - if (data?.clientAction?.type === "REDIRECT") { - window.location.href = data.clientAction.url; + const action = data?.clientAction; + + if (action?.type === "REDIRECT") { + window.location.href = action.url; return; } + + // CAC Bank: no redirect — the bank SMS'd an OTP. Collect it here and confirm. + if (action?.type === "COLLECT_OTP") { + setOtpMessage(action.message ?? "Enter the OTP sent to your phone"); + setOtpCode(""); + setOtpError(null); + setOtpModalOpen(true); + setIsProcessing(false); + return; + } + + // CBE: the bill now exists in CBE's system. Nothing to navigate to — show the number. + if (action?.type === "SHOW_BILL_REFERENCE") { + setBillAction({ + billReference: action.billReference, + instructions: action.instructions, + expiresAt: action.expiresAt, + }); + setBillCopied(false); + setIsProcessing(false); + return; + } + + // eBirr: the PIN prompt was pushed to the payer's handset; there is nothing to navigate to. + if (action?.type === "AWAIT_PUSH") { + setPushMessage( + action.message ?? + `Approve the payment on your phone${action.payerAccountMasked ? ` (${action.payerAccountMasked})` : ""}.`, + ); + setIsProcessing(false); + return; + } + router.push(`/excess-baggage/pay/${token}/result`); }, onError: (err: any) => { @@ -71,11 +196,92 @@ export default function ExcessBaggagePayPage() { }, }); - const handlePay = () => { + // CAC Bank OTP confirmation. A 200 means the debit settled; a 400 is a wrong/expired OTP — + // keep the modal open so the payer can re-enter it (the intent stays open). + const otpMutation = useMutation({ + mutationFn: (otp: string) => + apiClient.post(`/excess-baggage/pay/${token}/confirm`, { otp }), + onSuccess: () => { + setOtpModalOpen(false); + router.push(`/excess-baggage/pay/${token}/result`); + }, + onError: (err: any) => { + setOtpError( + err?.response?.data?.message ?? + err?.message ?? + "Invalid or expired OTP. Please try again.", + ); + }, + }); + + const startPayment = (mobile?: string) => { if (!selectedMethod) return; setIsProcessing(true); setPaymentError(null); - payMutation.mutate(selectedMethod); + payMutation.mutate({ + method: selectedMethod, + payerAccount: requiresPayerMobile(selectedMethod) + ? mobile?.trim() + : undefined, + }); + }; + + const handlePay = () => { + if (!selectedMethod || awaitingQuote) return; + setPaymentError(null); + + if (requiresPayerMobile(selectedMethod)) { + // Prefill with the number the charge was raised against, but leave it editable — the + // handset paying is often not the one the booking was made under. + if (!payerMobile.trim() && charge?.contactPhone) { + setPayerMobile(charge.contactPhone); + } + setPhoneError(null); + setPhoneModalOpen(true); + return; + } + + startPayment(); + }; + + const submitPhone = () => { + if (!payerMobile.trim()) { + setPhoneError("Please enter your mobile number"); + return; + } + setPhoneModalOpen(false); + startPayment(payerMobile); + }; + + // While a bill or a pushed PIN prompt is outstanding, watch the charge. Settlement happens + // server-side — a CBE teller, or the provider's webhook — so the browser has no other signal. + // Success is only ever claimed from this, never from a client-side guess. + const watching = !!billAction || !!pushMessage; + const { data: liveStatus } = useQuery<{ status: string; paid: boolean }>({ + queryKey: ["excessBaggageStatus", token], + queryFn: () => + apiClient.get<{ status: string; paid: boolean }>( + `/excess-baggage/pay/${token}/status`, + ), + enabled: !!token && watching, + refetchInterval: 5_000, + }); + + useEffect(() => { + if (watching && liveStatus?.paid) { + router.push(`/excess-baggage/pay/${token}/result`); + } + }, [watching, liveStatus?.paid, router, token]); + + const copyBillReference = async () => { + if (!billAction) return; + try { + await navigator.clipboard.writeText(billAction.billReference); + setBillCopied(true); + setTimeout(() => setBillCopied(false), 2000); + } catch { + /* clipboard unavailable — the number is still shown on screen */ + } }; if (loadingCharge) { @@ -112,10 +318,25 @@ export default function ExcessBaggagePayPage() {
Amount due - - {currency} {amountDisplay} - + {amountLabel ? ( + {amountLabel} + ) : quoteError ? ( + + ) : ( + + )}
+ {selectedMethod && quoteReady && displayCurrency !== chargeCurrency && ( +

+ Converted from {chargeCurrency} {formatAmount(chargeAmount, chargeCurrency)} at today's rate +

+ )} + {quoteError && ( +

+ {(quoteError as any)?.response?.data?.message ?? + "This payment method is unavailable right now. Please choose another."} +

+ )}
Weight {charge.excessWeightKg ?? "—"} kg @@ -131,7 +352,7 @@ export default function ExcessBaggagePayPage() {
) : (
- {paymentMethods.filter((m) => m.enabled).map((method) => { + {availableMethods.map((method) => { const Icon = getIconForMethod(method.type); const isSelected = selectedMethod === method.type; return ( @@ -166,17 +387,181 @@ export default function ExcessBaggagePayPage() { + + {/* CBE bill — show the number; confirmation only ever comes from the status poll */} + {billAction && ( +
+
+
+ +

Pay at CBE

+
+

+ {billAction.instructions ?? + "Pay this bill at any CBE branch, the CBE Birr app, mobile banking or USSD."} +

+
+ + {billAction.billReference} + + +
+
+

+ Amount: ETB {formatAmount(chargeAmount, "ETB")} +

+ {billAction.expiresAt && ( +

+ Pay before:{" "} + + {new Date(billAction.expiresAt).toLocaleString()} + +

+ )} +
+
+ + Waiting for payment confirmation — this page updates automatically once CBE + confirms your payment. +
+ +
+
+ )} + + {/* eBirr: the PIN prompt is on the payer's handset — nothing to navigate to. */} + {pushMessage && ( +
+ +
+

Check your phone

+

{pushMessage}

+
+
+ )} + + {/* Push-debit methods (CAC Bank, eBirr) — collect payer mobile before initiating */} + {phoneModalOpen && ( +
+
+
+ +

Your mobile number

+
+

+ {selectedMethod === "EBIRR" + ? "eBirr will prompt this number for your PIN to authorize the payment. Make sure it's the phone you have with you." + : "CAC Bank will send a one-time password to this number to authorize the payment."} +

+ { setPayerMobile(e.target.value); setPhoneError(null); }} + onKeyDown={(e) => { if (e.key === "Enter") submitPhone(); }} + placeholder={selectedMethod === "EBIRR" ? "09XX XXX XXX" : "77 XX XX XX"} + className="w-full px-3 py-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:border-primary focus:ring-1 focus:ring-primary outline-none" + /> + {phoneError && ( +

⚠️ {phoneError}

+ )} +
+ + +
+
+
+ )} + + {/* CAC Bank OTP entry */} + {otpModalOpen && ( +
+
+
+ +

Enter OTP

+
+

{otpMessage}

+ { setOtpCode(e.target.value.replace(/\D/g, "")); setOtpError(null); }} + onKeyDown={(e) => { if (e.key === "Enter" && otpCode.trim() && !otpMutation.isPending) otpMutation.mutate(otpCode.trim()); }} + placeholder="Enter code" + maxLength={10} + className="w-full text-center tracking-[0.4em] text-lg font-semibold px-3 py-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:border-primary focus:ring-1 focus:ring-primary outline-none" + /> + {otpError && ( +

⚠️ {otpError}

+ )} +
+ + +
+
+
+ )}
); From a9eac93fa3ea1afb7f4e1c4f9e00b5d57f33ba33 Mon Sep 17 00:00:00 2001 From: Abubeker Yasin Date: Tue, 18 Aug 2026 10:16:59 +0300 Subject: [PATCH 10/14] fix: ( supplementary-charges ) pay in the selected method's currency, add CAC Bank and CBE --- .../payments/internal-payments.controller.ts | 5 + .../modules/payments/payments.controller.ts | 59 +++ .../modules/payments/payments.service.spec.ts | 76 ++++ .../src/modules/payments/payments.service.ts | 66 +++ .../payments/supplementary-charges.service.ts | 201 ++++++++- .../payments/supplementary-charges.spec.ts | 245 +++++++++++ .../src/app/pay-balance/[token]/page.tsx | 412 +++++++++++++++++- 7 files changed, 1047 insertions(+), 17 deletions(-) create mode 100644 apps/edr-passenger-api/src/modules/payments/supplementary-charges.spec.ts diff --git a/apps/edr-passenger-api/src/modules/payments/internal-payments.controller.ts b/apps/edr-passenger-api/src/modules/payments/internal-payments.controller.ts index be46135a1..1b82389fb 100644 --- a/apps/edr-passenger-api/src/modules/payments/internal-payments.controller.ts +++ b/apps/edr-passenger-api/src/modules/payments/internal-payments.controller.ts @@ -58,6 +58,11 @@ export class InternalPaymentsController { if (request.referenceType === PaymentReferenceType.EXCESS_BAGGAGE) { return this.paymentsService.billQueryExcessBaggage(request.referenceId); } + if (request.referenceType === PaymentReferenceType.SUPPLEMENTARY_CHARGE) { + return this.paymentsService.billQuerySupplementaryCharge( + request.referenceId, + ); + } return this.paymentsService.billQuery(request.referenceId); } } diff --git a/apps/edr-passenger-api/src/modules/payments/payments.controller.ts b/apps/edr-passenger-api/src/modules/payments/payments.controller.ts index 858d108fe..57db52fe9 100644 --- a/apps/edr-passenger-api/src/modules/payments/payments.controller.ts +++ b/apps/edr-passenger-api/src/modules/payments/payments.controller.ts @@ -57,6 +57,18 @@ class WaiveSupplementaryChargeDto { class PaySupplementaryChargeDto { @ApiProperty({ enum: PaymentMethodTypeEnum, example: 'TELEBIRR' }) @IsEnum(PaymentMethodTypeEnum) method: PaymentMethodTypeEnum; @ApiPropertyOptional({ enum: ['web', 'mobile', 'inapp'], default: 'web' }) @IsOptional() @IsIn(['web', 'mobile', 'inapp']) platform?: PaymentPlatformDto; + @ApiPropertyOptional({ + description: + 'Payer account / mobile number. Required for the push-debit methods: CAC_BANK (the bank ' + + 'SMSes a one-time password to it) and EBIRR (the wallet pushes a USSD PIN prompt to it).', + example: '77123456', + }) + @IsOptional() @IsString() payerAccount?: string; +} + +class ConfirmSupplementaryOtpDto { + @ApiProperty({ description: 'One-time password the payer received by SMS (CAC Bank).', example: '4530' }) + @IsString() otp: string; } @ApiTags("Payment") @@ -413,6 +425,52 @@ export class PaymentsController { return this.supplementaryService.getByToken(token); } + @Get('supplementary/by-token/:token/amount') + @SetMetadata('isPublic', true) + @ApiOperation({ + summary: 'Quote a supplementary charge in a payment method’s settlement currency (public)', + description: + 'Returns what the given method would debit, converted from the charge’s stored ETB amount ' + + 'to that method’s settlement currency (WAAFI/DMONEY settle in DJF, CARD in USD, Ethiopian ' + + 'wallets in ETB). The self-pay page quotes this before the payer commits; paying recomputes ' + + 'it identically.', + }) + @ApiQuery({ name: 'method', required: true, example: 'WAAFI' }) + quoteSupplementaryAmount( + @Param('token') token: string, + @Query('method') method: string, + ) { + return this.supplementaryService.quoteAmount(token, method); + } + + @Get('supplementary/by-token/:token/status') + @SetMetadata('isPublic', true) + @ApiOperation({ + summary: 'Poll a supplementary charge’s settlement status (public)', + description: + 'Reports the charge’s current status without the payability gate on the by-token lookup, ' + + 'so a page can watch for settlement that happens out of band (a CBE bill paid at a branch, ' + + 'or a redirect payment confirmed by webhook).', + }) + getSupplementaryStatus(@Param('token') token: string) { + return this.supplementaryService.getStatus(token); + } + + @Post('supplementary/by-token/:token/confirm') + @SetMetadata('isPublic', true) + @ApiOperation({ + summary: 'Confirm an OTP-debit balance payment (CAC Bank, public — self-pay)', + description: + 'Submits the one-time password the payer received by SMS. A wrong or expired OTP returns ' + + '400 and the payment stays open for retry.', + }) + confirmSupplementaryOtp( + @Param('token') token: string, + @Body() dto: ConfirmSupplementaryOtpDto, + ) { + return this.supplementaryService.confirmOtp(token, dto.otp); + } + @Post('supplementary/by-token/:token/pay') @SetMetadata('isPublic', true) @ApiOperation({ summary: 'Initiate payment for a supplementary charge (public — self-pay)' }) @@ -430,6 +488,7 @@ export class PaymentsController { dto.method, dto.platform, resolveAllowedOrigin(origin, referer, frontendBaseUrl), + dto.payerAccount, ); } diff --git a/apps/edr-passenger-api/src/modules/payments/payments.service.spec.ts b/apps/edr-passenger-api/src/modules/payments/payments.service.spec.ts index 36b062261..71efe6546 100644 --- a/apps/edr-passenger-api/src/modules/payments/payments.service.spec.ts +++ b/apps/edr-passenger-api/src/modules/payments/payments.service.spec.ts @@ -50,6 +50,10 @@ describe("PaymentsService", () => { findUnique: jest.fn(), update: jest.fn(), }, + supplementaryCharge: { + findUnique: jest.fn(), + update: jest.fn(), + }, currencyExchangeRate: { findFirst: jest.fn(), }, @@ -758,4 +762,76 @@ describe("PaymentsService", () => { ).resolves.toEqual({ stillPayable: false, reason: "NOT_FOUND" }); }); }); + /** + * The live hop CBE makes while a teller is on the line, for a balance bill. Same + * double-payment guard as bookings and baggage: anything other than stillPayable=true makes + * CBE refuse the debit. + */ + describe("billQuerySupplementaryCharge", () => { + const payable = { + id: "sc-1", + amountMinor: 100_000, + status: "PENDING", + expiresAt: new Date(Date.now() + 60 * 60 * 1000), + booking: { + bookingRef: "BAL-001", + seats: [{ leg: 1, passengerName: "Abebe Kebede" }], + passenger: { user: { fullName: "Account Holder" } }, + }, + }; + + it("reports a pending charge as payable, in ETB, with the passenger name", async () => { + mockPrisma.supplementaryCharge.findUnique.mockResolvedValue(payable); + const result = await service.billQuerySupplementaryCharge("sc-1"); + expect(result).toMatchObject({ + stillPayable: true, + currency: "ETB", + currentAmountMinor: 1000, + payerName: "Abebe Kebede", + }); + expect(result.paymentReason).toContain("BAL-001"); + }); + + it("refuses an already paid charge", async () => { + mockPrisma.supplementaryCharge.findUnique.mockResolvedValue({ ...payable, status: "PAID" }); + await expect(service.billQuerySupplementaryCharge("sc-1")).resolves.toMatchObject({ + stillPayable: false, + reason: "ALREADY_PAID", + }); + }); + + it("refuses a waived charge", async () => { + mockPrisma.supplementaryCharge.findUnique.mockResolvedValue({ ...payable, status: "WAIVED" }); + await expect(service.billQuerySupplementaryCharge("sc-1")).resolves.toMatchObject({ + stillPayable: false, + reason: "CANCELLED", + }); + }); + + it("refuses within the settle margin so a debit cannot land after expiry", async () => { + mockPrisma.supplementaryCharge.findUnique.mockResolvedValue({ + ...payable, + expiresAt: new Date(Date.now() + 5_000), + }); + await expect(service.billQuerySupplementaryCharge("sc-1")).resolves.toMatchObject({ + stillPayable: false, + reason: "EXPIRED", + }); + }); + + it("treats a null expiry as an open-ended debt, still payable", async () => { + mockPrisma.supplementaryCharge.findUnique.mockResolvedValue({ ...payable, expiresAt: null }); + await expect(service.billQuerySupplementaryCharge("sc-1")).resolves.toMatchObject({ + stillPayable: true, + }); + }); + + it("reports NOT_FOUND for a bill whose charge is gone", async () => { + mockPrisma.supplementaryCharge.findUnique.mockResolvedValue(null); + await expect(service.billQuerySupplementaryCharge("sc-1")).resolves.toEqual({ + stillPayable: false, + reason: "NOT_FOUND", + }); + }); + }); }); diff --git a/apps/edr-passenger-api/src/modules/payments/payments.service.ts b/apps/edr-passenger-api/src/modules/payments/payments.service.ts index 1415c1dcc..b58b56ade 100644 --- a/apps/edr-passenger-api/src/modules/payments/payments.service.ts +++ b/apps/edr-passenger-api/src/modules/payments/payments.service.ts @@ -600,6 +600,72 @@ export class PaymentsService { return { ...base, stillPayable: true, reason: null }; } + /** + * Bill-query for a supplementary charge — the same live "still payable?" hop as bookings, + * against `SupplementaryCharge`. This is the double-payment guard for balance bills: once the + * charge is paid, waived or lapsed, CBE is told to refuse the debit. + * + * The charge's own 72-hour `expiresAt` is the deadline. It is nullable — a charge raised with + * no expiry is an open-ended debt and stays payable indefinitely, which is the intended reading + * of a null here rather than an immediate refusal. + */ + async billQuerySupplementaryCharge( + chargeId: string, + ): Promise { + const charge = await this.prisma.supplementaryCharge.findUnique({ + where: { id: chargeId }, + include: { + booking: { + include: { seats: true, passenger: { include: { user: true } } }, + }, + }, + }); + // A bill reference we issued whose charge has since been deleted — a data problem, not a + // customer-facing cancellation. + if (!charge) return { stillPayable: false, reason: "NOT_FOUND" }; + + const base = { + payerName: + charge.booking?.seats?.find((s) => s.leg === 1)?.passengerName ?? + charge.booking?.seats?.[0]?.passengerName ?? + charge.booking?.passenger?.user?.fullName ?? + null, + // The charge is raised in ETB and CBE settles ETB only, so no conversion applies. + currentAmountMinor: this.currencyService.displayMinorToChargeMajor( + charge.amountMinor, + "ETB", + ), + currency: "ETB", + // Rendered beside the amount on CBE's confirmation screen. The booking ref is on the + // passenger's ticket, so they can match the two before confirming. + paymentReason: `Outstanding balance — booking ${ + charge.booking?.bookingRef ?? "" + }`.trim(), + }; + + if (charge.status === "PAID") { + return { ...base, stillPayable: false, reason: "ALREADY_PAID" }; + } + // Staff wrote the balance off; from the payer's side the debt is gone. + if (charge.status === "WAIVED") { + return { ...base, stillPayable: false, reason: "CANCELLED" }; + } + // Confirmed CBE debits land in seconds, but must not be accepted so close to the deadline + // that the sweep expires the intent before the capture is registered. + if ( + charge.status === "EXPIRED" || + (charge.expiresAt && + charge.expiresAt.getTime() - PAYMENT_SETTLE_MARGIN_SECONDS * 1000 < + Date.now()) + ) { + return { ...base, stillPayable: false, reason: "EXPIRED" }; + } + if (charge.status !== "PENDING") { + return { ...base, stillPayable: false, reason: "NOT_PAYABLE" }; + } + return { ...base, stillPayable: true, reason: null }; + } + /** * The booking's payment deadline, resolved exactly like the auto-cancel job: the booking's * origin-segment time and that stop's own check-in window, falling back to the route default. diff --git a/apps/edr-passenger-api/src/modules/payments/supplementary-charges.service.ts b/apps/edr-passenger-api/src/modules/payments/supplementary-charges.service.ts index 079792366..b0bfabf09 100644 --- a/apps/edr-passenger-api/src/modules/payments/supplementary-charges.service.ts +++ b/apps/edr-passenger-api/src/modules/payments/supplementary-charges.service.ts @@ -4,11 +4,35 @@ import { AuditService } from '../../common/audit.service'; import { SmsClientService } from '../notifications/sms-client.service'; import { EmailClientService } from '../notifications/email-client.service'; import { PaymentClientService } from './payment-client.service'; -import { PaymentReferenceType, PaymentService as PaymentServiceEnum, ProviderMethod } from '@edr/types'; +import { CurrencyService } from '../currency/currency.service'; +import { + PaymentReferenceType, + PaymentService as PaymentServiceEnum, + ProviderMethod, + ProviderPaymentStatus, +} from '@edr/types'; import { PaymentPlatformDto } from './payments.dto'; +import { PaymentMethodType } from '@prisma/client'; const CHARGE_TTL_MS = 72 * 60 * 60 * 1000; // 72 hours +/** + * WALLET is an internal balance debit handled inside this app, not a provider — the payment + * microservice rejects it as one. Supplementary charges have no wallet path, so it is refused up + * front with a message the payer can act on rather than a 502 from the gateway layer. + */ +const UNSUPPORTED_METHODS = new Set([PaymentMethodType.WALLET]); + +/** + * Push-debit methods charge an account we must be told up front — CAC Bank SMSes a one-time + * password to it, eBirr pushes a USSD PIN prompt to it. Neither opens a hosted page that could + * collect the number later (mirrors PaymentsService and ExcessBaggageService). + */ +const METHODS_REQUIRING_PAYER_ACCOUNT = new Set([ + PaymentMethodType.CAC_BANK, + PaymentMethodType.EBIRR, +]); + @Injectable() export class SupplementaryChargesService { private readonly logger = new Logger(SupplementaryChargesService.name); @@ -19,6 +43,7 @@ export class SupplementaryChargesService { private smsClient: SmsClientService, private emailClient: EmailClientService, private paymentClient: PaymentClientService, + private currencyService: CurrencyService, ) {} async create(dto: { @@ -117,14 +142,161 @@ export class SupplementaryChargesService { return updated; } + /** + * What the payer is actually charged when settling this charge with `method`. + * + * The charge is raised in ETB, but the selected method settles in its own currency — WAAFI and + * D-Money in DJF, CARD in USD, the Ethiopian wallets in ETB — recorded on the PaymentMethod row. + * The payment microservice is currency-agnostic and hands whatever it is given straight to the + * gateway, so the ETB->settlement conversion has to happen here or the provider is asked to + * debit an ETB number labelled as its own currency. + * + * Both the quote shown to the payer and the amount sent to the provider come through this one + * method, so the price on the button and the price debited cannot drift apart. + */ + private async resolveChargeAmount( + charge: { amountMinor: number; currency: string }, + method: string, + ): Promise<{ amount: number; currency: string }> { + if (UNSUPPORTED_METHODS.has(method)) { + throw new BadRequestException( + `${method} is not available for balance payments`, + ); + } + + const paymentMethod = await this.prisma.paymentMethod.findUnique({ + where: { type: method as PaymentMethodType }, + }); + // CBE settles ETB only (docs/cbe/CBE_IMPLEMENTATION_PLAN.md D8) — never converted. + const chargeCurrency = + method === PaymentMethodType.CBE_BILL + ? 'ETB' + : (paymentMethod?.currency ?? charge.currency).toUpperCase(); + + // Applies the target currency's own precision — DJF rounds to whole francs, ETB/USD to cents. + const amount = await this.currencyService.convertMinorToChargeMajor( + charge.amountMinor, + charge.currency, + chargeCurrency, + ); + return { amount, currency: chargeCurrency }; + } + + /** + * Price quote for the pay page: what `method` would debit, in that method's settlement + * currency. The payer sees this before committing, and pay() recomputes it the same way. + */ + async quoteAmount(token: string, method: string) { + const charge = await this.getByToken(token); + const { amount, currency } = await this.resolveChargeAmount(charge, method); + return { chargeId: charge.id, method, currency, amount }; + } + + /** + * Bare status for the pay/result pages to poll. Unlike getByToken this does NOT reject a paid, + * expired or waived charge — reporting those states is the entire point. A CBE bill can settle + * long after the payer closed the tab, and redirect methods only converge when the settlement + * event lands, so the page needs something it can watch. + */ + async getStatus(token: string) { + const charge = await this.prisma.supplementaryCharge.findUnique({ + where: { paymentToken: token }, + select: { + id: true, + status: true, + paidAt: true, + amountMinor: true, + currency: true, + expiresAt: true, + }, + }); + if (!charge) throw new NotFoundException('Payment link not found'); + return { + chargeId: charge.id, + status: charge.status, + paid: charge.status === 'PAID', + paidAt: charge.paidAt, + amountMinor: charge.amountMinor, + currency: charge.currency, + expiresAt: charge.expiresAt, + }; + } + + /** + * Full_Name for CBE's confirmation screen — mandatory in its envelope. The traveller the balance + * is owed against: lead passenger on the booking, falling back to the account holder. + */ + private async resolvePayerName(bookingId: string): Promise { + const booking = await this.prisma.booking.findUnique({ + where: { id: bookingId }, + include: { seats: true, passenger: { include: { user: true } } }, + }); + if (!booking) return null; + return ( + booking.seats?.find((s: any) => s.leg === 1)?.passengerName ?? + booking.seats?.[0]?.passengerName ?? + booking.passenger?.user?.fullName ?? + null + ); + } + + /** + * Submit the one-time password for a COLLECT_OTP provider (CAC Bank). The bank SMSed it to the + * payerAccount given at pay(); this forwards it to the payment service and marks the charge paid + * when the debit settles. A wrong or expired OTP bubbles up as a 400 and the intent stays open, + * so the payer can simply re-enter it. + * + * Deliberately reads the charge directly rather than through getByToken: the bank is already + * holding a debit against this payer, and refusing to submit their OTP because the link TTL + * lapsed while they read the SMS would strand a payment that is mid-flight. + */ + async confirmOtp(token: string, otp: string) { + const charge = await this.prisma.supplementaryCharge.findUnique({ + where: { paymentToken: token }, + }); + if (!charge) throw new NotFoundException('Payment link not found'); + if (charge.status === 'PAID') { + return { chargeId: charge.id, status: 'SUCCEEDED', alreadyPaid: true }; + } + + const snapshot = await this.paymentClient.getIntentByReference( + PaymentReferenceType.SUPPLEMENTARY_CHARGE, + charge.id, + ); + if (!snapshot) { + throw new NotFoundException('No active payment to confirm for this charge'); + } + + const confirmed = await this.paymentClient.confirmOtp( + snapshot.intentId, + otp, + ); + if (confirmed.status === ProviderPaymentStatus.SUCCEEDED) { + await this.markPaid(charge.id, confirmed.providerTxnId); + } + + return { + chargeId: charge.id, + status: confirmed.status, + alreadyPaid: false, + }; + } + async pay( token: string, method: string, platform?: PaymentPlatformDto, requestOrigin?: string | null, + payerAccount?: string, ) { const charge = await this.getByToken(token); // validates status/expiry + if (METHODS_REQUIRING_PAYER_ACCOUNT.has(method) && !payerAccount?.trim()) { + throw new BadRequestException( + `payerAccount (mobile number) is required for ${method}`, + ); + } + const paymentMethod = method as ProviderMethod; // Self-pay links are opened on whichever portal domain the recipient used // (bookingedr.et vs passenger.edrsc.com), so the return pages must live on @@ -135,15 +307,38 @@ export class SupplementaryChargesService { const returnUrl = `${portalUrl}/pay-balance/${token}/success`; const failureUrl = `${portalUrl}/pay-balance/${token}/failed`; + const { amount, currency } = await this.resolveChargeAmount(charge, method); + + // CBE_BILL is inbound-only: no provider session is opened, the bill simply sits in CBE's + // system until someone pays it. It needs a real deadline and a payer name (Full_Name is + // mandatory in CBE's envelope) rather than the redirect flow's session semantics. + // + // Unlike an excess baggage charge (30-minute link TTL), this charge already carries a 72-hour + // deadline of its own, which is a sane bill lifetime — so it is passed straight through with + // no extension. That deadline is what stops the reconciliation sweep from expiring the intent + // early (CBE_IMPLEMENTATION_PLAN.md §6.4). A charge with no expiry at all yields no intent + // expiry either, which is correct: an open-ended debt backs an open-ended bill. + let payerName: string | undefined; + let expiresAt: string | undefined; + if (method === PaymentMethodType.CBE_BILL) { + expiresAt = charge.expiresAt?.toISOString(); + payerName = (await this.resolvePayerName(charge.bookingId)) ?? undefined; + } + const snapshot = await this.paymentClient.initiate({ service: PaymentServiceEnum.PASSENGER, referenceType: PaymentReferenceType.SUPPLEMENTARY_CHARGE, referenceId: charge.id, orderRef: `SC-${charge.id.substring(0, 8)}`, - amountMinor: charge.amountMinor / 100, - currency: charge.currency, + // `amountMinor` is the contract's name but its value is MAJOR units — the provider layer + // charges it verbatim at the currency's own precision (see PaymentIntentSnapshot). + amountMinor: amount, + currency, provider: paymentMethod, platform, + payerAccount: payerAccount?.trim() || undefined, + payerName, + expiresAt, returnUrl, failureUrl, }); diff --git a/apps/edr-passenger-api/src/modules/payments/supplementary-charges.spec.ts b/apps/edr-passenger-api/src/modules/payments/supplementary-charges.spec.ts new file mode 100644 index 000000000..130ed1870 --- /dev/null +++ b/apps/edr-passenger-api/src/modules/payments/supplementary-charges.spec.ts @@ -0,0 +1,245 @@ +import { BadRequestException } from '@nestjs/common'; +import { PaymentMethodType } from '@prisma/client'; +import { SupplementaryChargesService } from './supplementary-charges.service'; +import { CurrencyService } from '../currency/currency.service'; + +/** + * A supplementary charge is raised in ETB, but each payment method settles in its own currency and + * the payment microservice forwards whatever it is given straight to the gateway. These cover the + * ETB->settlement conversion, plus the two methods that could not complete at all before: CAC Bank + * (OTP debit) and CBE (inbound bill). + */ +describe('SupplementaryChargesService — payment methods', () => { + const CHARGE_ID = 'sc-1'; + const TOKEN = 'tok-1'; + + let prisma: Record; + let paymentClient: Record; + let service: SupplementaryChargesService; + let charge: any; + + const build = (rate?: { rate: number }) => { + charge = { + id: CHARGE_ID, + bookingId: 'booking-1', + amountMinor: 100_000, + currency: 'ETB', + status: 'PENDING', + expiresAt: new Date(Date.now() + 72 * 60 * 60 * 1000), + booking: { bookingRef: 'BAL-001' }, + }; + prisma = { + supplementaryCharge: { + findUnique: jest.fn().mockResolvedValue(charge), + update: jest.fn().mockResolvedValue({ ...charge, status: 'PAID' }), + }, + booking: { + findUnique: jest.fn().mockResolvedValue({ + seats: [{ leg: 1, passengerName: 'Abebe Kebede' }], + passenger: { user: { fullName: 'Account Holder' } }, + }), + }, + paymentMethod: { findUnique: jest.fn() }, + currencyExchangeRate: { + findFirst: jest.fn().mockResolvedValue(rate ?? null), + }, + }; + paymentClient = { + initiate: jest.fn().mockResolvedValue({ + intentId: 'intent-1', + status: 'REQUIRES_ACTION', + clientAction: { type: 'REDIRECT', url: 'https://gw.test/pay' }, + }), + getIntentByReference: jest + .fn() + .mockResolvedValue({ intentId: 'intent-1', status: 'REQUIRES_ACTION' }), + confirmOtp: jest.fn().mockResolvedValue({ + intentId: 'intent-1', + status: 'SUCCEEDED', + providerTxnId: 'CAC-77', + }), + }; + service = new SupplementaryChargesService( + prisma as any, + { log: jest.fn() } as any, + {} as any, + {} as any, + paymentClient as any, + new CurrencyService(prisma as any), + ); + }; + + const withMethod = (type: string, currency: string) => + prisma.paymentMethod.findUnique.mockResolvedValue({ type, currency }); + + describe('currency', () => { + it('charges an Ethiopian wallet in ETB, unconverted', async () => { + build(); + withMethod(PaymentMethodType.TELEBIRR, 'ETB'); + const quote = await service.quoteAmount(TOKEN, PaymentMethodType.TELEBIRR); + expect(quote).toMatchObject({ currency: 'ETB', amount: 1000 }); + expect(prisma.currencyExchangeRate.findFirst).not.toHaveBeenCalled(); + }); + + it('converts to DJF and rounds to whole francs', async () => { + build({ rate: 3.25 }); + withMethod(PaymentMethodType.DMONEY, 'DJF'); + const quote = await service.quoteAmount(TOKEN, PaymentMethodType.DMONEY); + expect(quote).toMatchObject({ currency: 'DJF', amount: 3250 }); + expect(Number.isInteger(quote.amount)).toBe(true); + }); + + it('sends the provider the converted amount, not the stored ETB total', async () => { + build({ rate: 0.018 }); + withMethod(PaymentMethodType.CARD, 'USD'); + await service.pay(TOKEN, PaymentMethodType.CARD, 'web' as any, null); + expect(paymentClient.initiate).toHaveBeenCalledWith( + expect.objectContaining({ + referenceType: 'SUPPLEMENTARY_CHARGE', + amountMinor: 18, + currency: 'USD', + }), + ); + }); + + it('quotes and charges the same figure', async () => { + build({ rate: 3.25 }); + withMethod(PaymentMethodType.WAAFI, 'DJF'); + const quote = await service.quoteAmount(TOKEN, PaymentMethodType.WAAFI); + await service.pay(TOKEN, PaymentMethodType.WAAFI, 'web' as any, null); + const sent = paymentClient.initiate.mock.calls[0][0]; + expect(quote.amount).toBe(sent.amountMinor); + expect(quote.currency).toBe(sent.currency); + }); + + it('refuses WALLET, which has no supplementary-charge path', async () => { + build(); + await expect( + service.quoteAmount(TOKEN, PaymentMethodType.WALLET), + ).rejects.toBeInstanceOf(BadRequestException); + expect(paymentClient.initiate).not.toHaveBeenCalled(); + }); + + it('fails closed when no exchange rate is configured', async () => { + build(); + withMethod(PaymentMethodType.WAAFI, 'DJF'); + await expect( + service.pay(TOKEN, PaymentMethodType.WAAFI, 'web' as any, null), + ).rejects.toBeInstanceOf(BadRequestException); + expect(paymentClient.initiate).not.toHaveBeenCalled(); + }); + }); + + describe('CAC Bank OTP debit', () => { + beforeEach(() => { + build({ rate: 3.25 }); + withMethod(PaymentMethodType.CAC_BANK, 'DJF'); + }); + + it('rejects pay() without a payer mobile', async () => { + await expect( + service.pay(TOKEN, PaymentMethodType.CAC_BANK, 'web' as any, null), + ).rejects.toBeInstanceOf(BadRequestException); + expect(paymentClient.initiate).not.toHaveBeenCalled(); + }); + + it('forwards the trimmed payer mobile', async () => { + await service.pay( + TOKEN, + PaymentMethodType.CAC_BANK, + 'web' as any, + null, + ' 77123456 ', + ); + expect(paymentClient.initiate).toHaveBeenCalledWith( + expect.objectContaining({ payerAccount: '77123456', currency: 'DJF' }), + ); + }); + + it('submits the OTP against the active intent and marks the charge paid', async () => { + const result = await service.confirmOtp(TOKEN, '4530'); + expect(paymentClient.getIntentByReference).toHaveBeenCalledWith( + 'SUPPLEMENTARY_CHARGE', + CHARGE_ID, + ); + expect(paymentClient.confirmOtp).toHaveBeenCalledWith('intent-1', '4530'); + expect(prisma.supplementaryCharge.update).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + status: 'PAID', + providerTxnId: 'CAC-77', + }), + }), + ); + expect(result).toMatchObject({ status: 'SUCCEEDED', alreadyPaid: false }); + }); + + it('leaves the charge unpaid when the OTP does not settle', async () => { + paymentClient.confirmOtp.mockResolvedValue({ + intentId: 'intent-1', + status: 'REQUIRES_ACTION', + }); + await service.confirmOtp(TOKEN, '0000'); + expect(prisma.supplementaryCharge.update).not.toHaveBeenCalled(); + }); + + it('is idempotent once already paid', async () => { + prisma.supplementaryCharge.findUnique.mockResolvedValue({ + ...charge, + status: 'PAID', + }); + await expect(service.confirmOtp(TOKEN, '4530')).resolves.toMatchObject({ + alreadyPaid: true, + }); + expect(paymentClient.confirmOtp).not.toHaveBeenCalled(); + }); + }); + + describe('CBE bill', () => { + beforeEach(() => { + build({ rate: 3.25 }); + withMethod(PaymentMethodType.CBE_BILL, 'DJF'); // misconfigured row must not win + }); + + it('forces ETB regardless of the PaymentMethod row', async () => { + const quote = await service.quoteAmount(TOKEN, PaymentMethodType.CBE_BILL); + expect(quote).toMatchObject({ currency: 'ETB', amount: 1000 }); + }); + + it('passes the charge own 72h deadline as the intent expiry', async () => { + await service.pay(TOKEN, PaymentMethodType.CBE_BILL, 'web' as any, null); + const sent = paymentClient.initiate.mock.calls[0][0]; + expect(sent.currency).toBe('ETB'); + expect(sent.expiresAt).toBe(charge.expiresAt.toISOString()); + // Comfortably longer than a browser-session TTL, so the sweep cannot kill the bill early. + expect(new Date(sent.expiresAt).getTime()).toBeGreaterThan( + Date.now() + 24 * 60 * 60 * 1000, + ); + }); + + it('sends the lead passenger as Full_Name, which CBE requires', async () => { + await service.pay(TOKEN, PaymentMethodType.CBE_BILL, 'web' as any, null); + expect(paymentClient.initiate.mock.calls[0][0].payerName).toBe( + 'Abebe Kebede', + ); + }); + + it('leaves the intent expiry unset for an open-ended charge', async () => { + charge.expiresAt = null; + await service.pay(TOKEN, PaymentMethodType.CBE_BILL, 'web' as any, null); + expect(paymentClient.initiate.mock.calls[0][0].expiresAt).toBeUndefined(); + }); + + it('reports a paid charge through getStatus without the payability gate', async () => { + prisma.supplementaryCharge.findUnique.mockResolvedValue({ + ...charge, + status: 'PAID', + paidAt: new Date(), + }); + await expect(service.getStatus(TOKEN)).resolves.toMatchObject({ + status: 'PAID', + paid: true, + }); + }); + }); +}); diff --git a/apps/edr-passenger-web/portal/src/app/pay-balance/[token]/page.tsx b/apps/edr-passenger-web/portal/src/app/pay-balance/[token]/page.tsx index fb2135cd3..da45893e5 100644 --- a/apps/edr-passenger-web/portal/src/app/pay-balance/[token]/page.tsx +++ b/apps/edr-passenger-web/portal/src/app/pay-balance/[token]/page.tsx @@ -1,6 +1,6 @@ "use client"; -import { useState } from "react"; +import { useEffect, useMemo, useState } from "react"; import { useParams, useRouter } from "next/navigation"; import { useQuery, useMutation } from "@tanstack/react-query"; import { apiClient } from "@/lib/api-client"; @@ -8,7 +8,10 @@ import { resolvePaymentRedirectUrl } from "@/lib/payment-redirect"; import { PaymentMethod } from "@/types"; import { Loader2, + Check, + Copy, CreditCard, + KeyRound, Smartphone, Wallet, Landmark, @@ -23,6 +26,28 @@ const getIconForMethod = (methodId: string) => { return Smartphone; }; +// WALLET is an internal balance debit with no supplementary-charge path — the API refuses it, so +// it is never offered here. +const UNSUPPORTED_METHODS = ["WALLET"]; + +// Push-debit methods charge an account we must know before initiating: CAC Bank SMSes a one-time +// password to it, eBirr pushes a USSD PIN prompt to it. Neither opens a hosted page that could +// collect the number afterwards, so it is asked for up front. +const requiresPayerMobile = (method: string | null) => + method === "CAC_BANK" || method === "EBIRR"; + +// DJF has no minor unit; ETB and USD are quoted to cents. Matches the API's charge-side rounding, +// so the quote renders exactly the figure the provider will debit. +const formatAmount = (amount: number, currency: string) => + amount.toFixed(currency.toUpperCase() === "DJF" ? 0 : 2); + +interface AmountQuote { + chargeId: string; + method: string; + currency: string; + amount: number; +} + export default function PayBalancePage() { const { token } = useParams<{ token: string }>(); const router = useRouter(); @@ -30,6 +55,26 @@ export default function PayBalancePage() { const [isProcessing, setIsProcessing] = useState(false); const [paymentError, setPaymentError] = useState(null); + // Push-debit (CAC Bank / eBirr): collect the payer's mobile before initiating, then — for CAC — + // the OTP the bank SMSes to it. + const [phoneModalOpen, setPhoneModalOpen] = useState(false); + const [payerMobile, setPayerMobile] = useState(""); + const [phoneError, setPhoneError] = useState(null); + const [otpModalOpen, setOtpModalOpen] = useState(false); + const [otpCode, setOtpCode] = useState(""); + const [otpMessage, setOtpMessage] = useState(null); + const [otpError, setOtpError] = useState(null); + const [pushMessage, setPushMessage] = useState(null); + + // CBE bill: no redirect and no OTP — the payer walks away with a bill number and pays it at a + // branch/app later, so the page shows the number and watches for settlement. + const [billAction, setBillAction] = useState<{ + billReference: string; + instructions?: string; + expiresAt?: string; + } | null>(null); + const [billCopied, setBillCopied] = useState(false); + const { data: charge, isLoading: loadingCharge, error: chargeError } = useQuery({ queryKey: ["supplementary-charge", token], queryFn: () => apiClient.get(`/payments/supplementary/by-token/${token}`), @@ -45,18 +90,102 @@ export default function PayBalancePage() { enabled: !!charge, }); + const availableMethods = useMemo( + () => + paymentMethods.filter( + (m) => m.enabled && !UNSUPPORTED_METHODS.includes(m.type), + ), + [paymentMethods], + ); + + // The charge is raised in ETB; this is what it costs before a method is chosen. + const chargeCurrency = charge?.currency ?? "ETB"; + const chargeAmount = useMemo( + () => Number(charge?.amountMinor ?? 0) / 100, + [charge], + ); + + // Each method settles in its own currency (WAAFI/DMONEY in DJF, CARD in USD, Ethiopian wallets + // in ETB), so the price has to be re-quoted server-side whenever the selection changes — the + // stored ETB amount is not what a Djiboutian wallet would debit. + const { + data: quote, + isFetching: fetchingQuote, + error: quoteError, + } = useQuery({ + queryKey: ["supplementaryAmount", token, selectedMethod], + queryFn: () => + apiClient.get( + `/payments/supplementary/by-token/${token}/amount?method=${selectedMethod}`, + ), + enabled: !!token && !!selectedMethod, + retry: false, + staleTime: 30_000, + }); + + // A quote is only usable once it belongs to the method currently selected — otherwise it is a + // leftover from the previous selection and would price the payment in the wrong currency. + const quoteReady = !fetchingQuote && quote?.method === selectedMethod; + const displayCurrency = selectedMethod ? (quote?.currency ?? "") : chargeCurrency; + const displayAmount = selectedMethod ? quote?.amount : chargeAmount; + const amountLabel = + quoteReady && displayAmount != null + ? `${displayCurrency} ${formatAmount(displayAmount, displayCurrency)}` + : !selectedMethod && displayAmount != null + ? `${chargeCurrency} ${formatAmount(displayAmount, chargeCurrency)}` + : null; + + // Never let Pay fire against a price the payer has not been shown. + const awaitingQuote = !!selectedMethod && !quoteReady; + const payMutation = useMutation({ - mutationFn: (method: string) => + mutationFn: (vars: { method: string; payerAccount?: string }) => apiClient.post(`/payments/supplementary/by-token/${token}/pay`, { - method, + method: vars.method, platform: "web", + ...(vars.payerAccount ? { payerAccount: vars.payerAccount } : {}), }), onSuccess: (data: any) => { - if (data?.clientAction?.type === "REDIRECT") { - window.location.href = resolvePaymentRedirectUrl(data.clientAction.url); + const action = data?.clientAction; + + if (action?.type === "REDIRECT") { + window.location.href = resolvePaymentRedirectUrl(action.url); return; } - // Immediate success (e.g. wallet) + + // CAC Bank: no redirect — the bank SMS'd an OTP. Collect it here and confirm. + if (action?.type === "COLLECT_OTP") { + setOtpMessage(action.message ?? "Enter the OTP sent to your phone"); + setOtpCode(""); + setOtpError(null); + setOtpModalOpen(true); + setIsProcessing(false); + return; + } + + // CBE: the bill now exists in CBE's system. Nothing to navigate to — show the number. + if (action?.type === "SHOW_BILL_REFERENCE") { + setBillAction({ + billReference: action.billReference, + instructions: action.instructions, + expiresAt: action.expiresAt, + }); + setBillCopied(false); + setIsProcessing(false); + return; + } + + // eBirr: the PIN prompt was pushed to the payer's handset; there is nothing to navigate to. + if (action?.type === "AWAIT_PUSH") { + setPushMessage( + action.message ?? + `Approve the payment on your phone${action.payerAccountMasked ? ` (${action.payerAccountMasked})` : ""}.`, + ); + setIsProcessing(false); + return; + } + + // Immediate success router.push(`/pay-balance/${token}/success`); }, onError: (err: any) => { @@ -67,11 +196,90 @@ export default function PayBalancePage() { }, }); - const handlePay = () => { + // CAC Bank OTP confirmation. A 200 means the debit settled; a 400 is a wrong/expired OTP — + // keep the modal open so the payer can re-enter it (the intent stays open). + const otpMutation = useMutation({ + mutationFn: (otp: string) => + apiClient.post(`/payments/supplementary/by-token/${token}/confirm`, { otp }), + onSuccess: () => { + setOtpModalOpen(false); + router.push(`/pay-balance/${token}/success`); + }, + onError: (err: any) => { + setOtpError( + err?.response?.data?.message ?? + err?.message ?? + "Invalid or expired OTP. Please try again.", + ); + }, + }); + + const startPayment = (mobile?: string) => { if (!selectedMethod) return; setIsProcessing(true); setPaymentError(null); - payMutation.mutate(selectedMethod); + payMutation.mutate({ + method: selectedMethod, + payerAccount: requiresPayerMobile(selectedMethod) ? mobile?.trim() : undefined, + }); + }; + + const handlePay = () => { + if (!selectedMethod || awaitingQuote) return; + setPaymentError(null); + + if (requiresPayerMobile(selectedMethod)) { + // Prefill with the number the charge was raised against, but leave it editable — the + // handset paying is often not the one the booking was made under. + if (!payerMobile.trim() && charge?.booking?.contactPhone) { + setPayerMobile(charge.booking.contactPhone); + } + setPhoneError(null); + setPhoneModalOpen(true); + return; + } + + startPayment(); + }; + + const submitPhone = () => { + if (!payerMobile.trim()) { + setPhoneError("Please enter your mobile number"); + return; + } + setPhoneModalOpen(false); + startPayment(payerMobile); + }; + + // While a bill or a pushed PIN prompt is outstanding, watch the charge. Settlement happens + // server-side — a CBE teller, or the provider's webhook — so the browser has no other signal. + // Success is only ever claimed from this, never from a client-side guess. + const watching = !!billAction || !!pushMessage; + const { data: liveStatus } = useQuery<{ status: string; paid: boolean }>({ + queryKey: ["supplementaryStatus", token], + queryFn: () => + apiClient.get<{ status: string; paid: boolean }>( + `/payments/supplementary/by-token/${token}/status`, + ), + enabled: !!token && watching, + refetchInterval: 5_000, + }); + + useEffect(() => { + if (watching && liveStatus?.paid) { + router.push(`/pay-balance/${token}/success`); + } + }, [watching, liveStatus?.paid, router, token]); + + const copyBillReference = async () => { + if (!billAction) return; + try { + await navigator.clipboard.writeText(billAction.billReference); + setBillCopied(true); + setTimeout(() => setBillCopied(false), 2000); + } catch { + /* clipboard unavailable — the number is still shown on screen */ + } }; if (loadingCharge) { @@ -95,8 +303,6 @@ export default function PayBalancePage() { ); } - const amountDisplay = (charge.amountMinor / 100).toFixed(2); - const currency = charge.currency ?? "ETB"; return (
@@ -122,8 +328,25 @@ export default function PayBalancePage() { )}
Amount due - {currency} {amountDisplay} + {amountLabel ? ( + {amountLabel} + ) : quoteError ? ( + + ) : ( + + )}
+ {selectedMethod && quoteReady && displayCurrency !== chargeCurrency && ( +

+ Converted from {chargeCurrency} {formatAmount(chargeAmount, chargeCurrency)} at today's rate +

+ )} + {quoteError && ( +

+ {(quoteError as any)?.response?.data?.message ?? + "This payment method is unavailable right now. Please choose another."} +

+ )}
{/* Payment methods */} @@ -136,7 +359,7 @@ export default function PayBalancePage() {
) : (
- {paymentMethods.filter((m) => m.enabled).map((method) => { + {availableMethods.map((method) => { const Icon = getIconForMethod(method.type); const isSelected = selectedMethod === method.type; return ( @@ -173,19 +396,180 @@ export default function PayBalancePage() {

🔒 Secure & encrypted payment

+ + {/* CBE bill — show the number; confirmation only ever comes from the status poll */} + {billAction && ( +
+
+
+ +

Pay at CBE

+
+

+ {billAction.instructions ?? + "Pay this bill at any CBE branch, the CBE Birr app, mobile banking or USSD."} +

+
+ + {billAction.billReference} + + +
+
+

+ Amount: ETB {formatAmount(chargeAmount, "ETB")} +

+ {billAction.expiresAt && ( +

+ Pay before:{" "} + + {new Date(billAction.expiresAt).toLocaleString()} + +

+ )} +
+
+ + Waiting for payment confirmation — this page updates automatically once CBE + confirms your payment. +
+ +
+
+ )} + + {/* eBirr: the PIN prompt is on the payer's handset — nothing to navigate to. */} + {pushMessage && ( +
+ +
+

Check your phone

+

{pushMessage}

+
+
+ )} + + {/* Push-debit methods (CAC Bank, eBirr) — collect payer mobile before initiating */} + {phoneModalOpen && ( +
+
+
+ +

Your mobile number

+
+

+ {selectedMethod === "EBIRR" + ? "eBirr will prompt this number for your PIN to authorize the payment. Make sure it's the phone you have with you." + : "CAC Bank will send a one-time password to this number to authorize the payment."} +

+ { setPayerMobile(e.target.value); setPhoneError(null); }} + onKeyDown={(e) => { if (e.key === "Enter") submitPhone(); }} + placeholder={selectedMethod === "EBIRR" ? "09XX XXX XXX" : "77 XX XX XX"} + className="w-full px-3 py-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:border-primary focus:ring-1 focus:ring-primary outline-none" + /> + {phoneError && ( +

⚠️ {phoneError}

+ )} +
+ + +
+
+
+ )} + + {/* CAC Bank OTP entry */} + {otpModalOpen && ( +
+
+
+ +

Enter OTP

+
+

{otpMessage}

+ { setOtpCode(e.target.value.replace(/\D/g, "")); setOtpError(null); }} + onKeyDown={(e) => { if (e.key === "Enter" && otpCode.trim() && !otpMutation.isPending) otpMutation.mutate(otpCode.trim()); }} + placeholder="Enter code" + maxLength={10} + className="w-full text-center tracking-[0.4em] text-lg font-semibold px-3 py-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:border-primary focus:ring-1 focus:ring-primary outline-none" + /> + {otpError && ( +

⚠️ {otpError}

+ )} +
+ + +
+
+
+ )}
); From 33100a31ae7d8f0be96f7cb5285c414f5898dd03 Mon Sep 17 00:00:00 2001 From: Abubeker Yasin Date: Tue, 18 Aug 2026 11:28:10 +0300 Subject: [PATCH 11/14] fix: ( backoffice ) accept phone or username in the login identifier field --- .../backoffice/src/app/login/page.tsx | 37 +++++++++++-------- .../backoffice/src/lib/auth-store.ts | 10 +++-- 2 files changed, 27 insertions(+), 20 deletions(-) diff --git a/apps/edr-passenger-web/backoffice/src/app/login/page.tsx b/apps/edr-passenger-web/backoffice/src/app/login/page.tsx index 4f0098792..899e8cd11 100644 --- a/apps/edr-passenger-web/backoffice/src/app/login/page.tsx +++ b/apps/edr-passenger-web/backoffice/src/app/login/page.tsx @@ -20,13 +20,15 @@ const features = [ ]; export default function LoginPage() { - const [email, setEmail] = useState(''); + // Accepts an email address, phone number, or username — sent to the IAM in + // the `email` field either way (the backend contract does not change). + const [identifier, setIdentifier] = useState(''); const [password, setPassword] = useState(''); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); const [showPassword, setShowPassword] = useState(false); const [isMounted, setIsMounted] = useState(false); - const [emailFocused, setEmailFocused] = useState(false); + const [identifierFocused, setIdentifierFocused] = useState(false); const [passwordFocused, setPasswordFocused] = useState(false); const [view, setView] = useState<'login' | 'forgot'>('login'); @@ -47,7 +49,7 @@ export default function LoginPage() { setLoading(true); setError(''); try { - await login(email, password); + await login(identifier.trim(), password); router.push('/dashboard'); } catch (err: any) { const msg = err.message || err.response?.data?.message || ''; @@ -152,26 +154,29 @@ export default function LoginPage() {
- {/* Email field */} + {/* Identifier field — email, phone number, or username */}
{ setEmail(e.target.value); setError(''); }} - onFocus={() => setEmailFocused(true)} - onBlur={() => setEmailFocused(false)} + type="text" + value={identifier} + onChange={(e) => { setIdentifier(e.target.value); setError(''); }} + onFocus={() => setIdentifierFocused(true)} + onBlur={() => setIdentifierFocused(false)} className="w-full px-4 py-3 rounded-xl bg-white dark:bg-gray-900 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-600 text-sm focus:outline-none" - placeholder="name@edr.com" + placeholder="name@edr.com, +251… or username" required - autoComplete="email" + autoCapitalize="none" + autoCorrect="off" + spellCheck={false} + autoComplete="username" />
@@ -209,7 +214,7 @@ export default function LoginPage() {
- {/* Stats Cards */} + {/* Stats — counts come from the API under the active filters, not the visible page */}
Total Logs
-
{stats.total}
+
{total}
Created
-
{stats.creates}
+
{creates.data?.total ?? '—'}
Updated
-
{stats.updates}
+
{updates.data?.total ?? '—'}
Deleted
-
{stats.deletes}
+
{deletes.data?.total ?? '—'}
{/* Filters */}
-
-
- +
+
+ setFilters({ ...filters, search: e.target.value })} @@ -206,11 +276,11 @@ export default function AuditLogsPage() { onChange={(e) => setFilters({ ...filters, action: e.target.value })} > - - - - - + {actionOptions.map((a) => ( + + ))}
@@ -221,55 +291,42 @@ export default function AuditLogsPage() { onChange={(e) => setFilters({ ...filters, entityType: e.target.value })} > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + {entityTypeOptions.map((t) => ( + + ))}
-
- setFilters({ search: '', action: '', entityType: '' })} - className="w-full" - > - Clear Filters - +
+ + setFilters({ ...filters, from: e.target.value })} + />
+
+ + setFilters({ ...filters, to: e.target.value })} + /> +
+
+
+ setFilters({ search: '', action: '', entityType: '', from: '', to: '' })} + > + Clear Filters +
- {/* Data Table */} + {/* Pagination */} +
+

+ {total === 0 + ? 'No results' + : `Showing ${page * PAGE_SIZE + 1}–${Math.min((page + 1) * PAGE_SIZE, total)} of ${total}`} +

+
+ setPage((p) => Math.max(0, p - 1))} + > + Previous + + + Page {page + 1} of {pageCount} + + = pageCount} + onClick={() => setPage((p) => p + 1)} + > + Next + +
+
+ {/* Details Modal */} { setShowDetailsModal(false); setSelectedLog(null); }} + onClose={() => { + setShowDetailsModal(false); + setSelectedLog(null); + }} title="Audit Log Details" size="xl" > - {selectedLog && (() => { - const l = selectedLog; - const actionColor: Record = { - CREATE: 'from-emerald-600 to-emerald-700', - UPDATE: 'from-blue-600 to-blue-700', - DELETE: 'from-red-600 to-red-700', - LOGIN: 'from-violet-600 to-violet-700', - LOGOUT: 'from-gray-600 to-gray-700', - }; - const gradient = actionColor[l.action] || 'from-gray-600 to-gray-700'; + {selectedLog && + (() => { + const l: AuditLog = selectedLog; + const gradient = CREATIVE_ACTIONS.has(l.action) + ? 'from-emerald-600 to-emerald-700' + : DESTRUCTIVE_ACTIONS.has(l.action) + ? 'from-red-600 to-red-700' + : 'from-blue-600 to-blue-700'; - const Field = ({ label, value, mono = false, truncate = false }: { label: string; value: string; mono?: boolean; truncate?: boolean }) => ( -
-

{label}

-

{value || '—'}

-
- ); - - const SectionHeader = ({ title }: { title: string }) => ( -

- {title} -

- ); - - return ( -
-
-
-
-

Action

-

{l.action}

-
-
- {l.entityType} -

{formatDateTime(l.createdAt)}

-
-
-
-
-

User

-

{l.user?.fullName || 'System'}

-
-
-

IP Address

-

{l.ipAddress || 'N/A'}

-
-
+ const Field = ({ + label, + value, + mono = false, + truncate = false, + }: { + label: string; + value?: string; + mono?: boolean; + truncate?: boolean; + }) => ( +
+

{label}

+

+ {value || '—'} +

+ ); -
-
- -
- - - - + const SectionHeader = ({ title }: { title: string }) => ( +

+ + {title} +

+ ); + + return ( +
+
+
+
+

Action

+

{l.action}

+
+
+ + {l.entityType} + +

{formatDateTime(l.createdAt)}

+
-
+
+
+

User

+

{actorName(l)}

+
+
+

IP Address

+

{l.ipAddress || 'N/A'}

+
+
+
+ +
+
+ +
+ + + + +
+
- {l.user && (
- - - + + +
- )} - {(l.ipAddress || l.userAgent) && ( -
- -
- -
-

User Agent

-

{l.userAgent || '—'}

+ {(l.ipAddress || l.userAgent) && ( +
+ +
+ +
+

User Agent

+

+ {l.userAgent || '—'} +

+
-
-
- )} + + )} + + {(l.oldData || l.newData) && ( +
+ +
+ {l.oldData && ( +
+

+ ← Before +

+
+                              {formatJsonData(l.oldData)}
+                            
+
+ )} + {l.newData && ( +
+

+ → After +

+
+                              {formatJsonData(l.newData)}
+                            
+
+ )} +
+
+ )} - {(l.oldData || l.newData) && (
- -
- {l.oldData && ( -
-

← Before

-
-                            {formatJsonData(l.oldData)}
-                          
-
- )} - {l.newData && ( -
-

→ After

-
-                            {formatJsonData(l.newData)}
-                          
-
- )} + +
+
- )} +
-
- -
- -
-
+
+ { + setShowDetailsModal(false); + setSelectedLog(null); + }} + > + Close + +
- -
- { setShowDetailsModal(false); setSelectedLog(null); }}>Close -
-
- ); - })()} + ); + })()}
); } + +export default function AuditLogsPage() { + return ( + + + + ); +} diff --git a/apps/edr-passenger-web/backoffice/src/lib/api/index.ts b/apps/edr-passenger-web/backoffice/src/lib/api/index.ts index f528f9dff..7350928b3 100644 --- a/apps/edr-passenger-web/backoffice/src/lib/api/index.ts +++ b/apps/edr-passenger-web/backoffice/src/lib/api/index.ts @@ -380,7 +380,11 @@ export const verifaydaApi = { // Audit API export const auditApi = { getLogs: async (params?: any) => { - const query = new URLSearchParams(params as Record).toString(); + // Drop empty filters so a blank search box doesn't send `search=` and match nothing. + const entries = Object.entries(params ?? {}).filter( + ([, v]) => v !== undefined && v !== null && v !== '', + ); + const query = new URLSearchParams(entries as [string, string][]).toString(); const response = await apiClient.get(`/audit/logs${query ? `?${query}` : ''}`); if (response?.data) { return Array.isArray(response.data) ? { items: response.data } : response; @@ -388,6 +392,7 @@ export const auditApi = { return Array.isArray(response) ? { items: response } : response; }, getLog: (id: string) => apiClient.get(`/audit/logs/${id}`), + getVocabulary: () => apiClient.get('/audit/vocabulary'), }; // Live Tracking API diff --git a/apps/edr-passenger-web/backoffice/src/types/edr.ts b/apps/edr-passenger-web/backoffice/src/types/edr.ts index 1b5ca7a1e..fa864eb71 100644 --- a/apps/edr-passenger-web/backoffice/src/types/edr.ts +++ b/apps/edr-passenger-web/backoffice/src/types/edr.ts @@ -301,7 +301,11 @@ export interface FraudRule { // Audit Types export interface AuditLog { id: string; - userId?: string; + /** IAM id of the staff member who performed the action. The API field is `iamUserId`. */ + iamUserId?: string; + /** Actor's name and phone, denormalized by the API at write time. */ + userName?: string; + userPhone?: string; action: string; entityType: string; entityId?: string; From 1f38b5a3c601eade92ffbb253a6360c3fe0ab7dc Mon Sep 17 00:00:00 2001 From: Abubeker Yasin Date: Wed, 19 Aug 2026 09:25:51 +0300 Subject: [PATCH 13/14] fix: ( fayda ) block one Fayda identity from verifying multiple passengers --- .../src/modules/verifayda/verifayda.dto.ts | 8 ++++ .../modules/verifayda/verifayda.service.ts | 18 ++++++++- .../src/app/booking/passengers/page.tsx | 39 ++++++++++++++++--- 3 files changed, 58 insertions(+), 7 deletions(-) diff --git a/apps/edr-passenger-api/src/modules/verifayda/verifayda.dto.ts b/apps/edr-passenger-api/src/modules/verifayda/verifayda.dto.ts index 26108a452..901118389 100644 --- a/apps/edr-passenger-api/src/modules/verifayda/verifayda.dto.ts +++ b/apps/edr-passenger-api/src/modules/verifayda/verifayda.dto.ts @@ -57,6 +57,14 @@ export class CompleteVerificationResultDto { agentId?: string; }; + @ApiPropertyOptional({ + description: + 'eSignet subject identifier for the verified individual (VERIFY flow). A PSUT — ' + + 'pairwise and stable per client_id, never the FIN. The booking flow compares it across ' + + 'passengers so one Fayda identity cannot verify more than one passenger on a booking.', + }) + faydaSub?: string; + @ApiPropertyOptional({ description: 'Verified full name from Fayda (VERIFY flow).' }) fullName?: string; diff --git a/apps/edr-passenger-api/src/modules/verifayda/verifayda.service.ts b/apps/edr-passenger-api/src/modules/verifayda/verifayda.service.ts index df6cfc21d..42376d4a1 100644 --- a/apps/edr-passenger-api/src/modules/verifayda/verifayda.service.ts +++ b/apps/edr-passenger-api/src/modules/verifayda/verifayda.service.ts @@ -70,11 +70,19 @@ export interface FaydaUserSummary { /** * Result of completing a verification. `verified` is always true on success. * LOGIN additionally returns a JWT + user; VERIFY returns the verified identity - * attributes (name, email, phone, dob, gender) for the caller to consume. + * attributes (name, email, phone, dob, gender, faydaSub) for the caller to consume. */ export interface CompleteVerificationResult { purpose: VerifaydaPurpose; verified: boolean; + /** + * eSignet subject identifier for the verified individual. This is a PSUT — + * pairwise and stable per `client_id`, never the FIN — so it is safe to hand + * to the browser, and it is the same value `/passengers/me` already returns. + * The booking flow uses it to stop one Fayda identity from verifying more + * than one passenger on the same booking. + */ + faydaSub?: string; token?: string; refreshToken?: string; requiresPassword?: boolean; @@ -280,6 +288,7 @@ export class VerifaydaService { result = { purpose: 'VERIFY', verified: true, + faydaSub: normalized.sub, fullName: normalized.fullName, email: normalized.email, phoneNumber: normalized.phoneNumber, @@ -357,6 +366,13 @@ export class VerifaydaService { code_challenge_method: 'S256', acr_values: this.faydaConfig.acrValues, claims_locales: this.faydaConfig.claimsLocales, + // Force a fresh authentication instead of silently reusing the eSignet + // SSO session. A booking can carry several passengers, each of whom must + // verify with their OWN Fayda; without this, the second and third + // "Verify with Fayda" clicks round-trip in a couple of seconds and hand + // back the first passenger's identity, which the booking flow then has to + // reject with no way for the user to authenticate as the right person. + prompt: 'login', }); // Every claim is marked essential so eSignet shows them locked/pre-checked diff --git a/apps/edr-passenger-web/portal/src/app/booking/passengers/page.tsx b/apps/edr-passenger-web/portal/src/app/booking/passengers/page.tsx index 60cd350a2..b48d64d96 100644 --- a/apps/edr-passenger-web/portal/src/app/booking/passengers/page.tsx +++ b/apps/edr-passenger-web/portal/src/app/booking/passengers/page.tsx @@ -740,6 +740,10 @@ function PassengersForm() { passportExpiryDate: stored.passportExpiryDate || '', passportIssuingAuthority: stored.passportIssuingAuthority || '', faydaVerified: stored.faydaVerified || false, + // Restore the identity that verified this passenger, so returning here from a + // later step (e.g. Back from /booking/seats) doesn't silently reopen the slot to + // an already-used Fayda. + faydaSub: stored.faydaSub || undefined, formExpanded: true, }; } @@ -852,13 +856,22 @@ function PassengersForm() { if (d?.verified) { const faydaSub: string | undefined = d.sub || d.faydaSub || d.fin; - // A single Fayda identity can't be reused across two different passengers. - const usedByOther = faydaSub && passengers.some( - (p, i) => i !== targetIndex && (p as any).faydaSub === faydaSub, - ); + // A single Fayda identity can't be reused across two different passengers. Read the + // live form rather than the `passengers` captured when this effect was created — the + // snapshot restore repopulates the array as the form initializes. + const currentPassengers = watch('passengers') || []; + const conflictIndex = faydaSub + ? currentPassengers.findIndex( + (p, i) => i !== targetIndex && (p as any)?.faydaSub === faydaSub, + ) + : -1; - if (usedByOther) { - setFaydaErrors((prev) => ({ ...prev, [targetIndex]: 'This Fayda identity is already linked to another passenger on this booking.' })); + if (conflictIndex >= 0) { + const conflictName = currentPassengers[conflictIndex]?.name?.trim(); + setFaydaErrors((prev) => ({ + ...prev, + [targetIndex]: `This Fayda ID has already been used to verify Passenger ${conflictIndex + 1}${conflictName ? ` (${conflictName})` : ''}. Each traveller must verify with their own Fayda.`, + })); setVerificationStatus((prev) => ({ ...prev, [targetIndex]: 'error' })); } else { // Convert "1980/12/01" → "1980-12-01" @@ -963,6 +976,13 @@ function PassengersForm() { const emailVal = pick(passengerData.email, user.email); if (emailVal) setValue('passengers.0.email', emailVal); + // A logged-in, already-verified user occupies slot 0 without going through a fresh + // Fayda round trip, so the callback never records their sub on the form. Seed it from + // the account here, otherwise the duplicate-identity check has nothing to compare + // against and the account holder can re-use their own Fayda on passenger 2. + const accountFaydaSub = pick(passengerData.faydaSub, (user as any).faydaSub); + if (accountFaydaSub) setValue('passengers.0.faydaSub', accountFaydaSub); + if (mustVerifyFayda) { // Force the Fayda gate: leave name/DOB/gender empty and keep the form collapsed so the // "Verify with Fayda" screen is shown instead of an editable, pre-filled form. @@ -1077,6 +1097,13 @@ function PassengersForm() { gender: p.gender, nationality: p.nationality, nationalId: p.nationalId, + // Carry the verified Fayda identity into the booking store so the duplicate-identity + // check still has it if the user comes back to this page from /booking/seats. Without + // it the restore path below rebuilds each passenger without a sub, and one Fayda could + // then re-verify every passenger. Stripped server-side by the global ValidationPipe + // (whitelist: true), so sending it to /passengers/save-details is a no-op there. + faydaVerified: p.faydaVerified, + faydaSub: p.faydaSub, passportNumber: p.passportNumber, passportCountry: p.passportCountry, passportIssueDate: p.passportIssueDate, From 014b1a6d472b8dbad97da179de1e23c09a60f4a8 Mon Sep 17 00:00:00 2001 From: Abubeker Yasin Date: Wed, 19 Aug 2026 15:28:10 +0300 Subject: [PATCH 14/14] fix: ( fayda ) reject a second booking for the same identity on one departure --- .../bookings/booking-identity.util.spec.ts | 130 ++++++++++++++++++ .../modules/bookings/booking-identity.util.ts | 96 +++++++++++++ .../src/modules/bookings/bookings.dto.ts | 19 ++- .../src/modules/bookings/bookings.service.ts | 33 ++++- .../src/modules/bookings/guest-booking.dto.ts | 13 +- .../modules/bookings/guest-booking.service.ts | 35 ++++- .../portal/src/app/booking/review/page.tsx | 6 + 7 files changed, 321 insertions(+), 11 deletions(-) create mode 100644 apps/edr-passenger-api/src/modules/bookings/booking-identity.util.spec.ts create mode 100644 apps/edr-passenger-api/src/modules/bookings/booking-identity.util.ts diff --git a/apps/edr-passenger-api/src/modules/bookings/booking-identity.util.spec.ts b/apps/edr-passenger-api/src/modules/bookings/booking-identity.util.spec.ts new file mode 100644 index 000000000..f1acb6cd2 --- /dev/null +++ b/apps/edr-passenger-api/src/modules/bookings/booking-identity.util.spec.ts @@ -0,0 +1,130 @@ +import { BadRequestException } from '@nestjs/common'; +import { IdDocumentType } from '@prisma/client'; +import { + assertIdentitiesNotAlreadyBooked, + resolveIdentityRef, +} from './booking-identity.util'; +import { PrismaService } from '../../common/prisma.service'; + +// ── Fixtures ───────────────────────────────────────────────────────────────── + +const SCHEDULE = 'schedule-1'; +const RETURN_SCHEDULE = 'schedule-2'; + +const makePrisma = (clash: any = null) => + ({ bookingSeat: { findFirst: jest.fn().mockResolvedValue(clash) } }) as unknown as PrismaService; + +const traveller = (passengerName: string, identityRef: string | null) => ({ + passengerName, + identityRef, +}); + +// ── resolveIdentityRef ─────────────────────────────────────────────────────── + +describe('resolveIdentityRef', () => { + it('uses the Fayda sub for national-ID travellers', () => { + expect( + resolveIdentityRef({ + idDocumentType: IdDocumentType.NATIONAL_ID, + faydaSub: 'psut-abc', + passportNumber: 'P1234567', + }), + ).toBe('psut-abc'); + }); + + it('uses the passport number for passport travellers, normalised to upper case', () => { + expect( + resolveIdentityRef({ + idDocumentType: IdDocumentType.PASSPORT, + faydaSub: 'psut-abc', + passportNumber: ' p1234567 ', + }), + ).toBe('P1234567'); + }); + + it('returns null when there is nothing to key on — children and Fayda-disabled bookings', () => { + expect(resolveIdentityRef({ idDocumentType: IdDocumentType.NATIONAL_ID })).toBeNull(); + expect( + resolveIdentityRef({ idDocumentType: IdDocumentType.NATIONAL_ID, faydaSub: ' ' }), + ).toBeNull(); + expect(resolveIdentityRef({ idDocumentType: IdDocumentType.PASSPORT })).toBeNull(); + }); +}); + +// ── assertIdentitiesNotAlreadyBooked ───────────────────────────────────────── + +describe('assertIdentitiesNotAlreadyBooked', () => { + it('rejects the same identity used twice inside one payload', async () => { + const prisma = makePrisma(); + await expect( + assertIdentitiesNotAlreadyBooked( + prisma, + [traveller('Abebe Kebede', 'psut-abc'), traveller('Sara Ali', 'psut-abc')], + [SCHEDULE], + ), + ).rejects.toThrow(BadRequestException); + // Rejected before touching the database. + expect(prisma.bookingSeat.findFirst).not.toHaveBeenCalled(); + }); + + it('ignores passengers with no identity — two children never collide with each other', async () => { + const prisma = makePrisma(); + await expect( + assertIdentitiesNotAlreadyBooked( + prisma, + [traveller('Child One', null), traveller('Child Two', null)], + [SCHEDULE], + ), + ).resolves.toBeUndefined(); + expect(prisma.bookingSeat.findFirst).not.toHaveBeenCalled(); + }); + + it('queries every leg of the booking, de-duplicated, for active bookings only', async () => { + const prisma = makePrisma(); + await assertIdentitiesNotAlreadyBooked( + prisma, + [traveller('Abebe Kebede', 'psut-abc')], + [SCHEDULE, RETURN_SCHEDULE, SCHEDULE, null, undefined], + ); + + const { where } = (prisma.bookingSeat.findFirst as jest.Mock).mock.calls[0][0]; + expect(where.scheduleId).toEqual({ in: [SCHEDULE, RETURN_SCHEDULE] }); + expect(where.idDocumentNumber).toEqual({ in: ['psut-abc'] }); + expect(where.booking.status.in).toEqual(['DRAFT', 'PENDING_PAYMENT', 'CONFIRMED', 'BOARDED']); + }); + + it('rejects an identity that already holds a ticket on the departure', async () => { + const prisma = makePrisma({ + idDocumentNumber: 'psut-abc', + passengerName: 'Abebe K.', + booking: { bookingRef: 'ABCDEF', status: 'CONFIRMED' }, + }); + + await expect( + assertIdentitiesNotAlreadyBooked(prisma, [traveller('Abebe Kebede', 'psut-abc')], [SCHEDULE]), + ).rejects.toThrow(/Abebe Kebede already has a ticket on this train \(booking ABCDEF\)/); + }); + + it('points an unpaid clash at the booking the traveller still has to settle', async () => { + const prisma = makePrisma({ + idDocumentNumber: 'psut-abc', + passengerName: 'Abebe K.', + booking: { bookingRef: 'ABCDEF', status: 'PENDING_PAYMENT' }, + }); + + await expect( + assertIdentitiesNotAlreadyBooked(prisma, [traveller('Abebe Kebede', 'psut-abc')], [SCHEDULE]), + ).rejects.toThrow(/already has an unpaid booking \(ABCDEF\)/); + }); + + it('allows the booking when nothing active matches — a cancelled ticket frees the identity', async () => { + const prisma = makePrisma(null); + await expect( + assertIdentitiesNotAlreadyBooked( + prisma, + [traveller('Abebe Kebede', 'psut-abc'), traveller('Sara Ali', 'P7654321')], + [SCHEDULE], + ), + ).resolves.toBeUndefined(); + }); +}); diff --git a/apps/edr-passenger-api/src/modules/bookings/booking-identity.util.ts b/apps/edr-passenger-api/src/modules/bookings/booking-identity.util.ts new file mode 100644 index 000000000..cd5385765 --- /dev/null +++ b/apps/edr-passenger-api/src/modules/bookings/booking-identity.util.ts @@ -0,0 +1,96 @@ +import { BadRequestException } from '@nestjs/common'; +import { BookingStatus, IdDocumentType } from '@prisma/client'; +import { PrismaService } from '../../common/prisma.service'; + +/** + * Booking states that still hold a traveller's place on a departure. CANCELLED, REFUNDED and + * NO_SHOW are deliberately excluded: cancelling a ticket must immediately free the identity so + * the same person can book that train again. PENDING_PAYMENT counts — otherwise the whole check + * is bypassable by simply never finishing the first payment. + */ +const ACTIVE_BOOKING_STATUSES: BookingStatus[] = [ + BookingStatus.DRAFT, + BookingStatus.PENDING_PAYMENT, + BookingStatus.CONFIRMED, + BookingStatus.BOARDED, +]; + +/** + * The single value that identifies a human across bookings: the Fayda subject identifier (PSUT) + * for Ethiopians, the passport number for everyone else. It is written to + * `BookingSeat.idDocumentNumber` — an existing column, so no migration — and compared there. + * + * Returns null when there is nothing to key on: children under 5 have no Fayda, and neither does + * a booking made while the Fayda integration is switched off. Those passengers are simply not + * deduplicated rather than being blocked. + * + * Both inputs come from the client, so this stops honest misuse of the booking form, not a + * hand-crafted POST. Binding the sub to the server-side verification session is the follow-up + * that would make it tamper-proof. + */ +export function resolveIdentityRef(passenger: { + idDocumentType?: IdDocumentType | null; + faydaSub?: string | null; + passportNumber?: string | null; +}): string | null { + if (passenger.idDocumentType === IdDocumentType.PASSPORT) { + // Hand-typed, so normalise case — "p1234567" and "P1234567" are the same document. + const passport = passenger.passportNumber?.trim().toUpperCase(); + return passport || null; + } + const sub = passenger.faydaSub?.trim(); + return sub || null; +} + +/** + * Rejects a booking when one identity would occupy more than one seat on the same departure — + * either twice within this payload, or once here and once on an existing active booking. + * + * Keyed on `BookingSeat.scheduleId`, which is per leg, so round-trip outbound/return and transit + * leg-1/leg-2 are naturally treated as separate departures and never collide with each other. + */ +export async function assertIdentitiesNotAlreadyBooked( + prisma: PrismaService, + passengers: Array<{ passengerName: string; identityRef: string | null }>, + scheduleIds: Array, +): Promise { + const nameByIdentity = new Map(); + for (const passenger of passengers) { + if (!passenger.identityRef) continue; + const alreadyUsedBy = nameByIdentity.get(passenger.identityRef); + if (alreadyUsedBy !== undefined) { + throw new BadRequestException( + `${passenger.passengerName} and ${alreadyUsedBy} were verified with the same identity. ` + + `Each traveller must be verified with their own Fayda or passport.`, + ); + } + nameByIdentity.set(passenger.identityRef, passenger.passengerName); + } + + const identityRefs = [...nameByIdentity.keys()]; + const targetScheduleIds = [...new Set(scheduleIds.filter((id): id is string => !!id))]; + if (!identityRefs.length || !targetScheduleIds.length) return; + + const clash = await prisma.bookingSeat.findFirst({ + where: { + scheduleId: { in: targetScheduleIds }, + idDocumentNumber: { in: identityRefs }, + booking: { status: { in: ACTIVE_BOOKING_STATUSES } }, + }, + select: { + idDocumentNumber: true, + passengerName: true, + booking: { select: { bookingRef: true, status: true } }, + }, + }); + if (!clash) return; + + const traveller = nameByIdentity.get(clash.idDocumentNumber!) ?? clash.passengerName; + throw new BadRequestException( + clash.booking.status === BookingStatus.PENDING_PAYMENT + ? `${traveller} already has an unpaid booking (${clash.booking.bookingRef}) on this train. ` + + `Complete or cancel that booking before making a new one.` + : `${traveller} already has a ticket on this train (booking ${clash.booking.bookingRef}). ` + + `Each traveller may hold only one ticket per departure.`, + ); +} diff --git a/apps/edr-passenger-api/src/modules/bookings/bookings.dto.ts b/apps/edr-passenger-api/src/modules/bookings/bookings.dto.ts index 42d4af0d9..454339516 100644 --- a/apps/edr-passenger-api/src/modules/bookings/bookings.dto.ts +++ b/apps/edr-passenger-api/src/modules/bookings/bookings.dto.ts @@ -18,6 +18,7 @@ export class PassengerInputDto { dateOfBirth: Date; @ApiProperty({ example: 'NATIONAL_ID', enum: IdDocumentType, description: 'NATIONAL_ID for Ethiopians (Verifayda verified), PASSPORT for others' }) @IsEnum(IdDocumentType) idDocumentType: IdDocumentType; @ApiPropertyOptional({ example: 'ET123456789', description: 'Ethiopian national ID - verified via Verifayda 2.0 (NOT stored in database)' }) @IsOptional() @IsString() idDocumentNumber?: string; + @ApiPropertyOptional({ example: '8267a1f4-...', description: 'Fayda subject identifier (PSUT) from POST /fayda/verification/complete. Stored on the booking seat and compared across bookings so one Fayda identity cannot hold two seats on the same departure.' }) @IsOptional() @IsString() faydaSub?: string; @ApiPropertyOptional({ example: 'P1234567', description: 'Passport number for non-Ethiopian passengers (no verification)' }) @IsOptional() @IsString() passportNumber?: string; @ApiPropertyOptional({ example: 'Djibouti', description: 'Passport issuing country for non-Ethiopians' }) @IsOptional() @IsString() passportCountry?: string; @ApiPropertyOptional({ example: 'Ethiopian', description: 'Ethiopian (Verifayda + Telebirr/CBE/eBirr), Djiboutian (Passport + Waafi), Other (Passport + Card)' }) @IsOptional() @IsString() nationality?: string; @@ -67,11 +68,19 @@ export class RoundTripPassengerDto { description: 'Ethiopian national ID - verified via Verifayda 2.0 (NOT stored in database)' }) @IsOptional() @IsString() idDocumentNumber?: string; - - @ApiPropertyOptional({ - example: 'P1234567', - description: 'Passport number for non-Ethiopian passengers (no verification)' - }) + + @ApiPropertyOptional({ + example: '8267a1f4-...', + description: + 'Fayda subject identifier (PSUT) from POST /fayda/verification/complete. Stored on the booking seat ' + + 'and compared across bookings so one Fayda identity cannot hold two seats on the same departure.' + }) + @IsOptional() @IsString() faydaSub?: string; + + @ApiPropertyOptional({ + example: 'P1234567', + description: 'Passport number for non-Ethiopian passengers (no verification)' + }) @IsOptional() @IsString() passportNumber?: string; @ApiPropertyOptional({ diff --git a/apps/edr-passenger-api/src/modules/bookings/bookings.service.ts b/apps/edr-passenger-api/src/modules/bookings/bookings.service.ts index 7f0a6eee5..d2a9825ec 100644 --- a/apps/edr-passenger-api/src/modules/bookings/bookings.service.ts +++ b/apps/edr-passenger-api/src/modules/bookings/bookings.service.ts @@ -6,6 +6,7 @@ import { SeatsService } from '../seats/seats.service'; import { TicketsService } from '../tickets/tickets.service'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { CreateBookingDto, ModifyBookingDto } from './bookings.dto'; +import { assertIdentitiesNotAlreadyBooked, resolveIdentityRef } from './booking-identity.util'; import { Cron, CronExpression } from '@nestjs/schedule'; import { VerifaydaService } from '../verifayda/verifayda.service'; import { CurrencyService } from '../currency/currency.service'; @@ -861,6 +862,11 @@ export class BookingsService { this.resolveIamContact(dto.passengerId), ]); const { adultCount, childCount } = this.countPassengers(passengersData); + + // One traveller, one seat per departure — checked before any fare/hold work so a rejected + // booking leaves nothing behind. + await assertIdentitiesNotAlreadyBooked(this.prisma, passengersData, [dto.scheduleId]); + const fareCalculation = dto.packageId && dto.priceTierId ? await this.calculatePackageFare(dto.priceTierId, adultCount, childCount) : await this.calculateFare(dto.scheduleId, dto.seatClassId, originStop, destStop, passengersData[0]?.nationality, adultCount, childCount, dto.promoCode, dto.loyaltyRedemptionPoints); @@ -988,6 +994,7 @@ export class BookingsService { dateOfBirth: p.dateOfBirth, passengerCategory: p.category, idDocumentType: p.idDocumentType, + idDocumentNumber: p.identityRef, passportNumber: p.passportNumber, passportCountry: p.passportCountry, verifaydaVerified: p.verifaydaVerified, @@ -1058,6 +1065,11 @@ export class BookingsService { ]); const { adultCount, childCount } = this.countPassengers(passengersData); + await assertIdentitiesNotAlreadyBooked(this.prisma, passengersData, [ + dto.scheduleId, + dto.returnScheduleId, + ]); + // Package bookings use fixed tier price split equally across both legs let outboundFare: Awaited>; let returnFare: Awaited>; @@ -1196,6 +1208,7 @@ export class BookingsService { dateOfBirth: p.dateOfBirth, passengerCategory: p.category, idDocumentType: p.idDocumentType, + idDocumentNumber: p.identityRef, passportNumber: p.passportNumber, passportCountry: p.passportCountry, verifaydaVerified: p.verifaydaVerified, @@ -1211,6 +1224,7 @@ export class BookingsService { dateOfBirth: p.dateOfBirth, passengerCategory: p.category, idDocumentType: p.idDocumentType, + idDocumentNumber: p.identityRef, passportNumber: p.passportNumber, passportCountry: p.passportCountry, verifaydaVerified: p.verifaydaVerified, @@ -1301,6 +1315,11 @@ export class BookingsService { ]); const { adultCount, childCount } = this.countPassengers(passengersData); + await assertIdentitiesNotAlreadyBooked(this.prisma, passengersData, [ + dto.scheduleId, + dto.leg2ScheduleId, + ]); + const leg2SeatClassId = dto.leg2SeatClassId ?? dto.seatClassId; const [leg1Fare, leg2Fare] = await Promise.all([ this.calculateFare(dto.scheduleId, dto.seatClassId, leg1OriginStop, leg1DestStop, passengersData[0]?.nationality, adultCount, childCount), @@ -1386,6 +1405,7 @@ export class BookingsService { dateOfBirth: p.dateOfBirth, passengerCategory: p.category, idDocumentType: p.idDocumentType, + idDocumentNumber: p.identityRef, passportNumber: p.passportNumber, passportCountry: p.passportCountry, verifaydaVerified: p.verifaydaVerified, @@ -1401,6 +1421,7 @@ export class BookingsService { dateOfBirth: p.dateOfBirth, passengerCategory: p.category, idDocumentType: p.idDocumentType, + idDocumentNumber: p.identityRef, passportNumber: p.passportNumber, passportCountry: p.passportCountry, verifaydaVerified: p.verifaydaVerified, @@ -1495,6 +1516,14 @@ export class BookingsService { this.resolveIamContact(dto.passengerId), ]); const { adultCount, childCount } = this.countPassengers(passengersData); + + await assertIdentitiesNotAlreadyBooked(this.prisma, passengersData, [ + dto.scheduleId, + dto.leg2ScheduleId, + dto.returnScheduleId, + dto.returnLeg2ScheduleId, + ]); + const nat = passengersData[0]?.nationality; const obL2SeatClassId = dto.leg2SeatClassId ?? dto.seatClassId; @@ -1558,6 +1587,7 @@ export class BookingsService { dateOfBirth: p.dateOfBirth, passengerCategory: p.category, idDocumentType: p.idDocumentType, + idDocumentNumber: p.identityRef, passportNumber: p.passportNumber, passportCountry: p.passportCountry, verifaydaVerified: p.verifaydaVerified, @@ -1659,7 +1689,7 @@ export class BookingsService { nationality = nationality || (passenger.passportCountry === 'Djibouti' ? 'Djiboutian' : 'Other'); } - processedPassengers.push({ ...passenger, passengerName, dateOfBirth, category, verifaydaVerified, verifaydaData, nationality }); + processedPassengers.push({ ...passenger, passengerName, dateOfBirth, category, verifaydaVerified, verifaydaData, nationality, identityRef: resolveIdentityRef(passenger) }); } return processedPassengers; } @@ -1696,6 +1726,7 @@ export class BookingsService { verifaydaVerified, verifaydaData, nationality, + identityRef: resolveIdentityRef(passenger), // Normalise: PassengerInputDto uses seatId/returnSeatId; RoundTripPassengerDto uses // outboundSeatId/returnSeatId. Accept either form so both DTOs work. outboundSeatId: passenger.outboundSeatId ?? passenger.seatId, diff --git a/apps/edr-passenger-api/src/modules/bookings/guest-booking.dto.ts b/apps/edr-passenger-api/src/modules/bookings/guest-booking.dto.ts index ac60b8480..7065b6183 100644 --- a/apps/edr-passenger-api/src/modules/bookings/guest-booking.dto.ts +++ b/apps/edr-passenger-api/src/modules/bookings/guest-booking.dto.ts @@ -25,10 +25,19 @@ export class GuestPassengerDto { @ApiProperty({ example: 'NATIONAL_ID', enum: IdDocumentType, description: 'NATIONAL_ID for Ethiopians (Verifayda verified), PASSPORT for others' }) @IsEnum(IdDocumentType) idDocumentType: IdDocumentType; - @ApiPropertyOptional({ example: 'ET123456789', description: 'Ethiopian national ID - verified via Verifayda 2.0 (NOT stored)' }) + @ApiPropertyOptional({ example: 'ET123456789', description: 'Ethiopian national ID - verified via Verifayda 2.0 (NOT stored)' }) @IsOptional() @IsString() idDocumentNumber?: string; - @ApiPropertyOptional({ example: 'P1234567', description: 'Passport number for non-Ethiopians' }) + @ApiPropertyOptional({ + example: '8267a1f4-...', + description: + 'Fayda subject identifier (PSUT) returned by POST /fayda/verification/complete for this traveller. ' + + 'Stored on the booking seat and compared across bookings so one Fayda identity cannot hold two ' + + 'seats on the same departure. Omit for children under 5 and non-Ethiopians (the passport number is used instead).', + }) + @IsOptional() @IsString() faydaSub?: string; + + @ApiPropertyOptional({ example: 'P1234567', description: 'Passport number for non-Ethiopians' }) @IsOptional() @IsString() passportNumber?: string; @ApiPropertyOptional({ example: 'Djibouti', description: 'Passport issuing country' }) diff --git a/apps/edr-passenger-api/src/modules/bookings/guest-booking.service.ts b/apps/edr-passenger-api/src/modules/bookings/guest-booking.service.ts index c8061184f..0414296a4 100644 --- a/apps/edr-passenger-api/src/modules/bookings/guest-booking.service.ts +++ b/apps/edr-passenger-api/src/modules/bookings/guest-booking.service.ts @@ -12,6 +12,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter'; import { PaymentsService } from '../payments/payments.service'; import { SmsClientService } from '../notifications/sms-client.service'; import { CreateGuestBookingDto, SavedPassengerProfileDto, IssueReservationBookingDto, ReservationBookingKind } from './guest-booking.dto'; +import { assertIdentitiesNotAlreadyBooked, resolveIdentityRef } from './booking-identity.util'; import { Currency, PassengerCategory, IdDocumentType, PaymentMethodType, PaymentIntentStatus } from '@prisma/client'; import { resolveCheckinCutoff } from '../../common/utils/checkin-cutoff.utils'; import { computePaymentDeadline } from '../../common/utils/payment-deadline.utils'; @@ -225,9 +226,14 @@ export class GuestBookingService { verifaydaVerified, verifaydaData, nationality, + identityRef: resolveIdentityRef(passenger), }); } + // One traveller, one seat per departure — checked before any fare/hold work so a rejected + // booking leaves nothing behind. + await assertIdentitiesNotAlreadyBooked(this.prisma, passengersData, [dto.scheduleId]); + // Calculate fare — package bookings use the fixed tier price, bypassing the fare engine const isPackageOneway = !!dto.packageId && !!dto.priceTierId; let baseFareMinor: number; @@ -392,6 +398,7 @@ export class GuestBookingService { dateOfBirth: p.dateOfBirth, passengerCategory: p.category, idDocumentType: p.idDocumentType, + idDocumentNumber: p.identityRef, passportNumber: p.passportNumber, passportCountry: p.passportCountry, verifaydaVerified: p.verifaydaVerified, @@ -772,9 +779,14 @@ export class GuestBookingService { nationality = nationality || 'Other'; } - passengersData.push({ ...passenger, passengerName, dateOfBirth, category, verifaydaVerified, verifaydaData, nationality }); + passengersData.push({ ...passenger, passengerName, dateOfBirth, category, verifaydaVerified, verifaydaData, nationality, identityRef: resolveIdentityRef(passenger) }); } + await assertIdentitiesNotAlreadyBooked(this.prisma, passengersData, [ + dto.scheduleId, + dto.returnScheduleId, + ]); + // Calculate fares for both legs — package bookings use the fixed tier price split across legs const returnSeatClassId = dto.returnSeatClassId || dto.seatClassId; const isPackageRoundTrip = !!dto.packageId && !!dto.priceTierId; @@ -935,6 +947,7 @@ export class GuestBookingService { dateOfBirth: p.dateOfBirth, passengerCategory: p.category, idDocumentType: p.idDocumentType, + idDocumentNumber: p.identityRef, passportNumber: p.passportNumber, passportCountry: p.passportCountry, verifaydaVerified: p.verifaydaVerified, @@ -950,6 +963,7 @@ export class GuestBookingService { dateOfBirth: p.dateOfBirth, passengerCategory: p.category, idDocumentType: p.idDocumentType, + idDocumentNumber: p.identityRef, passportNumber: p.passportNumber, passportCountry: p.passportCountry, verifaydaVerified: p.verifaydaVerified, @@ -1072,9 +1086,14 @@ export class GuestBookingService { } else { nationality = nationality || 'Other'; } - passengersData.push({ ...passenger, passengerName, dateOfBirth, category, verifaydaVerified, verifaydaData, nationality }); + passengersData.push({ ...passenger, passengerName, dateOfBirth, category, verifaydaVerified, verifaydaData, nationality, identityRef: resolveIdentityRef(passenger) }); } + await assertIdentitiesNotAlreadyBooked(this.prisma, passengersData, [ + dto.scheduleId, + dto.leg2ScheduleId, + ]); + const leg2SeatClassId = dto.leg2SeatClassId || dto.seatClassId; const primaryNationality = passengersData[0]?.nationality; const paidChildrenCount = Math.max(0, childCount - 1); @@ -1145,6 +1164,7 @@ export class GuestBookingService { dateOfBirth: p.dateOfBirth, passengerCategory: p.category, idDocumentType: p.idDocumentType, + idDocumentNumber: p.identityRef, passportNumber: p.passportNumber, passportCountry: p.passportCountry, verifaydaVerified: p.verifaydaVerified, @@ -1160,6 +1180,7 @@ export class GuestBookingService { dateOfBirth: p.dateOfBirth, passengerCategory: p.category, idDocumentType: p.idDocumentType, + idDocumentNumber: p.identityRef, passportNumber: p.passportNumber, passportCountry: p.passportCountry, verifaydaVerified: p.verifaydaVerified, @@ -1282,9 +1303,16 @@ export class GuestBookingService { } else { nationality = nationality || 'Other'; } - passengersData.push({ ...passenger, passengerName, dateOfBirth, category, verifaydaVerified, verifaydaData, nationality }); + passengersData.push({ ...passenger, passengerName, dateOfBirth, category, verifaydaVerified, verifaydaData, nationality, identityRef: resolveIdentityRef(passenger) }); } + await assertIdentitiesNotAlreadyBooked(this.prisma, passengersData, [ + dto.scheduleId, + dto.leg2ScheduleId, + dto.returnScheduleId, + dto.returnLeg2ScheduleId, + ]); + const nat = passengersData[0]?.nationality; const paidChildren = Math.max(0, childCount - 1); const obL2ClassId = dto.leg2SeatClassId ?? dto.seatClassId; @@ -1325,6 +1353,7 @@ export class GuestBookingService { dateOfBirth: p.dateOfBirth, passengerCategory: p.category, idDocumentType: p.idDocumentType, + idDocumentNumber: p.identityRef, passportNumber: p.passportNumber, passportCountry: p.passportCountry, verifaydaVerified: p.verifaydaVerified, diff --git a/apps/edr-passenger-web/portal/src/app/booking/review/page.tsx b/apps/edr-passenger-web/portal/src/app/booking/review/page.tsx index 4b9148001..4d4b954df 100644 --- a/apps/edr-passenger-web/portal/src/app/booking/review/page.tsx +++ b/apps/edr-passenger-web/portal/src/app/booking/review/page.tsx @@ -363,6 +363,9 @@ const adultPassengerCount = searchCriteria?.adultCount ?? passengers.filter(p => dateOfBirth: p.dateOfBirth, idDocumentType: isEthiopian ? 'NATIONAL_ID' : 'PASSPORT', idDocumentNumber: isEthiopian ? (p.nationalId || '') : '', + // Verified Fayda identity for this traveller. The backend stores it on the booking seat and + // refuses a second seat for the same identity on the same departure. + ...(p.faydaSub ? { faydaSub: p.faydaSub } : {}), passportNumber: !isEthiopian ? (p.passportNumber || '') : '', passportCountry: !isEthiopian ? (p.passportCountry || '') : '', nationality: p.nationality, @@ -417,6 +420,9 @@ const adultPassengerCount = searchCriteria?.adultCount ?? passengers.filter(p => dateOfBirth: p.dateOfBirth, idDocumentType: isEthiopian ? 'NATIONAL_ID' : 'PASSPORT', idDocumentNumber: isEthiopian ? (p.nationalId || '') : '', + // Verified Fayda identity for this traveller. The backend stores it on the booking seat and + // refuses a second seat for the same identity on the same departure. + ...(p.faydaSub ? { faydaSub: p.faydaSub } : {}), passportNumber: !isEthiopian ? (p.passportNumber || '') : '', passportCountry: !isEthiopian ? (p.passportCountry || '') : '', nationality: p.nationality,