This commit is contained in:
Roba Boru
2026-07-18 21:53:16 +03:00
38 changed files with 1952 additions and 102 deletions

View File

@@ -1,18 +1 @@
-- Remove duplicate JourneySegment rows, keeping the one with the lowest id
-- (earliest created) per (scheduleId, seatId, departureStationId) group.
-- This cleans up any existing double-bookings before the unique index is applied.
DELETE FROM passenger."JourneySegment"
WHERE id NOT IN (
SELECT MIN(id)
FROM passenger."JourneySegment"
WHERE "seatId" IS NOT NULL
GROUP BY "scheduleId", "seatId", "departureStationId"
)
AND "seatId" IS NOT NULL;
-- Prevents two confirmed bookings from occupying the same seat on the same
-- schedule hop — the hard DB backstop against application-level race conditions.
-- Partial index: seatId IS NOT NULL excludes free-child rows that have no seat.
CREATE UNIQUE INDEX "JourneySegment_scheduleId_seatId_departureStationId_key"
ON passenger."JourneySegment" ("scheduleId", "seatId", "departureStationId")
WHERE "seatId" IS NOT NULL;
-- Migration already applied directly to the database.

View File

@@ -1,12 +1 @@
-- Rename StopStatus enum values to reflect segment-level booking lifecycle.
-- UPCOMING → OPEN (segment is bookable)
-- APPROACHING → CHECKIN_CLOSED (within check-in cutoff, no new bookings)
-- CURRENT → BOARDED (train has departed this stop)
-- COMPLETED stays as-is
ALTER TYPE "passenger"."StopStatus" RENAME VALUE 'UPCOMING' TO 'OPEN';
ALTER TYPE "passenger"."StopStatus" RENAME VALUE 'APPROACHING' TO 'CHECKIN_CLOSED';
ALTER TYPE "passenger"."StopStatus" RENAME VALUE 'CURRENT' TO 'BOARDED';
-- Add per-route check-in window. Each route can define how many minutes before
-- a stop's planned departure check-in is closed. Defaults to 30 minutes.
ALTER TABLE "passenger"."Route" ADD COLUMN "checkinMinutesBefore" INTEGER NOT NULL DEFAULT 30;
-- Migration already applied directly to the database.

View File

@@ -1 +1 @@
ALTER TABLE "passenger"."RouteStop" ADD COLUMN "checkinMinutesBefore" INTEGER;
-- Migration already applied directly to the database.

View File

@@ -0,0 +1 @@
-- Migration already applied directly to the database.

View File

@@ -0,0 +1,20 @@
/*
Warnings:
- A unique constraint covering the columns `[scheduleId,seatId,departureStationId]` on the table `JourneySegment` will be added. If there are existing duplicate values, this will fail.
*/
-- Deduplicate before applying the unique index.
-- Keeps the row with the lowest id per (scheduleId, seatId, departureStationId) group.
DELETE FROM passenger."JourneySegment"
WHERE id NOT IN (
SELECT MIN(id)
FROM passenger."JourneySegment"
WHERE "seatId" IS NOT NULL
GROUP BY "scheduleId", "seatId", "departureStationId"
)
AND "seatId" IS NOT NULL;
-- CreateIndex
CREATE UNIQUE INDEX IF NOT EXISTS "JourneySegment_scheduleId_seatId_departureStationId_key"
ON "JourneySegment"("scheduleId", "seatId", "departureStationId");

View File

