Enhance overview and train scheduling features

- Updated OverviewContractsTabPanel to include a new donut chart for freight type distribution.
- Modified OverviewOperationsTabPanel to improve data visualization with additional charts and refactored data handling.
- Introduced CreateScheduleWindowFields component for configuring booking windows in train scheduling.
- Added new API endpoints for allocation candidates and booking allocation in trainScheduling.service.
- Enhanced BookingRequestsPage to support allocation of paid bookings with a modal for selecting alternative dates.
- Updated QUERY_KEYS and URLS constants to accommodate new operations and features.
- Improved type definitions for overview and train scheduling to support new functionalities.
This commit is contained in:
Marshal
2026-08-03 21:06:59 +00:00
parent 488c2465be
commit e68bdb7a1a
30 changed files with 1580 additions and 82 deletions

View File

@@ -151,6 +151,14 @@ export interface ExportTrainOption {
}>;
}
/** A train a paid-unallocated booking can board (route + capacity verified). */
export interface AllocationCandidate {
id: string;
reference: string | null;
direction: string | null;
scheduledDepartureDate: Date;
}
/** A day-level pool key: all trains on this route departing on this EAT day. */
interface RouteDayGroup {
originYardId: string;
@@ -3040,6 +3048,104 @@ export class BookingBatchService implements OnModuleInit {
this.notifyBoardChanged(newScheduleId, "booking_moved");
}
/**
* Trains a paid-but-unallocated booking can board right now: OPEN window,
* future departure, route covers the booking's leg, and remaining corridor
* capacity fits it. Split by the booking's own scheduled day so the UI can
* offer one-click same-day allocation vs an explicit "another date" choice.
*/
async allocationCandidates(bookingId: string): Promise<{
sameDay: AllocationCandidate[];
otherDays: AllocationCandidate[];
}> {
const booking = await this.dataSource.getRepository(Booking).findOne({
where: { id: bookingId },
relations: {
bookingContainers: { containerType: true },
// wagonTypes drives the break-bulk items-per-wagon fit — size the
// booking exactly as the intercity accept check does.
cargoType: { wagonTypes: true },
},
});
if (!booking) throw new NotFoundException(`Booking ${bookingId} not found`);
const schedules = await this.trainSchedulesRepository.findAll({
where: [
{ status: TrainScheduleStatusEnum.Draft },
{ status: TrainScheduleStatusEnum.Scheduled },
],
});
const today = eatDay(new Date());
const bookingDay = booking.scheduledDate ? eatDay(booking.scheduledDate) : null;
const sameDay: AllocationCandidate[] = [];
const otherDays: AllocationCandidate[] = [];
for (const s of schedules) {
if (!s.scheduledDepartureDate || eatDay(s.scheduledDepartureDate) < today) continue;
if (s.bookingWindowStatus !== "OPEN") continue;
if (s.id === booking.trainScheduleId) continue;
const stops = await this.stopsForSchedule(s);
const fromIdx = stops.indexOf(booking.originYardId);
const toIdx = stops.indexOf(booking.destinationYardId);
if (fromIdx < 0 || toIdx < 0 || fromIdx >= toIdx) continue;
// ponytail: full capacity build per candidate is heavy; the set is small
// (future OPEN trains on the booking's route) — precompute if it grows.
const cap = await this.intercityCapacity(s.id);
if (!cap) continue;
const leg = cap.budget.legForYards(booking.originYardId, booking.destinationYardId);
if (!cap.budget.fits(cap.needFor(booking), leg)) continue;
const candidate: AllocationCandidate = {
id: s.id,
reference: s.reference ?? s.trainNumber ?? null,
direction: s.direction ?? null,
scheduledDepartureDate: s.scheduledDepartureDate,
};
(eatDay(s.scheduledDepartureDate) === bookingDay ? sameDay : otherDays).push(candidate);
}
const byDate = (a: AllocationCandidate, b: AllocationCandidate) =>
new Date(a.scheduledDepartureDate).getTime() - new Date(b.scheduledDepartureDate).getTime();
sameDay.sort(byDate);
otherDays.sort(byDate);
return { sameDay, otherDays };
}
/**
* Place a PAID booking that lost (or never got) its train: re-point via
* moveToSchedule (window/route validation + day sync), then allocate it
* immediately — payment already landed, so no new pay window opens. The
* customer gets an in-app notice when the new train departs on a different
* day than their original choice.
*/
async allocatePaid(bookingId: string, scheduleId: string): Promise<void> {
const before = await this.dataSource
.getRepository(Booking)
.findOne({ where: { id: bookingId } });
if (!before) throw new NotFoundException(`Booking ${bookingId} not found`);
if (before.paymentStatus !== "PAID" && before.status !== "PAID") {
throw new BadRequestException(
"Booking is not paid — use the regular scheduling flow",
);
}
const previousDay = before.scheduledDate ? eatDay(before.scheduledDate) : null;
await this.moveToSchedule(bookingId, scheduleId);
const fresh = await this.dataSource.getRepository(Booking).findOne({
where: { id: bookingId },
relations: { bookingContainers: { containerType: true }, cargoType: true },
});
if (!fresh) return;
if (!(await this.holdIfWagonShort(scheduleId, fresh))) {
await this.allocate(scheduleId, fresh, "paid");
}
const schedule = await this.dataSource
.getRepository(TrainSchedule)
.findOne({ where: { id: scheduleId } });
if (
previousDay &&
schedule?.scheduledDepartureDate &&
eatDay(schedule.scheduledDepartureDate) !== previousDay
) {
this.notifier.allocatedOtherDay(fresh, schedule.scheduledDepartureDate);
}
}
/**
* One reminder per hold, shortly before its pay deadline (the window tick
* calls this every pass; `payment_reminder_sent_at` dedups). Skips paid
@@ -3526,6 +3632,16 @@ export class BookingBatchService implements OnModuleInit {
}
return;
}
// Paid but detached from any train (staff removed it from an allocation,
// or a sweep caught it unpinned): money was taken, so it must board — it
// stays paid-unallocated for staff to place via the allocate action.
if (paid) {
this.logger.log(
`[BATCH] expire skipped for ${booking.reference} — payment landed ` +
`but no train attached; left paid-unallocated for manual placement`,
);
return;
}
// Reconcile-before-expire (only when a pay window was actually open):
// no webhook arrived, so ask the gateway DIRECTLY whether the money
// landed. A late capture found there is registered as SUCCEEDED and
@@ -3854,12 +3970,26 @@ export class BookingBatchService implements OnModuleInit {
// booking can use — don't kill it for nothing.
const overlaps = victimLeg.fromEdge < leg.toEdge && leg.fromEdge < victimLeg.toEdge;
if (!overlaps) continue;
const victimPaid =
victim.paymentStatus === "PAID" || victim.status === "PAID";
await this.dataSource.transaction(async (manager) => {
await this.trainScheduleBookingsRepository.deleteByScheduleAndBooking(
scheduleId,
victim.id,
manager,
);
if (victimPaid) {
// Paid bookings are never expired — money was taken, so it boards.
// Detach it so it surfaces in the paid-unallocated queue for staff
// to re-place; the settled invoice stays untouched.
await manager.getRepository(Booking).update(victim.id, {
trainScheduleId: null,
schedulingStatus: "ELIGIBLE",
paymentDeadline: null,
selectedForBatchAt: null,
} as never);
return;
}
await manager.getRepository(Booking).update(victim.id, {
status: "EXPIRED",
schedulingStatus: "ELIGIBLE",

View File

@@ -275,6 +275,19 @@ export class BookingNotifierService {
this.inApp(b, 'Booking rescheduled', msg);
}
/**
* Staff placed a paid booking onto a train departing on a DIFFERENT day than
* the customer's original choice. In-app only — staff drove the change and
* the allocation itself already notifies through the secured path.
*/
allocatedOtherDay(b: Booking, newDeparture: Date): void {
const when = newDeparture.toLocaleDateString('en-GB', { timeZone: BATCH_TIMEZONE });
const msg =
`Booking ${b.reference ?? b.id} has been allocated to a train on a different date. ` +
`New departure date: ${when}.`;
this.inApp(b, 'Booking allocated to another date', msg);
}
/**
* Booking was removed from its train during a staff reschedule (not a government
* pre-empt). It returns to eligible — the customer must rebook or reschedule.

View File

@@ -9,9 +9,107 @@ import {
IsNumber,
IsOptional,
IsUUID,
Max,
Min,
ValidateNested,
} from 'class-validator';
/**
* Per-schedule booking-window rule chosen AT CREATION, instead of inheriting the
* live global rules. Mirrors {@link UpdateScheduleWindowRuleDto}, plus the
* booking-close offset (which the post-creation override deliberately never
* touches). Every field is optional — an omitted field falls back to the global
* value, so staff can override just the one knob they care about.
*/
export class CreateScheduleWindowRuleDto {
@ApiPropertyOptional({ example: 8, description: 'Local EAT hour the booking desk opens each day' })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(0)
@Max(23)
windowOpenHour?: number;
@ApiPropertyOptional({
example: 17,
description:
'Local EAT hour the booking desk shuts each day. Equal to windowOpenHour = 24-hour desk',
})
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(0)
@Max(23)
windowCloseHour?: number;
@ApiPropertyOptional({ example: 3, description: 'How long each booking cycle stays open, in hours' })
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0.0166)
@Max(12)
windowDurationHours?: number;
@ApiPropertyOptional({ example: 30, description: 'Max staff document-review minutes after the window closes' })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(0)
docReviewMinutes?: number;
@ApiPropertyOptional({ example: 60, description: 'Customer payment window minutes' })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
paymentWindowMinutes?: number;
@ApiPropertyOptional({
example: 3,
description: 'Days before departure the IMPORT/DOMESTIC booking window starts',
})
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(0)
importWindowLeadDays?: number;
@ApiPropertyOptional({
example: 24,
description: 'Hours before departure the single FCFS EXPORT window opens',
})
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
exportBookingLeadHours?: number;
@ApiPropertyOptional({
example: 180,
nullable: true,
description:
'Minutes before departure the booking window closes; 0/null = close at departure. ' +
'Only the offset matching the schedule direction is used (import offset for ' +
'IMPORT/DOMESTIC, export offset for EXPORT).',
})
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(0)
importCloseOffsetMinutes?: number | null;
@ApiPropertyOptional({
example: 1440,
nullable: true,
description: 'Minutes before departure an EXPORT booking window closes; 0/null = at departure',
})
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(0)
exportCloseOffsetMinutes?: number | null;
}
export class CreateContainerTrainScheduleDto {
@ApiProperty({ format: 'uuid' })
@IsUUID()
@@ -73,4 +171,19 @@ export class CreateContainerTrainScheduleDto {
@IsOptional()
@IsBoolean()
reverseWagonOrder?: boolean;
@ApiPropertyOptional({
type: CreateScheduleWindowRuleDto,
description:
'Configure the booking window for THIS schedule instead of inheriting the live ' +
'global rules. Omit to use the global rules (the default). The values sent are ' +
'frozen onto the schedule as its rule snapshot, exactly as a post-creation ' +
'override would. Rejected for an IMPORT/DOMESTIC train that joins an existing ' +
'route+day group — those siblings share one window timeline, so edit the group ' +
"window instead of giving one member its own.",
})
@IsOptional()
@ValidateNested()
@Type(() => CreateScheduleWindowRuleDto)
windowRule?: CreateScheduleWindowRuleDto;
}

View File

@@ -842,6 +842,32 @@ export class TrainSchedulingController {
return { ok: true };
}
@Get("bookings/:bookingId/allocation-candidates")
@TrainSchedulingView()
@ApiOperation({
summary:
"Trains a paid-unallocated booking fits, split same-day vs other days",
})
getAllocationCandidates(
@Param("bookingId", ParseUUIDPipe) bookingId: string,
) {
return this.bookingBatchService.allocationCandidates(bookingId);
}
@Post("bookings/:bookingId/allocate")
@TrainSchedulingUpdate()
@ApiOperation({
summary:
"Staff: place a paid booking onto a fitting train (notifies customer on date change)",
})
async allocatePaidBooking(
@Param("bookingId", ParseUUIDPipe) bookingId: string,
@Body("trainScheduleId", ParseUUIDPipe) trainScheduleId: string,
) {
await this.bookingBatchService.allocatePaid(bookingId, trainScheduleId);
return { ok: true };
}
@Get("schedules/:id/checkpoints")
@TrainSchedulingView()
@ApiOperation({

View File

@@ -805,6 +805,51 @@ describe('TrainSchedulingService', () => {
).rejects.toBeInstanceOf(BadRequestException);
});
describe('restampPendingWindows (hand-configured windows are exempt)', () => {
const future = new Date(Date.now() + 30 * 24 * 3600_000);
const update = jest.fn();
beforeEach(() => {
update.mockClear();
// Global rules read + the TrainSchedule repo the restamp writes through.
dataSource.getRepository.mockImplementation((entity: unknown) => {
const name = (entity as { name?: string })?.name;
if (name === 'TrainSchedulingGlobalRules') {
return { find: jest.fn().mockResolvedValue([]) };
}
return { update };
});
});
it('re-stamps a schedule that follows the global rules', async () => {
trainSchedulesRepository.findAll.mockResolvedValue([
{
id: 'sched-global',
direction: 'IMPORT',
scheduledDepartureDate: future,
windowRuleCustom: false,
},
]);
await expect(service.restampPendingWindows()).resolves.toBe(1);
expect(update).toHaveBeenCalledWith('sched-global', expect.anything());
});
it('leaves a hand-configured schedule alone', async () => {
trainSchedulesRepository.findAll.mockResolvedValue([
{
id: 'sched-custom',
direction: 'IMPORT',
scheduledDepartureDate: future,
windowRuleCustom: true,
},
]);
// Staff picked these times deliberately — a global-rules edit must not
// overwrite them, or the per-schedule configuration would be pointless.
await expect(service.restampPendingWindows()).resolves.toBe(0);
expect(update).not.toHaveBeenCalled();
});
});
describe('getUnassignedBookings', () => {
const scheduleId = 'sched-unassigned-1';
const trainSetId = 'train-set-unassigned';

View File

@@ -181,6 +181,13 @@ import {
const SCHEDULABLE_BOOKING_STATUSES = ['PAID'] as const;
/** Drops the keys a partial override left undefined, so `...` merges keep the base value. */
function pickDefined<T extends object>(source: T): Partial<T> {
return Object.fromEntries(
Object.entries(source).filter(([, v]) => v !== undefined),
) as Partial<T>;
}
/**
* The booking-window rule fields frozen onto a train schedule at creation (and
* refreshed by restampPendingWindows for not-yet-open schedules). The board draws
@@ -906,6 +913,9 @@ export class TrainSchedulingService {
windowClosesAt: cap(times.windowClosesAt, t.departure),
...ruleFields,
rulePaymentWindowMinutes,
// Deliberately overridden — exempt from the global re-stamp, which would
// otherwise revert this schedule the next time global rules are saved.
windowRuleCustom: true,
});
}
this.logger.log(
@@ -1197,6 +1207,9 @@ export class TrainSchedulingService {
let restamped = 0;
for (const s of schedules) {
if (!s.scheduledDepartureDate || s.scheduledDepartureDate <= now) continue;
// Hand-configured windows are not "pending the global rule" — staff picked
// these times deliberately, so a global-rules edit must leave them alone.
if (s.windowRuleCustom) continue;
const times =
s.direction === 'EXPORT'
? computeExportWindowTimes(s.scheduledDepartureDate, cfg)
@@ -1460,29 +1473,8 @@ export class TrainSchedulingService {
// it on schedule. DOMESTIC runs the same one-booking-day cycle as IMPORT
// (opens at 08:00 EAT `importWindowLeadDays` before departure); EXPORT opens
// 24h before departure (FCFS). No schedule is ever always-open now.
const windowCfg = await this.getWindowConfig();
const globalCfg = await this.getWindowConfig();
// Staff cannot schedule inside the lead window — there must be room for a
// booking window before departure. IMPORT/DOMESTIC lead is in whole EAT
// days (lead 3, today 11th → first allowed departure is the 14th); EXPORT
// lead is in hours (24h = 1 day ahead).
const earliest = earliestSchedulableDeparture(direction, windowCfg, new Date());
if (departure.getTime() < earliest.getTime()) {
const detail =
direction === 'EXPORT'
? `at least ${windowCfg.exportBookingLeadHours} hour(s) ahead`
: `at least ${windowCfg.importWindowLeadDays} day(s) ahead`;
throw new BadRequestException(
`Departure ${departure.toISOString()} is inside the booking lead window; ` +
`${direction === 'EXPORT' ? 'export' : 'import'} trains must be scheduled ${detail} ` +
`(earliest ${earliest.toISOString()})`,
);
}
// Freeze the rule this schedule is born with. A later global-rules edit
// only re-derives NOT-YET-OPEN schedules (see restampPendingWindows); an
// already-open schedule keeps this snapshot, and the batch board draws its
// windows from it rather than the live config.
const ruleSnapshot = windowRuleSnapshot(windowCfg);
// Route+day grouping (IMPORT/DOMESTIC only): if a schedule already exists
// on this origin + destination + EAT departure day, this new train JOINS
// its group and adopts the group's shared window timeline (open/close +
@@ -1506,6 +1498,77 @@ export class TrainSchedulingService {
route.destinationYardId,
departure,
);
// Per-schedule window rule chosen at creation. Refused for a train that
// JOINS an existing route+day group: the group shares ONE window timeline,
// so a joining train adopts the anchor's times verbatim and its own
// settings would be silently discarded. Staff edit the group's window
// instead (Booking window settings, which fans out to every sibling).
if (dto.windowRule && groupAnchor) {
throw new BadRequestException(
'This train joins an existing booking group (same route and departure day), ' +
'which shares one booking window across all its trains. Create it with the ' +
'group settings, then use Booking window settings to change the window for ' +
'the whole group.',
);
}
// The rule this schedule is born under: staff overrides on top of the live
// global config, so an omitted field still follows the global value.
const windowCfg: BookingWindowConfig = dto.windowRule
? {
...globalCfg,
...pickDefined({
windowOpenHour: dto.windowRule.windowOpenHour,
windowCloseHour: dto.windowRule.windowCloseHour,
windowDurationHours: dto.windowRule.windowDurationHours,
docReviewMinutes: dto.windowRule.docReviewMinutes,
importWindowLeadDays: dto.windowRule.importWindowLeadDays,
exportBookingLeadHours: dto.windowRule.exportBookingLeadHours,
}),
// One pay-window override drives both directions (only the one
// matching this schedule's direction is ever read).
...(dto.windowRule.paymentWindowMinutes !== undefined
? {
paymentWindowMinutes: dto.windowRule.paymentWindowMinutes,
exportPaymentWindowMinutes: dto.windowRule.paymentWindowMinutes,
}
: {}),
// Close offsets are nullable-by-intent: null/0 means "close at
// departure", which must override a non-null global, so these are
// merged on presence rather than on definedness.
...(dto.windowRule.importCloseOffsetMinutes !== undefined
? { importCloseOffsetMinutes: dto.windowRule.importCloseOffsetMinutes ?? null }
: {}),
...(dto.windowRule.exportCloseOffsetMinutes !== undefined
? { exportCloseOffsetMinutes: dto.windowRule.exportCloseOffsetMinutes ?? null }
: {}),
}
: globalCfg;
// Staff cannot schedule inside the lead window — there must be room for a
// booking window before departure. IMPORT/DOMESTIC lead is in whole EAT
// days (lead 3, today 11th → first allowed departure is the 14th); EXPORT
// lead is in hours (24h = 1 day ahead). Checked against the schedule's OWN
// lead, so a custom lead is honoured rather than rejected by the global one.
const earliest = earliestSchedulableDeparture(direction, windowCfg, new Date());
if (departure.getTime() < earliest.getTime()) {
const detail =
direction === 'EXPORT'
? `at least ${windowCfg.exportBookingLeadHours} hour(s) ahead`
: `at least ${windowCfg.importWindowLeadDays} day(s) ahead`;
throw new BadRequestException(
`Departure ${departure.toISOString()} is inside the booking lead window; ` +
`${direction === 'EXPORT' ? 'export' : 'import'} trains must be scheduled ${detail} ` +
`(earliest ${earliest.toISOString()})`,
);
}
// Freeze the rule this schedule is born with. A later global-rules edit
// only re-derives NOT-YET-OPEN schedules (see restampPendingWindows); an
// already-open schedule keeps this snapshot, and the batch board draws its
// windows from it rather than the live config.
const ruleSnapshot = windowRuleSnapshot(windowCfg);
const computedTimes =
direction === 'EXPORT'
? { ...ruleSnapshot, ...computeExportWindowTimes(departure, windowCfg) }
@@ -1514,12 +1577,30 @@ export class TrainSchedulingService {
...ruleSnapshot,
...computeImportWindowTimes(departure, windowCfg, new Date()),
};
if (
computedTimes.windowOpensAt.getTime() >= computedTimes.windowClosesAt.getTime()
) {
throw new BadRequestException(
'These booking-window settings leave no window before departure — with the ' +
'desk hours and close offset applied, the window would only open once the ' +
'train has left.',
);
}
const windowFields = {
bookingWindowStatus: 'CLOSED',
windowPhase: 'PRE_WINDOW',
...(groupAnchor
? this.groupWindowFieldsFrom(groupAnchor, departure)
: computedTimes),
// `windowRuleSnapshot` never stamps the pay window (NULL = follow the
// live global value for the direction), so an explicit staff override is
// persisted here — the same field the post-creation override writes.
...(dto.windowRule?.paymentWindowMinutes !== undefined
? { rulePaymentWindowMinutes: dto.windowRule.paymentWindowMinutes }
: {}),
// Hand-configured windows opt OUT of the global re-stamp, or the next
// global-rules edit would overwrite exactly what staff chose here.
windowRuleCustom: dto.windowRule != null,
};
// A built train's own consist is the schedule's capacity: full when all
// its wagons are allocated. Trains built without wagons yet fall back to