Files
edr-platform/apps/edr-freight-api/src/modules/train-scheduling/fleet-plan.util.ts
Marshal 11771e5f92 remove reopen delay minutes from global rules and update related types
- Removed the  field from  and related components.
- Updated  to reflect the removal of the reopen delay input field.
- Modified  to include new train number fields:  and .
- Added  interface to manage active schedules with trade direction.
- Introduced  interface to track wagon shortages in bookings.
- Updated  logic to ensure consistent UI state representation.
- Created migrations to drop the  column and add  and  columns to the  table.
- Added tests for the new booking window display logic and wagon planning functionality.
2026-07-15 09:13:02 +00:00

192 lines
6.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { Booking } from '../bookings/entities/booking.entity';
import type { WagonType } from '../wagon-types/entities/wagon-type.entity';
import {
buildBulkWagonPlan,
buildContainerWagonPlan,
buildMixedWagonPlan,
containerWagonsForLines,
roundTons,
type WagonPlanSlot,
} from './wagon-plan.util';
export type FleetAvailabilityRow = {
wagonTypeId: string;
wagonTypeCode: string;
needed: number;
available: number;
shortfall: number;
};
/** Per-booking wagon shortage: how many wagons of which type this booking still lacks. */
export type BookingWagonShortage = {
/** Candidate wagon-type codes usable by the booking, joined ("NW6" or "NW6/CW3"). */
wagonTypeCodes: string;
wagonsNeeded: number;
wagonsAvailable: number;
wagonsShort: number;
};
export type DeferredBookingRow = {
id: string;
reference: string;
reason: string;
/** Set when the deferral is a fleet-stock shortage (absent for config issues). */
shortage?: BookingWagonShortage | null;
};
export function sortBookingsForScheduling(bookings: Booking[]): Booking[] {
return [...bookings].sort((a, b) => {
const govDiff = Number(Boolean(b.isGovernment)) - Number(Boolean(a.isGovernment));
if (govDiff !== 0) return govDiff;
const priorityDiff = (b.priorityScore ?? 0) - (a.priorityScore ?? 0);
if (priorityDiff !== 0) return priorityDiff;
const aTime = a.scheduledDate ? new Date(a.scheduledDate).getTime() : 0;
const bTime = b.scheduledDate ? new Date(b.scheduledDate).getTime() : 0;
return aTime - bTime;
});
}
export function wagonsRequiredForBooking(booking: Booking, bulkWagonCapacity?: number): number {
if (booking.freightType === 'BULK') {
const weight = Number(booking.cargoTotalWeightVgm ?? 0);
const capacity = bulkWagonCapacity && bulkWagonCapacity > 0 ? bulkWagonCapacity : 1;
return Math.max(1, Math.ceil(weight / capacity));
}
// TEU-aware, ceiled once at the booking level (40ft = 1 wagon, two 20ft = 1
// wagon). Honors containerType.wagonsPerUnit; falls back to the line's stored
// fraction. Ceiling per line would over-count split 20ft lines.
return Math.max(1, containerWagonsForLines(booking.bookingContainers ?? []));
}
export function countSlotsByType(wagonPlan: WagonPlanSlot[]): Map<string, { code: string; count: number }> {
const map = new Map<string, { code: string; count: number }>();
for (const slot of wagonPlan) {
const existing = map.get(slot.wagonTypeId) ?? { code: slot.wagonTypeCode, count: 0 };
existing.count += 1;
map.set(slot.wagonTypeId, existing);
}
return map;
}
export function computeFleetAvailability(
demandPlan: WagonPlanSlot[],
fleetByTypeId: Map<string, number>,
fleetTypeCodes: Map<string, string>,
): FleetAvailabilityRow[] {
const neededByType = countSlotsByType(demandPlan);
const typeIds = new Set([...neededByType.keys(), ...fleetByTypeId.keys()]);
return [...typeIds].map((wagonTypeId) => {
const needed = neededByType.get(wagonTypeId)?.count ?? 0;
const available = fleetByTypeId.get(wagonTypeId) ?? 0;
return {
wagonTypeId,
wagonTypeCode:
neededByType.get(wagonTypeId)?.code ??
fleetTypeCodes.get(wagonTypeId) ??
wagonTypeId,
needed,
available,
shortfall: Math.max(0, needed - available),
};
}).filter((row) => row.needed > 0 || row.available > 0);
}
export function selectBookingsWithinFleetCap(
bookings: Booking[],
fleetByTypeId: Map<string, number>,
resolveWagonTypeId: (booking: Booking) => string,
bulkWagonCapacity?: number,
): { fitting: Booking[]; deferred: DeferredBookingRow[] } {
const remaining = new Map(fleetByTypeId);
const fitting: Booking[] = [];
const deferred: DeferredBookingRow[] = [];
for (const booking of sortBookingsForScheduling(bookings)) {
const typeId = resolveWagonTypeId(booking);
const needed = wagonsRequiredForBooking(booking, bulkWagonCapacity);
const available = remaining.get(typeId) ?? 0;
if (available >= needed) {
remaining.set(typeId, available - needed);
fitting.push(booking);
continue;
}
deferred.push({
id: booking.id,
reference: booking.reference,
reason:
available > 0
? `Needs ${needed} wagons but only ${available} available for this type`
: `No available wagons for required type (${needed} needed)`,
});
}
return { fitting, deferred };
}
export function buildCappedWagonPlan(params: {
bookings: Booking[];
resolvedMode: 'CONTAINER' | 'BULK' | 'MIXED';
containerWagonType: WagonType;
bulkWagonType: WagonType;
}): WagonPlanSlot[] {
const { bookings, resolvedMode, containerWagonType, bulkWagonType } = params;
if (resolvedMode === 'MIXED') {
const containerBookings = bookings.filter((b) => b.freightType === 'CONTAINER');
const bulkBookings = bookings.filter((b) => b.freightType === 'BULK');
return buildMixedWagonPlan(
containerBookings,
bulkBookings,
containerWagonType,
bulkWagonType,
);
}
if (resolvedMode === 'BULK') {
return buildBulkWagonPlan(bookings, bulkWagonType);
}
return buildContainerWagonPlan(bookings, containerWagonType);
}
export function summarizeFleetWarnings(
fleetAvailability: FleetAvailabilityRow[],
deferred: DeferredBookingRow[],
): string[] {
const warnings: string[] = [];
for (const row of fleetAvailability.filter((r) => r.shortfall > 0)) {
warnings.push(
`Fleet shortage: need ${row.needed} ${row.wagonTypeCode}, only ${row.available} available (short ${row.shortfall})`,
);
}
// Name the bookings the shortage actually hits, with their own per-type counts,
// so staff know WHAT is held out — not just that the pool is short overall.
for (const row of deferred) {
if (!row.shortage) continue;
warnings.push(
`Booking ${row.reference} held out: needs ${row.shortage.wagonsNeeded} × ${row.shortage.wagonTypeCodes}, ` +
`only ${row.shortage.wagonsAvailable} available (short ${row.shortage.wagonsShort})`,
);
}
if (deferred.length) {
warnings.push(
`${deferred.length} booking(s) deferred to next train due to insufficient fleet wagons`,
);
}
return warnings;
}
export function totalAssignedWeight(bookings: Booking[]): number {
return roundTons(bookings.reduce((sum, b) => sum + Number(b.cargoTotalWeightVgm ?? 0), 0));
}