@@ -580,7 +580,7 @@ model BookingSeat {
bookingId String
seatId String
leg Int @default(1) // 1=outbound/leg-1, 2=return/leg-2
scheduleId String? // which schedule this seat belongs to
scheduleId String // which schedule this seat belongs to
passengerName String
dateOfBirth DateTime?
passengerCategory PassengerCategory @default(ADULT)
@@ -599,6 +599,7 @@ model BookingSeat {
displayFareMinor Int?
booking Booking @relation(fields: [bookingId], references: [id])
seat Seat @relation(fields: [seatId], references: [id])
@@unique([scheduleId, seatId])
@@schema("passenger")
}

View File

@@ -85,6 +85,7 @@ export class AgentsService {
seats: {
create: dto.passengers.map(p => ({
seat: { connect: { id: p.seatId } },
scheduleId: dto.scheduleId,
passengerName: p.fullName,
idDocumentType: p.idDocumentType as IdDocumentType | undefined,
idDocumentNumber: p.idDocumentNumber

View File

@@ -320,8 +320,8 @@ export class BookingsService {
id: b.id,
bookingRef: b.bookingRef,
status: b.status,
totalMinor: b.totalMinor,
currency: b.currency || null,
totalMinor: b.displayTotalMinor ?? b.totalMinor,
currency: b.displayCurrency ?? b.currency ?? null,
displayCurrency: b.displayCurrency ?? null,
displayTotalMinor: b.displayTotalMinor ?? null,
adultCount: b.adultCount,
@@ -578,7 +578,7 @@ export class BookingsService {
const mappedPkg = pkgItems.map((b: any) => ({
id: b.id, bookingRef: b.bookingRef, status: b.status,
totalMinor: b.totalMinor, currency: b.currency || b.displayCurrency,
totalMinor: b.displayTotalMinor ?? b.totalMinor, currency: b.displayCurrency || b.currency,
displayCurrency: b.displayCurrency, displayTotalMinor: b.displayTotalMinor,
contactEmail: b.contactEmail, contactPhone: b.contactPhone,
bookingType: 'PACKAGE', packageId: b.packageId, priceTierId: b.priceTierId,
@@ -732,8 +732,8 @@ export class BookingsService {
id: b.id,
bookingRef: b.bookingRef,
status: b.status,
totalMinor: b.totalMinor,
currency: b.currency || b.displayCurrency,
totalMinor: b.displayTotalMinor ?? b.totalMinor,
currency: b.displayCurrency || b.currency,
displayCurrency: b.displayCurrency,
displayTotalMinor: b.displayTotalMinor,
contactEmail: b.contactEmail,
@@ -866,6 +866,15 @@ export class BookingsService {
resolvedTotalMinor = displayCurrency !== Currency.ETB
? await this.currencyService.convertAmount(dto.reviewedTotalMinor, displayCurrency, Currency.ETB)
: dto.reviewedTotalMinor;
// For package bookings where per-seat fares weren't supplied, back-derive the
// per-seat fare from reviewedTotalMinor so BookingSeat.fareMinor reflects the
// actual berth price (Upper/Middle/Lower) rather than the tier's minimum price.
if (dto.packageId && seatedPassengers.length > 0) {
const perSeatFare = Math.round(dto.reviewedTotalMinor / seatedPassengers.length);
passengersWithFares.forEach(p => {
if (p.fareMinor > 0) p.fareMinor = p.seatFareMinor ?? perSeatFare;
});
}
} else if (allFaresProvided) {
// seatFareMinor is in display currency — sum is already the display total
displayTotalMinor = passengersWithFares.reduce((sum, p) => sum + p.fareMinor, 0);
@@ -901,6 +910,7 @@ export class BookingsService {
seats: {
create: passengersWithFares.map(p => ({
seat: { connect: { id: p.seatId } },
scheduleId: dto.scheduleId,
passengerName: p.passengerName,
dateOfBirth: p.dateOfBirth,
passengerCategory: p.category,
@@ -1050,6 +1060,19 @@ export class BookingsService {
totalMinor = displayCurrency !== Currency.ETB
? await this.currencyService.convertAmount(dto.reviewedTotalMinor, displayCurrency, Currency.ETB)
: dto.reviewedTotalMinor;
// For package bookings where per-seat fares weren't supplied, back-derive the
// per-leg per-seat fare from reviewedTotalMinor so BookingSeat.fareMinor reflects
// the actual berth price (Upper/Middle/Lower) rather than the tier's minimum price.
if (dto.packageId) {
const seatedCount = passengersData.filter(p => p.outboundSeatId).length;
if (seatedCount > 0) {
const perSeatPerLeg = Math.round(dto.reviewedTotalMinor / (seatedCount * 2));
passengersWithFares.forEach(p => {
if (p.outboundFareMinor > 0) p.outboundFareMinor = p.seatFareMinor ?? perSeatPerLeg;
if (p.returnFareMinor > 0) p.returnFareMinor = p.returnSeatFareMinor ?? perSeatPerLeg;
});
}
}
} else if (allRTFaresProvided && !dto.packageId) {
// seatFareMinor/returnSeatFareMinor are in display currency — sum is already the display total
displayTotalMinor = passengersWithFares.reduce((sum, p) => sum + p.outboundFareMinor + p.returnFareMinor, 0);
@@ -1822,8 +1845,8 @@ export class BookingsService {
id: pkgBooking.id,
bookingRef: pkgBooking.bookingRef,
status: pkgBooking.status,
totalMinor: pkgBooking.totalMinor,
currency: pkgBooking.currency || pkgBooking.displayCurrency,
totalMinor: pkgBooking.displayTotalMinor ?? pkgBooking.totalMinor,
currency: pkgBooking.displayCurrency || pkgBooking.currency,
adultCount: pkgBooking.passengerCount,
childCount: 0,
displayCurrency: pkgBooking.displayCurrency,
@@ -1852,7 +1875,7 @@ export class BookingsService {
fullName: p.passengerName,
category: 'ADULT',
leg: 1,
fareMinor: Math.round(pkgBooking.totalMinor / pkgBooking.passengerCount),
fareMinor: Math.round((pkgBooking.displayTotalMinor ?? pkgBooking.totalMinor) / pkgBooking.passengerCount),
verifaydaVerified: false,
seat: null,
})),

View File

@@ -231,6 +231,14 @@ export class GuestBookingService {
let resolvedTotalMinor: number;
if (dto.reviewedTotalMinor != null) {
displayTotalMinor = dto.reviewedTotalMinor;
// For package bookings, back-derive per-seat fareMinor from reviewedTotalMinor
// so BookingSeat records store the actual berth price, not the tier minimum.
if (isPackageOneway && seatedPassengers.length > 0) {
const perSeatFare = Math.round(dto.reviewedTotalMinor / seatedPassengers.length);
passengersWithFares.forEach(p => {
if (p.fareMinor > 0) p.fareMinor = p.seatFareMinor ?? perSeatFare;
});
}
} else if (allFaresProvided) {
displayTotalMinor = passengersWithFares.reduce((sum, p) => sum + p.fareMinor, 0);
} else {
@@ -291,6 +299,7 @@ export class GuestBookingService {
seats: {
create: passengersWithFares.map((p) => ({
seat: { connect: { id: p.seatId } },
scheduleId: dto.scheduleId,
passengerName: p.passengerName,
dateOfBirth: p.dateOfBirth,
passengerCategory: p.category,
@@ -515,6 +524,17 @@ export class GuestBookingService {
totalMinor = displayCurrency !== Currency.ETB
? await this.currencyService.convertAmount(displayTotalMinor, displayCurrency, Currency.ETB)
: displayTotalMinor;
// For package bookings, back-derive per-leg per-seat fareMinor from reviewedTotalMinor.
if (isPackageRoundTrip) {
const seatedCount = passengersData.filter(p => p.seatId).length;
if (seatedCount > 0) {
const perSeatPerLeg = Math.round(dto.reviewedTotalMinor / (seatedCount * 2));
passengersWithFares.forEach(p => {
if (p.outboundFareMinor > 0) p.outboundFareMinor = p.seatFareMinor ?? perSeatPerLeg;
if (p.returnFareMinor > 0) p.returnFareMinor = p.returnSeatFareMinor ?? perSeatPerLeg;
});
}
}
} else if (allRTFaresProvided && !isPackageRoundTrip) {
// seatFareMinor/returnSeatFareMinor are display-currency — sum is already display total
displayTotalMinor = passengersWithFares.reduce((sum, p) => sum + p.outboundFareMinor + p.returnFareMinor, 0);

View File

@@ -2,7 +2,8 @@ import { Controller, Get, Param, SetMetadata, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { DashboardService } from './dashboard.service';
import { JwtGuard } from '../../common/jwt.guard';
import { PassengerAdmin } from '../../common/passenger-guards';
import { PassengerAdmin, PassengerStaff } from '../../common/passenger-guards';
import { PASSENGER_PERMS } from '../../seed/passenger-permissions.registry';
@ApiTags('Dashboard')
@Controller('dashboard')
@@ -10,7 +11,7 @@ export class DashboardController {
constructor(private service: DashboardService) {}
@Get('backoffice-stats')
@PassengerAdmin()
@PassengerStaff([PASSENGER_PERMS.dashboard.view, PASSENGER_PERMS.admin])
@ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Backoffice summary: totals and revenue by currency' })
getBackofficeStats() { return this.service.getBackofficeStats(); }

View File

@@ -11,12 +11,13 @@ export class DashboardService {
) {}
async getBackofficeStats() {
const [totalBookings, totalPackageBookings, totalTickets, totalPassengers, revenueRows, packageRevenueRows] =
const [totalBookings, totalPackageBookings, totalTickets, totalPassengers, blockedSeatsCount, revenueRows, packageRevenueRows] =
await Promise.all([
this.prisma.booking.count(),
this.prisma.booking.count({ where: { packageId: { not: null } } }),
this.prisma.ticket.count(),
this.prisma.passenger.count(),
this.prisma.seat.count({ where: { status: 'BLOCKED' } }),
this.prisma.$queryRaw<{ currency: string; total: bigint }[]>`
SELECT
COALESCE("displayCurrency"::text, "currency"::text) AS currency,
@@ -56,6 +57,7 @@ export class DashboardService {
totalPackageTickets,
totalNormalTickets: totalTickets - totalPackageTickets,
totalPassengers,
blockedSeatsCount,
revenueByCurrency: toMap(revenueRows),
packageRevenueByCurrency: toMap(packageRevenueRows),
};

View File

@@ -444,8 +444,8 @@ export class PackagesService {
passengerCount,
adultCount,
childCount,
totalMinor,
currency: 'ETB',
totalMinor: displayTotalMinor,
currency: displayCurrency,
displayCurrency,
displayTotalMinor,
status: 'PENDING_PAYMENT',

View File

@@ -12,8 +12,15 @@ import {
PaymentIntentSnapshot,
PaymentReferenceType,
PaymentService,
ProviderStatus,
} from "@edr/types";
/** Side-by-side DB row + live provider status from the payment service diagnostic endpoints. */
export interface PaymentDiagnostic {
db: Record<string, unknown> | null;
provider: ProviderStatus | null;
}
/**
* Thin HTTP client for the payment microservice (apps/edr-payment-api) — the passenger app's
* side of the Phase 6 cutover (docs/payment-service §10). Domain validation stays here;
@@ -55,6 +62,28 @@ export class PaymentClientService {
}
}
/**
* GET /payments/diagnostic?… — DB intent row + live provider status for a domain reference,
* side by side. Returns { db: null, provider: null } when the payment service has no intent.
*/
async getDiagnosticByReference(
referenceType: PaymentReferenceType,
referenceId: string,
): Promise<PaymentDiagnostic> {
const query = new URLSearchParams({
service: PaymentService.PASSENGER,
referenceType,
referenceId,
});
try {
return await this.call("GET", `/payments/diagnostic?${query.toString()}`);
} catch (err) {
if (err instanceof AxiosError && err.response?.status === 404)
return { db: null, provider: null };
throw err;
}
}
/**
* POST /payments/intents/:id/confirm — submit an OTP for a COLLECT_OTP provider (CAC Bank).
* A wrong/expired OTP comes back as 400 from the payment service; surface that as a

View File

@@ -133,6 +133,33 @@ export class PaymentsController {
return this.service.getIntentByBookingId(bookingId);
}
@Get("status/:bookingRefOrId")
@SetMetadata("isPublic", true)
@ApiOperation({
summary: "Get payment status by booking id or booking reference (PNR)",
description:
"Accepts either a booking UUID or a booking reference / PNR (e.g. EDR-20240001), " +
"resolves it to the booking, and returns the authoritative payment status pulled from " +
"the payment microservice.",
})
getStatusByBookingRefOrId(@Param("bookingRefOrId") bookingRefOrId: string) {
return this.service.getIntentByBookingRefOrId(bookingRefOrId);
}
@Get("diagnostic/:bookingRefOrId")
@SetMetadata("isPublic", true)
@ApiOperation({
summary:
"Get { db, provider } by booking id or booking reference (PNR) — diagnostic",
description:
"Accepts a booking UUID or a booking reference / PNR (e.g. EDR-20240001), resolves it to " +
"the booking, and returns { db, provider }: the payment service's stored intent row and a " +
"live provider status query, side by side. Pure read — does not reconcile the booking.",
})
getPaymentDiagnostic(@Param("bookingRefOrId") bookingRefOrId: string) {
return this.service.getPaymentDiagnosticByBookingRefOrId(bookingRefOrId);
}
@Post(":bookingId/confirm")
@SetMetadata("isPublic", true)
@ApiOperation({

View File

@@ -118,6 +118,7 @@ describe("Payments E2E", () => {
data: {
bookingId: booking.id,
seatId: seat.id,
scheduleId: schedule.id,
passengerName: "Test Passenger",
},
});

View File

@@ -24,7 +24,10 @@ import {
ForceConfirmDto,
} from "./payments.dto";
import { PaymentEventDto, MarkPaidResponseDto } from "./internal-payments.dto";
import { PaymentClientService } from "./payment-client.service";
import {
PaymentClientService,
PaymentDiagnostic,
} from "./payment-client.service";
import { CurrencyService } from "../currency/currency.service";
import { AuditService } from "../../common/audit.service";
import { rebaseUrlOrigin } from "../../common/utils/redirect-origin.util";
@@ -534,6 +537,51 @@ export class PaymentsService {
};
}
/**
* Payment status by booking id (UUID) OR booking reference / PNR (e.g. EDR-20240001).
* Resolves the PNR to its booking id, then pulls the authoritative status from the payment
* microservice (via {@link getIntentByBookingId}).
*/
async getIntentByBookingRefOrId(
bookingRefOrId: string,
): Promise<IntentStatusDto> {
const bookingId = await this.resolveBookingId(bookingRefOrId);
return this.getIntentByBookingId(bookingId);
}
/**
* Diagnostic view by booking id (UUID) OR booking reference / PNR: the payment service's
* stored intent row and a live provider status query, side by side ({ db, provider }).
* Pure read — does not reconcile or confirm the booking.
*/
async getPaymentDiagnosticByBookingRefOrId(
bookingRefOrId: string,
): Promise<PaymentDiagnostic> {
const bookingId = await this.resolveBookingId(bookingRefOrId);
return this.paymentClient.getDiagnosticByReference(
PaymentReferenceType.BOOKING,
bookingId,
);
}
/** Accept a booking UUID as-is; otherwise look the id up from its bookingRef/PNR. */
private async resolveBookingId(bookingRefOrId: string): Promise<string> {
const isUuid =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
bookingRefOrId,
);
if (isUuid) return bookingRefOrId;
const booking = await this.prisma.booking.findUnique({
where: { bookingRef: bookingRefOrId },
select: { id: true },
});
if (!booking) {
throw new NotFoundException(`Booking not found: ${bookingRefOrId}`);
}
return booking.id;
}
async getIntentByBookingId(bookingId: string): Promise<IntentStatusDto> {
const local = await this.prisma.paymentIntent.findUnique({
where: { bookingId },

View File

@@ -18,6 +18,12 @@ export class ReportsController {
return this.service.generateReport(dto);
}
@Get('passengers')
@ApiOperation({ summary: 'Passengers report for a specific schedule' })
getOccupancyReport(@Query('scheduleId') scheduleId: string) {
return this.service.getOccupancyBySchedule(scheduleId);
}
@Get(':reportId')
@ApiOperation({ summary: 'Get report by ID' })
getReport(@Param('reportId') reportId: string) {

View File

@@ -191,6 +191,122 @@ export class ReportsService {
};
}
async getOccupancyBySchedule(scheduleId: string) {
const schedule = await this.prisma.trainSchedule.findUnique({
where: { id: scheduleId },
include: {
originStation: true,
destinationStation: true,
train: true,
coachAssignments: {
include: {
coach: {
include: {
coachType: true,
seats: { select: { id: true } },
},
},
},
},
bookings: {
where: { status: { in: ['CONFIRMED', 'BOARDED'] } },
include: {
seats: {
include: {
seat: { include: { coach: { include: { coachType: true } } } },
},
},
},
},
stopTimes: { include: { station: true }, orderBy: { sequence: 'asc' } },
},
});
if (!schedule) return null;
const totalSeats = (schedule as any).coachAssignments.reduce((s: number, a: any) => s + a.coach.seats.length, 0);
const allBookingSeats = (schedule as any).bookings.flatMap((b: any) => b.seats);
const totalPassengers = allBookingSeats.length;
const occupancyRate = totalSeats > 0 ? +((totalPassengers / totalSeats) * 100).toFixed(1) : 0;
// Per-coach breakdown
const coachMap = new Map<string, { coachNumber: string; coachType: string; totalSeats: number; booked: number }>();
for (const assignment of (schedule as any).coachAssignments) {
const c = assignment.coach;
coachMap.set(c.id, {
coachNumber: c.number,
coachType: (c as any).coachType?.name ?? 'Unknown',
totalSeats: c.seats.length,
booked: 0,
});
}
for (const bs of allBookingSeats) {
const coachId = bs.seat?.coachId;
if (coachId && coachMap.has(coachId)) coachMap.get(coachId)!.booked++;
}
const byCoach = [...coachMap.values()].map(c => ({
...c,
occupancyRate: c.totalSeats > 0 ? +((c.booked / c.totalSeats) * 100).toFixed(1) : 0,
}));
// Per-origin station breakdown (using booking's originStationId)
const originMap = new Map<string, { stationName: string; passengers: number }>();
for (const booking of (schedule as any).bookings) {
const stationId = booking.originStationId ?? schedule.originStationId;
const stationName = (schedule as any).stopTimes.find((st: any) => st.stationId === stationId)?.station?.name
?? (schedule as any).originStation?.name
?? stationId;
if (!originMap.has(stationId)) originMap.set(stationId, { stationName, passengers: 0 });
originMap.get(stationId)!.passengers += booking.seats.length;
}
const byOrigin = [...originMap.values()].sort((a, b) => b.passengers - a.passengers);
// Per-destination station breakdown
const destMap = new Map<string, { stationName: string; passengers: number }>();
for (const booking of (schedule as any).bookings) {
const stationId = booking.destinationStationId ?? schedule.destinationStationId;
const stationName = (schedule as any).stopTimes.find((st: any) => st.stationId === stationId)?.station?.name
?? (schedule as any).destinationStation?.name
?? stationId;
if (!destMap.has(stationId)) destMap.set(stationId, { stationName, passengers: 0 });
destMap.get(stationId)!.passengers += booking.seats.length;
}
const byDestination = [...destMap.values()].sort((a, b) => b.passengers - a.passengers);
// Per-class breakdown
const classMap = new Map<string, { className: string; totalSeats: number; booked: number }>();
for (const assignment of (schedule as any).coachAssignments) {
const typeName = (assignment.coach as any).coachType?.name ?? 'Unknown';
if (!classMap.has(typeName)) classMap.set(typeName, { className: typeName, totalSeats: 0, booked: 0 });
classMap.get(typeName)!.totalSeats += assignment.coach.seats.length;
}
for (const bs of allBookingSeats) {
const typeName = bs.seat?.coach?.coachType?.name ?? 'Unknown';
if (!classMap.has(typeName)) classMap.set(typeName, { className: typeName, totalSeats: 0, booked: 0 });
classMap.get(typeName)!.booked++;
}
const byClass = [...classMap.values()].map(c => ({
...c,
occupancyRate: c.totalSeats > 0 ? +((c.booked / c.totalSeats) * 100).toFixed(1) : 0,
}));
return {
schedule: {
id: schedule.id,
trainName: (schedule as any).train?.name ?? (schedule as any).train?.number,
origin: (schedule as any).originStation?.name,
destination: (schedule as any).destinationStation?.name,
departureAt: schedule.departureAt,
arrivalAt: schedule.arrivalAt,
},
summary: { totalSeats, totalPassengers, occupancyRate },
byCoach,
byClass,
byOrigin,
byDestination,
};
}
async getReport(reportId: string) {
return this.prisma.operationalReport.findUnique({ where: { id: reportId } });
}

View File

@@ -54,11 +54,16 @@ export class CreateScheduleDto {
plannedTimes?: PlannedStopTimeDto[];
}
export class CoachAssignmentDto {
@ApiProperty({ example: 'coach-uuid' }) @IsString() coachId: string;
@ApiProperty({ example: 1 }) @IsInt() @Min(1) positionNumber: number;
}
export class UpdateScheduleDto {
@ApiPropertyOptional({ example: '2026-06-15T08:00:00Z', description: 'Scheduled departure from the first stop (origin)' }) @IsOptional() @IsDateString() departureAt?: string;
@ApiPropertyOptional({ example: '2026-06-15T20:00:00Z', description: 'Scheduled arrival at the last stop (destination)' }) @IsOptional() @IsDateString() arrivalAt?: string;
@ApiPropertyOptional({ enum: TripStatus, example: TripStatus.SCHEDULED }) @IsOptional() @IsEnum(TripStatus) status?: TripStatus;
@ApiPropertyOptional({ type: Array, description: 'List of coaches to assign' }) @IsOptional() @IsArray() coaches?: Array<{ coachId: string; positionNumber: number }>;
@ApiPropertyOptional({ type: [CoachAssignmentDto], description: 'List of coaches to assign' }) @IsOptional() @IsArray() @ValidateNested({ each: true }) @Type(() => CoachAssignmentDto) coaches?: CoachAssignmentDto[];
@ApiPropertyOptional({ example: false, description: 'Exclude from public search (reserved for packages)' }) @IsOptional() isPackageOnly?: boolean;
@ApiPropertyOptional({ type: [PlannedStopTimeDto], description: 'Planned times per stop — when provided, replaces all existing stop times for the schedule' })
@IsOptional() @IsArray() @ValidateNested({ each: true }) @Type(() => PlannedStopTimeDto)

View File

@@ -535,8 +535,8 @@ export class SearchService {
discountMinor: fare.discountMinor,
taxesFeesMinor: 0,
loyaltyRedemptionMinor: loyaltyMinor,
totalMinor,
currency: 'ETB',
totalMinor: displayTotalMinor,
currency: displayCurrency,
displayCurrency,
displayTotalMinor,
};
@@ -653,8 +653,8 @@ export class SearchService {
passengers: passengerLines,
subtotalMinor,
discountMinor,
totalMinor,
currency: 'ETB',
totalMinor: displayTotalMinor,
currency: displayCurrency,
displayCurrency,
displayTotalMinor,
};

View File

@@ -1020,7 +1020,7 @@ export class SeatsService {
where: {
OR: [
{ scheduleId: schedule.id },
{ scheduleId: null, booking: { scheduleId: schedule.id } },
{ booking: { scheduleId: schedule.id } },
],
booking: { status: { in: ['CONFIRMED', 'BOARDED'] } },
},

View File

@@ -53,6 +53,7 @@ export class TicketsController {
@ApiQuery({ name: 'originStationId', required: false })
@ApiQuery({ name: 'destinationStationId', required: false })
@ApiQuery({ name: 'arrivalDate', required: false })
@ApiQuery({ name: 'departureDate', required: false })
@ApiQuery({ name: 'dateFrom', required: false })
@ApiQuery({ name: 'dateTo', required: false })
@ApiQuery({ name: 'coachId', required: false })
@@ -64,6 +65,7 @@ export class TicketsController {
@Query('originStationId') originStationId?: string,
@Query('destinationStationId') destinationStationId?: string,
@Query('arrivalDate') arrivalDate?: string,
@Query('departureDate') departureDate?: string,
@Query('dateFrom') dateFrom?: string,
@Query('dateTo') dateTo?: string,
@Query('coachId') coachId?: string,
@@ -76,6 +78,7 @@ export class TicketsController {
originStationId,
destinationStationId,
arrivalDate,
departureDate,
dateFrom,
dateTo,
coachId,

View File

@@ -27,7 +27,7 @@ export class TicketsService {
@InjectDataSource() private readonly dataSource: DataSource,
) {}
async listTickets(filters: { search?: string; status?: string; originStationId?: string; destinationStationId?: string; arrivalDate?: string; dateFrom?: string; dateTo?: string; coachId?: string; skip: number; take: number }) {
async listTickets(filters: { search?: string; status?: string; originStationId?: string; destinationStationId?: string; departureDate?: string; arrivalDate?: string; dateFrom?: string; dateTo?: string; coachId?: string; skip: number; take: number }) {
const where: any = {};
if (filters.search) {
where.OR = [
@@ -41,10 +41,16 @@ export class TicketsService {
where.status = filters.status;
}
if (filters.originStationId) {
where.booking = { ...where.booking, schedule: { ...where.booking?.schedule, originStationId: filters.originStationId } };
where.booking = { ...where.booking, originStationId: filters.originStationId };
}
if (filters.destinationStationId) {
where.booking = { ...where.booking, schedule: { ...where.booking?.schedule, destinationStationId: filters.destinationStationId } };
where.booking = { ...where.booking, destinationStationId: filters.destinationStationId };
}
if (filters.departureDate) {
const start = new Date(filters.departureDate);
const end = new Date(filters.departureDate);
end.setDate(end.getDate() + 1);
where.booking = { ...where.booking, schedule: { ...where.booking?.schedule, departureAt: { gte: start, lt: end } } };
}
if (filters.arrivalDate) {
const start = new Date(filters.arrivalDate);
@@ -70,7 +76,7 @@ export class TicketsService {
include: {
booking: {
include: {
schedule: { include: { originStation: true, destinationStation: true, train: true } },
schedule: { include: { originStation: true, destinationStation: true, train: true, stopTimes: { include: { station: true } } } },
returnSchedule: { include: { originStation: true, destinationStation: true } },
passenger: { include: { travelerProfiles: true } },
seats: { include: { seat: { include: { coach: true } } } },
@@ -146,6 +152,18 @@ export class TicketsService {
contactPhone: t.booking?.contactPhone,
returnSchedule: t.booking?.returnSchedule ?? null,
seats: t.booking?.seats ?? [],
originStation: (() => {
const id = t.booking?.originStationId;
if (!id) return t.booking?.schedule?.originStation ?? null;
const stop = t.booking?.schedule?.stopTimes?.find((st: any) => st.stationId === id);
return stop?.station ?? t.booking?.schedule?.originStation ?? null;
})(),
destinationStation: (() => {
const id = t.booking?.destinationStationId;
if (!id) return t.booking?.schedule?.destinationStation ?? null;
const stop = t.booking?.schedule?.stopTimes?.find((st: any) => st.stationId === id);
return stop?.station ?? t.booking?.schedule?.destinationStation ?? null;
})(),
},
schedule: t.booking?.schedule,
seat: t.seat ? {

View File

@@ -3,7 +3,7 @@
import { useQuery } from '@tanstack/react-query';
import { PermissionGuard } from '@/components/layout/PermissionGuard';
import { PERMS } from '@/lib/permissions';
import { Ticket, AlertCircle, BookOpen, Banknote, ArrowRight } from 'lucide-react';
import { Ticket, AlertCircle, BookOpen, Banknote, ArrowRight, ScanLine } from 'lucide-react';
import { dashboardApi } from '@/lib/api/dashboard';
import { apiClient } from '@/lib/api-client';
import { formatCurrency } from '@/lib/utils';
@@ -99,7 +99,8 @@ function DashboardPageContent() {
queryKey: ['backoffice-stats'],
queryFn: dashboardApi.getBackofficeStats,
retry: 1,
staleTime: 60000,
staleTime: 30000,
refetchInterval: 60000,
});
const { data: paymentMethods } = useQuery({
@@ -143,9 +144,19 @@ function DashboardPageContent() {
return (
<div className="space-y-6 p-6">
<div>
<h1 className="text-3xl font-bold text-foreground">Dashboard</h1>
<p className="text-muted-foreground mt-1">Welcome back! Here&apos;s your operational summary.</p>
<div className="flex items-start justify-between">
<div>
<h1 className="text-3xl font-bold text-foreground">Dashboard</h1>
<p className="text-muted-foreground mt-1">Welcome back! Here&apos;s your operational summary.</p>
</div>
<Link
href="/boarding"
className="flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-sm font-medium text-foreground hover:bg-muted transition-colors"
title="Boarding / Gate Scan"
>
<ScanLine className="h-4 w-4 text-[rgb(20,113,76)]" />
<span className="hidden sm:inline">Boarding</span>
</Link>
</div>
{statsError && (

View File

@@ -0,0 +1,5 @@
import DashboardLayout from '../../dashboard/layout';
export default function PassengersLayout({ children }: { children: React.ReactNode }) {
return <>{children}</>;
}

View File

@@ -0,0 +1,315 @@
'use client';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Users, Armchair, TrendingUp, Train, Download } from 'lucide-react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell } from 'recharts';
import { apiClient } from '@/lib/api-client';
import { formatDateTime } from '@/lib/utils';
import ActionButton from '@/components/ui/ActionButton';
const COLORS = ['#10b981', '#3b82f6', '#f59e0b', '#8b5cf6', '#ef4444', '#06b6d4'];
function StatCard({ label, value, sub, icon: Icon, color }: { label: string; value: string | number; sub?: string; icon: any; color: string }) {
return (
<div className="card flex flex-col gap-1">
<div className="flex items-center justify-between">
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{label}</p>
<div className={`rounded-lg p-1.5 ${color}`}><Icon className="h-4 w-4" /></div>
</div>
<p className="text-2xl font-bold tabular-nums mt-1">{value}</p>
{sub && <p className="text-xs text-muted-foreground">{sub}</p>}
</div>
);
}
export default function PassengersReportPage() {
const [scheduleId, setScheduleId] = useState('');
const { data: schedules = [] } = useQuery<any[]>({
queryKey: ['schedules-list'],
queryFn: () => apiClient.get('/schedules'),
select: (d: any) => d?.items ?? (Array.isArray(d) ? d : []),
});
const { data, isFetching } = useQuery({
queryKey: ['occupancy-report', scheduleId],
queryFn: () => apiClient.get(`/reports/passengers?scheduleId=${scheduleId}`),
enabled: !!scheduleId,
});
const report = data as any;
const doExport = () => {
if (!report) return;
const rows = [
['Coach', 'Type', 'Total Seats', 'Booked', 'Occupancy %'],
...report.byCoach.map((c: any) => [c.coachNumber, c.coachType, c.totalSeats, c.booked, c.occupancyRate]),
];
const csv = rows.map(r => r.map((v: any) => `"${v}"`).join(',')).join('\n');
const blob = new Blob([csv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `occupancy-${scheduleId}-${new Date().toISOString().split('T')[0]}.csv`;
a.click();
URL.revokeObjectURL(url);
};
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold text-foreground">Passengers Report</h1>
<p className="text-muted-foreground mt-1">Select a schedule to view passenger occupancy breakdown</p>
</div>
{/* Schedule Selector */}
<div className="card">
<div className="flex flex-wrap items-end gap-4">
<div className="flex-1 min-w-64">
<label className="label">Schedule</label>
<select
className="input"
value={scheduleId}
onChange={(e) => setScheduleId(e.target.value)}
>
<option value=""> Select a schedule </option>
{schedules.map((s: any) => (
<option key={s.id} value={s.id}>
{s.train?.name ?? s.train?.number ?? 'Train'} · {s.originStation?.name} {s.destinationStation?.name} · {s.departureAt ? new Date(s.departureAt).toLocaleString() : ''}
</option>
))}
</select>
</div>
{isFetching && <p className="text-sm text-muted-foreground self-center">Loading</p>}
{report && (
<ActionButton icon={Download} variant="secondary" onClick={doExport}>
Export CSV
</ActionButton>
)}
</div>
</div>
{isFetching && (
<div className="card py-12 text-center text-muted-foreground">Loading passengers data</div>
)}
{report && (
<>
{/* Schedule Info */}
<div className="card flex items-center gap-4">
<div className="rounded-lg bg-emerald-100 dark:bg-emerald-900/30 p-2.5">
<Train className="h-5 w-5 text-emerald-600 dark:text-emerald-400" />
</div>
<div>
<p className="font-semibold">{report.schedule.trainName}</p>
<p className="text-sm text-muted-foreground">
{report.schedule.origin} {report.schedule.destination} · Departure: {formatDateTime(report.schedule.departureAt)}
</p>
</div>
</div>
{/* Summary Cards */}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<StatCard
label="Total Seats"
value={report.summary.totalSeats}
icon={Armchair}
color="bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400"
/>
<StatCard
label="Total Passengers"
value={report.summary.totalPassengers}
icon={Users}
color="bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400"
/>
<StatCard
label="Occupancy Rate"
value={`${report.summary.occupancyRate}%`}
sub={`${report.summary.totalSeats - report.summary.totalPassengers} seats available`}
icon={TrendingUp}
color="bg-amber-100 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400"
/>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* By Coach */}
<div className="card">
<h3 className="text-base font-semibold mb-4">Occupancy by Coach</h3>
{report.byCoach.length > 0 ? (
<>
<ResponsiveContainer width="100%" height={220}>
<BarChart data={report.byCoach} layout="vertical" margin={{ left: 8 }}>
<CartesianGrid strokeDasharray="3 3" horizontal={false} />
<XAxis type="number" domain={[0, 100]} tickFormatter={(v) => `${v}%`} tick={{ fontSize: 11 }} />
<YAxis type="category" dataKey="coachNumber" tick={{ fontSize: 11 }} width={56} tickFormatter={(v) => `Coach ${v}`} />
<Tooltip formatter={(v: number) => [`${v}%`, 'Occupancy']} />
<Bar dataKey="occupancyRate" radius={[0, 3, 3, 0]}>
{report.byCoach.map((_: any, i: number) => (
<Cell key={i} fill={COLORS[i % COLORS.length]} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
<table className="w-full mt-3 text-sm">
<thead>
<tr className="text-xs text-muted-foreground border-b border-border">
<th className="text-left py-1.5 font-medium">Coach</th>
<th className="text-left py-1.5 font-medium">Type</th>
<th className="text-right py-1.5 font-medium">Booked</th>
<th className="text-right py-1.5 font-medium">Total</th>
<th className="text-right py-1.5 font-medium">Rate</th>
</tr>
</thead>
<tbody>
{report.byCoach.map((c: any, i: number) => (
<tr key={i} className="border-b border-border/50 last:border-0">
<td className="py-1.5 font-mono font-semibold">Coach {c.coachNumber}</td>
<td className="py-1.5 text-muted-foreground">{c.coachType}</td>
<td className="py-1.5 text-right tabular-nums">{c.booked}</td>
<td className="py-1.5 text-right tabular-nums text-muted-foreground">{c.totalSeats}</td>
<td className="py-1.5 text-right tabular-nums font-semibold">{c.occupancyRate}%</td>
</tr>
))}
</tbody>
</table>
</>
) : (
<p className="text-sm text-muted-foreground">No coach data</p>
)}
</div>
{/* By Class */}
<div className="card">
<h3 className="text-base font-semibold mb-4">Occupancy by Class</h3>
{report.byClass.length > 0 ? (
<>
<ResponsiveContainer width="100%" height={220}>
<BarChart data={report.byClass}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="className" tick={{ fontSize: 11 }} />
<YAxis domain={[0, 100]} tickFormatter={(v) => `${v}%`} tick={{ fontSize: 11 }} />
<Tooltip formatter={(v: number) => [`${v}%`, 'Occupancy']} />
<Bar dataKey="occupancyRate" radius={[3, 3, 0, 0]}>
{report.byClass.map((_: any, i: number) => (
<Cell key={i} fill={COLORS[i % COLORS.length]} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
<table className="w-full mt-3 text-sm">
<thead>
<tr className="text-xs text-muted-foreground border-b border-border">
<th className="text-left py-1.5 font-medium">Class</th>
<th className="text-right py-1.5 font-medium">Booked</th>
<th className="text-right py-1.5 font-medium">Total</th>
<th className="text-right py-1.5 font-medium">Rate</th>
</tr>
</thead>
<tbody>
{report.byClass.map((c: any, i: number) => (
<tr key={i} className="border-b border-border/50 last:border-0">
<td className="py-1.5 font-medium">{c.className}</td>
<td className="py-1.5 text-right tabular-nums">{c.booked}</td>
<td className="py-1.5 text-right tabular-nums text-muted-foreground">{c.totalSeats}</td>
<td className="py-1.5 text-right tabular-nums font-semibold">{c.occupancyRate}%</td>
</tr>
))}
</tbody>
</table>
</>
) : (
<p className="text-sm text-muted-foreground">No class data</p>
)}
</div>
{/* By Origin */}
<div className="card">
<h3 className="text-base font-semibold mb-4">Passengers by Boarding Station</h3>
{report.byOrigin.length > 0 ? (
<table className="w-full text-sm">
<thead>
<tr className="text-xs text-muted-foreground border-b border-border">
<th className="text-left py-1.5 font-medium">Station</th>
<th className="text-right py-1.5 font-medium">Passengers</th>
<th className="text-right py-1.5 font-medium">Share</th>
</tr>
</thead>
<tbody>
{report.byOrigin.map((o: any, i: number) => {
const pct = report.summary.totalPassengers > 0
? ((o.passengers / report.summary.totalPassengers) * 100).toFixed(1)
: '0';
return (
<tr key={i} className="border-b border-border/50 last:border-0">
<td className="py-2">
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full flex-shrink-0" style={{ background: COLORS[i % COLORS.length] }} />
{o.stationName}
</div>
</td>
<td className="py-2 text-right tabular-nums font-semibold">{o.passengers}</td>
<td className="py-2 text-right tabular-nums text-muted-foreground">{pct}%</td>
</tr>
);
})}
</tbody>
</table>
) : (
<p className="text-sm text-muted-foreground">No boarding station data</p>
)}
</div>
{/* By Destination */}
<div className="card">
<h3 className="text-base font-semibold mb-4">Passengers by Alighting Station</h3>
{report.byDestination.length > 0 ? (
<table className="w-full text-sm">
<thead>
<tr className="text-xs text-muted-foreground border-b border-border">
<th className="text-left py-1.5 font-medium">Station</th>
<th className="text-right py-1.5 font-medium">Passengers</th>
<th className="text-right py-1.5 font-medium">Share</th>
</tr>
</thead>
<tbody>
{report.byDestination.map((d: any, i: number) => {
const pct = report.summary.totalPassengers > 0
? ((d.passengers / report.summary.totalPassengers) * 100).toFixed(1)
: '0';
return (
<tr key={i} className="border-b border-border/50 last:border-0">
<td className="py-2">
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full flex-shrink-0" style={{ background: COLORS[i % COLORS.length] }} />
{d.stationName}
</div>
</td>
<td className="py-2 text-right tabular-nums font-semibold">{d.passengers}</td>
<td className="py-2 text-right tabular-nums text-muted-foreground">{pct}%</td>
</tr>
);
})}
</tbody>
</table>
) : (
<p className="text-sm text-muted-foreground">No alighting station data</p>
)}
</div>
</div>
</>
)}
{!report && !isFetching && scheduleId && (
<div className="card py-12 text-center text-muted-foreground">No data found for this schedule.</div>
)}
{!scheduleId && (
<div className="card py-16 text-center text-muted-foreground">
<Armchair className="h-10 w-10 mx-auto mb-3 opacity-30" />
<p>Select a schedule above to load the occupancy report</p>
</div>
)}
</div>
);
}

View File

@@ -2,8 +2,9 @@
import { useState, useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Download, Armchair, CheckCircle, Clock, AlertCircle } from 'lucide-react';
import { Download, Armchair, CheckCircle, Clock, AlertCircle, Ban } from 'lucide-react';
import { bookingsApi } from '@/lib/api';
import { dashboardApi } from '@/lib/api/dashboard';
import Badge from '@/components/ui/Badge';
import ActionButton from '@/components/ui/ActionButton';
import { formatDateTime, formatCurrency } from '@/lib/utils';
@@ -46,6 +47,12 @@ export default function SeatStatusReportPage() {
const [statusFilter, setStatusFilter] = useState<'ALL' | 'PAID' | 'UNPAID'>('ALL');
const [search, setSearch] = useState('');
const { data: stats } = useQuery({
queryKey: ['backoffice-stats'],
queryFn: dashboardApi.getBackofficeStats,
staleTime: 30000,
});
const { data: bookingsData, isLoading } = useQuery({
queryKey: ['seat-report-bookings'],
queryFn: () => bookingsApi.getAll({ pageSize: 1000 }),
@@ -150,7 +157,7 @@ export default function SeatStatusReportPage() {
</div>
{/* Summary Cards */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<div className="card">
<div className="flex items-start justify-between">
<div>
@@ -189,6 +196,19 @@ export default function SeatStatusReportPage() {
<AlertCircle className="h-8 w-8 text-red-500 opacity-30" />
</div>
</div>
<div className="card">
<div className="flex items-start justify-between">
<div>
<p className="text-muted-foreground text-sm font-medium">Blocked Seats</p>
<p className="text-2xl font-bold mt-2 text-slate-600 dark:text-slate-400">
{stats?.blockedSeatsCount ?? '—'}
</p>
<p className="text-xs text-muted-foreground mt-1">Globally blocked</p>
</div>
<Ban className="h-8 w-8 text-slate-500 opacity-30" />
</div>
</div>
</div>
{/* Filters */}

View File

@@ -15,7 +15,7 @@ import { formatDateTime, formatCurrency, formatDateTimeShort } from '@/lib/utils
import { useAuthStore } from '@/lib/auth-store';
export default function TicketsPage() {
const [filters, setFilters] = useState({ search: '', status: '', originStationId: '', destinationStationId: '', arrivalDate: '', dateFrom: '', dateTo: '', coachId: '' });
const [filters, setFilters] = useState({ search: '', status: '', originStationId: '', destinationStationId: '', departureDate: '', arrivalDate: '', dateFrom: '', dateTo: '', coachId: '' });
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
const [ticketToDelete, setTicketToDelete] = useState<any>(null);
const [deleteError, setDeleteError] = useState<string | null>(null);
@@ -71,6 +71,7 @@ export default function TicketsPage() {
status: filters.status || undefined,
originStationId: filters.originStationId || undefined,
destinationStationId: filters.destinationStationId || undefined,
departureDate: filters.departureDate || undefined,
arrivalDate: filters.arrivalDate || undefined,
dateFrom: filters.dateFrom || undefined,
dateTo: filters.dateTo || undefined,
@@ -358,11 +359,13 @@ export default function TicketsPage() {
render: (ticket: any) => {
const isRoundTrip = ticket.booking?.bookingType === 'ROUND_TRIP' || ticket.booking?.bookingType === 'ROUND_TRIP_TRANSIT';
const returnDeparture = ticket.booking?.returnSchedule?.departureAt;
const origin = ticket.booking?.originStation?.name || ticket.schedule?.originStation?.name || 'N/A';
const destination = ticket.booking?.destinationStation?.name || ticket.schedule?.destinationStation?.name || 'N/A';
return (
<div>
<div className="font-medium">
{ticket.schedule?.originStation?.name || 'N/A'} {ticket.schedule?.destinationStation?.name || 'N/A'}
{origin} {destination}
</div>
<div className="text-xs text-muted-foreground">
{!isRoundTrip ? (
@@ -551,7 +554,7 @@ export default function TicketsPage() {
Error loading tickets: {error instanceof Error ? error.message : 'Unknown error'}
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-4">
<div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-4">
<div>
<label className="label">Search</label>
<input
@@ -589,14 +592,27 @@ export default function TicketsPage() {
</select>
</div>
<div>
<label className="label">Arrival Date</label>
<label className="label">Departure Date</label>
<input
type="date"
className="input"
value={filters.arrivalDate}
onChange={(e) => setFilters({ ...filters, arrivalDate: e.target.value })}
value={filters.departureDate}
onChange={(e) => setFilters({ ...filters, departureDate: e.target.value })}
/>
</div>
<div>
<label className="label">Coach</label>
<select
className="input"
value={filters.coachId}
onChange={(e) => setFilters({ ...filters, coachId: e.target.value })}
>
<option value="">All Coaches</option>
{(Array.isArray(coachesData) ? coachesData : (coachesData as any)?.data || []).map((coach: any) => (
<option key={coach.id} value={coach.id}>{coach.number}</option>
))}
</select>
</div>
<div className="flex items-end">
<button type="button" className="input w-full px-4 text-sm font-medium text-primary border-primary/40"
onClick={() => setShowExtraFilters(v => !v)}>
@@ -605,7 +621,7 @@ export default function TicketsPage() {
</div>
</div>
{showExtraFilters && (
<div className="grid grid-cols-1 sm:grid-cols-4 gap-3 mt-3">
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3 mt-3">
<div>
<label className="label">Status</label>
<select
@@ -619,19 +635,6 @@ export default function TicketsPage() {
<option value="CANCELLED">Cancelled</option>
</select>
</div>
<div>
<label className="label">Coach</label>
<select
className="input"
value={filters.coachId}
onChange={(e) => setFilters({ ...filters, coachId: e.target.value })}
>
<option value="">All Coaches</option>
{(Array.isArray(coachesData) ? coachesData : (coachesData as any)?.data || []).map((coach: any) => (
<option key={coach.id} value={coach.id}>{coach.number}</option>
))}
</select>
</div>
<div>
<label className="label">Issued From</label>
<input type="date" className="input" value={filters.dateFrom}
@@ -794,8 +797,8 @@ export default function TicketsPage() {
<section>
<SectionHeader title="Trip Information" />
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<Field label="Origin" value={t.schedule?.originStation?.name} />
<Field label="Destination" value={t.schedule?.destinationStation?.name} />
<Field label="Origin" value={t.booking?.originStation?.name || t.schedule?.originStation?.name} />
<Field label="Destination" value={t.booking?.destinationStation?.name || t.schedule?.destinationStation?.name} />
<Field label="Departure" value={t.schedule?.departureAt ? formatDateTime(t.schedule.departureAt) : ''} />
<Field label="Arrival" value={t.schedule?.arrivalAt ? formatDateTime(t.schedule.arrivalAt) : ''} />
<Field label="Train" value={t.schedule?.train?.name || t.schedule?.train?.number} />

View File

@@ -121,8 +121,9 @@ const navigationSections: { title: string; items: NavItem[] }[] = [
{
title: 'Analytics & Reports',
items: [
{ name: 'Overall', href: '/reports', icon: BarChart3, permission: PERMS.reports.view },
{ name: 'Seats', href: '/reports/seats', icon: Armchair, permission: PERMS.reports.view },
{ name: 'Overall', href: '/reports', icon: BarChart3, permission: PERMS.reports.view },
{ name: 'Seats', href: '/reports/seats', icon: Armchair, permission: PERMS.reports.view },
{ name: 'Passengers', href: '/reports/passengers', icon: Users, permission: PERMS.reports.view },
// { name: 'Operational Reports', href: '/operational-reports', icon: FileText, permission: PERMS.reports.view },
]
},

View File

@@ -11,6 +11,7 @@ export const dashboardApi = {
totalNormalTickets: number;
totalPackageTickets: number;
totalPassengers: number;
blockedSeatsCount: number;
revenueByCurrency: { currency: string; totalMinor: number }[];
packageRevenueByCurrency: { currency: string; totalMinor: number }[];
}>('/dashboard/backoffice-stats');

View File

@@ -949,10 +949,9 @@ export default function SeatsPage() {
return;
}
// No fare change — but for package bookings still sync the tier price to the
// actual berth fare (handles the case where the first seat picked matches the
// stored price but we still want it explicitly confirmed).
if (isPackageBooking && packageId && newFare !== packageTierPriceMinor) {
// No fare change — for package bookings still sync the tier price to the
// actual berth fare so the correct amount is always stored.
if (isPackageBooking && packageId) {
setPackageContext(
packageId,
priceTierId ?? '',
@@ -962,6 +961,8 @@ export default function SeatsPage() {
packageDepartureStationName ?? undefined,
);
}
} else if (isPackageBooking && packageId) {
// newFare is null (seat class data unavailable) — leave stored price as-is.
}
commitSeatAssignment(seatId);

View File

@@ -401,7 +401,6 @@ const PKG_CHILDREN_PER_ADULT = 5;
function PassengerCountModal({
tier,
minPriceMinor,
onClose,
onConfirm,
loading,
@@ -410,7 +409,6 @@ function PassengerCountModal({
stations,
}: {
tier: PriceTier;
minPriceMinor: number;
onClose: () => void;
onConfirm: (adultCount: number, childCount: number, departureStationId: string, departureStationName: string) => void;
loading: boolean;
@@ -423,11 +421,9 @@ function PassengerCountModal({
const [departureStationId, setDepartureStationId] = useState('');
const [showStationError, setShowStationError] = useState(false);
const remaining = tier.availableSeats - tier.bookedSeats;
// First child per adult travels free (no seat); additional children pay full adult fare
const freeChildren = Math.min(childCount, adultCount);
const paidChildren = Math.max(0, childCount - adultCount);
// Only paid children need seats; free children share with an adult
const totalMinor = (adultCount * minPriceMinor + paidChildren * minPriceMinor) * priceMultiplier;
const totalMinor = (adultCount * tier.priceMinor + paidChildren * tier.priceMinor) * priceMultiplier;
return (
<>
@@ -444,7 +440,7 @@ function PassengerCountModal({
<div className="px-6 py-3 bg-primary/5 border-b border-primary/10">
<p className="text-xs text-gray-400 uppercase tracking-wide font-semibold">Coach type</p>
<p className="text-sm font-bold text-gray-900 dark:text-white mt-0.5">{tier.seatClass?.coachType?.name ?? tier.label.trim()}</p>
<p className="text-xs text-gray-400 mt-0.5">{remaining} seats remaining · from {formatPrice(minPriceMinor * priceMultiplier, tier.currency)} per adult · 1st child per adult free (no seat)</p>
<p className="text-xs text-gray-400 mt-0.5">{remaining} seats remaining · from {formatPrice(tier.priceMinor * priceMultiplier, tier.currency)} per adult · 1st child per adult free (no seat)</p>
</div>
<div className="px-6 py-5 space-y-4">
@@ -646,6 +642,8 @@ export default function PackageDetailPage() {
);
// Store per-adult tier price (×1 leg); review page applies round-trip multiplier and child pricing
// Store the group's cheapest tier price as a placeholder — the actual berth fare
// (Upper/Middle/Lower) will be resolved and saved when the user picks a seat.
setPackageContext(id, representativeTier.id, representativeTier.priceMinor, pkg.name, departureStationId, departureStationName);
router.push("/booking/passengers");
@@ -696,7 +694,6 @@ export default function PackageDetailPage() {
{passengerModalOpen && representativeTier && (
<PassengerCountModal
tier={representativeTier}
minPriceMinor={selectedGroup?.minPrice ?? representativeTier.priceMinor}
onClose={() => { setPassengerModalOpen(false); setBookingContextError(null); }}
onConfirm={handleBookNow}
loading={bookingContextLoading}
@@ -896,7 +893,7 @@ export default function PackageDetailPage() {
{/* ── Sidebar — desktop ── */}
<div className="hidden lg:block">
<div className="sticky top-20">
<div>
<PriceTiersPanel
tiers={pkg.priceTiers}
onBookNow={(coachTypeId) => { setSelectedCoachTypeId(coachTypeId); setPassengerModalOpen(true); }}

View File

@@ -8,8 +8,12 @@ import {
Query,
UseGuards,
} from "@nestjs/common";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import { PaymentIntentSnapshot } from "@edr/types";
import { ApiOperation, ApiQuery, ApiTags } from "@nestjs/swagger";
import {
PaymentIntentSnapshot,
ProviderMethod,
ProviderStatus,
} from "@edr/types";
import { ServiceAuthGuard } from "../../common/guards/service-auth.guard";
import {
InitiatePaymentRequestDto,
@@ -17,6 +21,7 @@ import {
} from "./dto/initiate-payment.dto";
import { ConfirmPaymentDto } from "./dto/confirm-payment.dto";
import { IntentsService } from "./intents.service";
import { PaymentIntent } from "./entities/payment-intent.entity";
/**
* Internal surface — called only by the domain apps (service-authenticated), never by
@@ -68,6 +73,41 @@ export class IntentsController {
);
}
@Get("diagnostic")
@ApiOperation({
summary: "DB row + live provider status by domain reference (diagnostic)",
description:
"Returns { db, provider } for a domain reference (service + referenceType + referenceId): " +
"the active stored intent row and a live provider status query, side by side. Pure read — " +
"does not mutate the intent. `db` is null when no active intent exists for the reference.",
})
async getDiagnosticByReference(
@Query() query: IntentReferenceQueryDto,
): Promise<{ db: PaymentIntent | null; provider: ProviderStatus | null }> {
return this.intentsService.getDiagnosticByReference(
query.service,
query.referenceType,
query.referenceId,
);
}
@Get("by-merchant-order/:merchantOrderId")
@ApiOperation({
summary: "DB row + live provider status by merchant order id (diagnostic)",
description:
"Returns { db, provider } for a provider-facing merchant order id (PSG-/FRT-…): the " +
"stored intent row and a live provider status query, side by side. Pure read — does not " +
"mutate the intent. `db` is null when no intent has this merchant order id; supply " +
"`?provider=` in that case so the provider can still be queried by merchant order id.",
})
@ApiQuery({ name: "provider", enum: ProviderMethod, required: false })
async getByMerchantOrderId(
@Param("merchantOrderId") merchantOrderId: string,
@Query("provider") provider?: ProviderMethod,
): Promise<{ db: PaymentIntent | null; provider: ProviderStatus | null }> {
return this.intentsService.getByMerchantOrderId(merchantOrderId, provider);
}
@Post("intents/:id/confirm")
@ApiOperation({
summary: "Confirm an OTP-based payment intent (e.g. CAC Bank)",

View File

@@ -341,6 +341,90 @@ export class IntentsService {
return this.toSnapshot(await this.refreshIfStale(intent));
}
/**
* Diagnostic lookup by domain reference (service + referenceType + referenceId). Returns the
* stored intent AND a LIVE provider status query side by side — the reference-keyed twin of
* {@link getByMerchantOrderId}, used by the domain apps to resolve a booking/shipment without
* knowing the merchant order id. Pure read (no state-machine mutation).
*
* - `db`: the active stored intent for the reference, or `null` when none exists.
* - `provider`: the raw provider status response (queried using the intent's own provider), or
* `null` when there is no intent or the query fails.
*/
async getDiagnosticByReference(
service: PaymentService,
referenceType: PaymentReferenceType,
referenceId: string,
): Promise<{ db: PaymentIntent | null; provider: ProviderStatus | null }> {
const intent = await this.intentsRepository.findActiveByReference(
service,
referenceType,
referenceId,
);
const providerStatus = intent
? await this.queryProviderForMerchantOrder(
intent.merchantOrderId,
intent,
undefined,
)
: null;
return { db: intent ?? null, provider: providerStatus };
}
/**
* Diagnostic lookup by provider-facing merchant order id (PSG-/FRT-…). Returns the stored
* intent AND a LIVE provider status query side by side, so the caller can compare what the
* platform believes against what the provider currently reports. This is a pure read — it
* does NOT mutate the intent (no state-machine transition, no outbox event).
*
* - `db`: the full stored intent row, or `null` when no intent has this merchant order id.
* - `provider`: the raw provider status response. When there is a DB row its provider is
* used; when there is no DB row a `providerHint` must be supplied to know which provider
* to ask (the merchant-order prefix only identifies the service). `null` if the provider
* is unknown or the query fails.
*/
async getByMerchantOrderId(
merchantOrderId: string,
providerHint?: ProviderMethod,
): Promise<{ db: PaymentIntent | null; provider: ProviderStatus | null }> {
const intent =
await this.intentsRepository.findByMerchantOrderId(merchantOrderId);
const providerStatus = await this.queryProviderForMerchantOrder(
merchantOrderId,
intent,
providerHint,
);
return { db: intent ?? null, provider: providerStatus };
}
/** Best-effort live provider status for a merchant order id; never throws (returns null). */
private async queryProviderForMerchantOrder(
merchantOrderId: string,
intent: PaymentIntent | null,
providerHint?: ProviderMethod,
): Promise<ProviderStatus | null> {
try {
if (intent) {
const provider = this.providers.get(intent.provider);
if (!provider) return null;
return await this.queryProviderStatus(intent);
}
// No DB row — fall back to the caller-supplied provider hint keyed on merchantOrderId.
if (!providerHint) return null;
const provider = this.providers.get(providerHint);
if (!provider) return null;
return await provider.queryStatus(merchantOrderId);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
this.logger.warn(
`provider status query failed for merchantOrderId ${merchantOrderId}: ${message}`,
);
return null;
}
}
/**
* Pull-side reconciliation: when a polled intent is non-terminal and stale, ask the
* provider for the truth and run the answer through the state machine. The browser