feat: add contract extension request functionality

- Implemented  method in  to allow customers to request an extension for expired contracts.
- Added  component in  for users to initiate extension requests.
- Updated  to include logic for handling extension requests for expired contracts.
- Enhanced  to display extension request options and status.
- Created migration to add  and  columns to the contracts table.
- Added unit tests for contract extension request and handling in .
- Defined DTOs for request and extension in .
- Updated types in  to include new fields related to contract extensions.
This commit is contained in:
marshal
2026-09-06 12:33:40 +00:00
parent f225721e89
commit 75b75e3d4e
32 changed files with 1582 additions and 179 deletions

View File

@@ -75,25 +75,13 @@ import { WagonType } from '../../wagon-types/entities/wagon-type.entity';
import { WagonTypesRepository } from '../../wagon-types/wagon-types.repository';
import { Wagon } from '../../wagons/entities/wagon.entity';
import { WagonEventInput, WagonHistoryService } from '../../wagon-history/wagon-history.service';
import { TabularExportService } from '../../exports/tabular-export.service';
import {
buildWagonListWorkbook,
groupWagonListLines,
WagonListLine,
} from '../utils/wagon-list-workbook.util';
/** One line of the schedule wagon-list export (raw SQL projection). */
interface ScheduleWagonListRow {
sequenceNo: number | null;
wagonNumber: string | null;
wagonType: string | null;
containerNumber: string | null;
containerSizeFt: number | null;
loadType: string | null;
status: string | null;
bulkCargoDescription: string | null;
/** numeric columns arrive as strings from pg. */
vgmTons: string | null;
originLabel: string | null;
destinationLabel: string | null;
bookingReference: string | null;
customerName: string | null;
}
import { AdjustScheduleConsistDto } from '../dto/adjust-schedule-consist.dto';
import { AssignBookingsDto } from '../dto/assign-bookings.dto';
import { CreateContainerTrainScheduleDto } from '../dto/create-container-train-schedule.dto';
@@ -112,6 +100,7 @@ import { PreviewBulkTrainScheduleDto } from '../dto/preview-bulk-train-schedule.
import { PreviewContainerTrainScheduleDto } from '../dto/preview-container-train-schedule.dto';
import { PreviewTrainScheduleDto } from '../dto/preview-train-schedule.dto';
import { TrainSchedulingGlobalRules } from '../entities/train-scheduling-global-rules.entity';
import { WeightLimitRule } from '../../rule-engine/entities/weight-limit-rule.entity';
import { UpdateTrainSchedulingGlobalRulesDto } from '../dto/update-train-scheduling-global-rules.dto';
import {
ImportDjiboutiOperation,
@@ -160,6 +149,7 @@ import {
validateMixedTrainLimitsPerEdge,
MAX_TEU_SLOTS_PER_WAGON,
type ContainerPlacementInput,
type ContainerPlacementRules,
type WagonPlanSlot,
} from '../utils/wagon-plan.util';
import {
@@ -190,6 +180,8 @@ import {
trainSetLocomotiveLimits,
wagonTypeDimensionsFromEntity,
LocomotiveLimits,
MAX_FALLBACK_LENGTH,
MAX_FALLBACK_WEIGHT,
WagonTypeDimensions,
} from '../train-capacity.util';
import {
@@ -379,13 +371,13 @@ export interface UnassignedBookingsResponse {
bookings: CompositionUnassignedBookingRow[];
}
const DEFAULT_TRAIN_LIMITS: Required<TrainLimitConfig> = {
maxWeightTons: 3500,
maxLengthMeters: 760,
maxWagonsPerTrain: Math.floor(760 / 14),
max20ftContainerWeightTons: 30,
max20ftPairWeightDiffTons: 10,
};
/**
* Train weight/length come from locomotive configuration (the assigned set, or
* the strongest in-service locomotive when none is assigned yet); per-box
* container ceilings come from the rule engine's weight limit rules. Only the
* 20ft pair-imbalance tolerance is a static default.
*/
const DEFAULT_20FT_PAIR_WEIGHT_DIFF_TONS = 10;
/** Raw row shape for the booking-window queries (company- and contract-scoped). */
interface BookingWindowRow {
@@ -447,11 +439,9 @@ export class TrainSchedulingService {
// Per-wagon history ledger (global module). @Optional keeps the positional
// spec constructors working; production always has it.
@Optional() private readonly wagonHistory?: WagonHistoryService,
// Trailing + @Optional so the positional constructors in the existing specs
// keep working; production always resolves it from ExportsModule.
@Optional() private readonly tabularExport?: TabularExportService,
// Crew composition gate (ITLMS Rolling Stock §1.2 "prior to departure").
// Trailing + @Optional for the same positional-spec reason as above.
// Trailing + @Optional so the positional constructors in the existing specs
// keep working; production always resolves it.
@Optional() private readonly trainCrewAssignments?: TrainCrewAssignmentService,
) {}
@@ -813,9 +803,9 @@ export class TrainSchedulingService {
}
/**
* Train length/weight and 20ft weight caps are engine-internal (wagon
* planning still reads them off the row); they are no longer exposed or
* editable through the global-rules endpoints.
* Train length/weight and the 20ft weight cap columns are legacy: planning
* now takes weight/length from locomotive configuration and per-box ceilings
* from weight limit rules. They are neither read nor exposed here.
*/
private toPublicGlobalRules(row: TrainSchedulingGlobalRules | null) {
if (!row) return row;
@@ -3779,15 +3769,15 @@ export class TrainSchedulingService {
}
/**
* The schedule detail page's wagon-list Excel export.
*
* One row per container (a wagon carrying two boxes yields two rows, repeating
* the wagon number) so each container's own VGM is present and totals footable.
* Bulk wagons, having no containers, yield a single row carrying the bulk
* description and the allocated tonnage as the VGM figure.
* The schedule detail page's wagon-list Excel export, laid out like the
* wagon sheet the yard circulates by hand: containers grouped by customer,
* one line per container (a two-box wagon repeats its wagon number under one
* "No."), a blank line between customers, and the wagon count / company /
* transitor merged down each group. See buildWagonListWorkbook.
*
* Only wagon slots that actually carry an allocation are listed — empty slots
* on the consist are omitted.
* on the consist are omitted. A bulk wagon yields one line carrying the cargo
* description in place of a container number.
*/
async scheduleWagonListWorkbook(
scheduleId: string,
@@ -3796,56 +3786,37 @@ export class TrainSchedulingService {
if (!schedule) {
throw new NotFoundException(`Train schedule ${scheduleId} not found`);
}
if (!this.tabularExport) {
throw new BadRequestException('Tabular export service is unavailable');
}
// Row grain is the container item; the LEFT JOIN keeps bulk (and any
// container-less) allocation as one row. `booking_container_units` is joined
// on BOTH container number and its booking_container line — container
// numbers repeat across bookings, so number alone would multiply rows.
const rows: ScheduleWagonListRow[] = await this.dataSource.query(
// Row grain is the container item; the LEFT JOIN keeps a bulk (or any
// container-less) allocation as one row. The transitor is the customs
// clearing agent the customer named on the booking.
const lines: WagonListLine[] = await this.dataSource.query(
`SELECT tsw.sequence_no AS "sequenceNo",
w.wagon_number AS "wagonNumber",
COALESCE(wt.name, wt.code) AS "wagonType",
ci.container_number AS "containerNumber",
cit.size_ft AS "containerSizeFt",
a.load_type AS "loadType",
a.status AS "status",
bl.cargo_description AS "bulkCargoDescription",
COALESCE(
ci.gross_weight_tons,
bcu.vgm_tons,
bc.vgm_per_unit_tons,
a.allocated_weight_tons
) AS "vgmTons",
COALESCE(by_.label, so.label) AS "originLabel",
COALESCE(ay.label, sd.label) AS "destinationLabel",
b.reference AS "bookingReference",
COALESCE(
slc.name,
CASE WHEN b.is_government THEN NULLIF(TRIM(b.government_institution), '') END,
c.name
) AS "customerName"
) AS "customerName",
NULLIF(TRIM(b.customs_clearing_agent), '') AS "transitor"
FROM freight.train_schedules s
JOIN freight.train_set_wagons tsw
ON tsw.train_set_id = s.train_set_id AND tsw.deleted_at IS NULL
JOIN freight.wagon_booking_allocations a
ON a.train_set_wagon_id = tsw.id AND a.deleted_at IS NULL
LEFT JOIN freight.wagons w ON w.id = tsw.physical_wagon_id
LEFT JOIN freight.wagon_types wt ON wt.id = tsw.wagon_type_id
LEFT JOIN freight.bookings b ON b.id = a.booking_id
LEFT JOIN freight.companies c ON c.id = b.company_id
LEFT JOIN freight.shipping_line_companies slc ON slc.id = b.shipping_line_company_id
LEFT JOIN freight.wagon_allocation_container_items ci
ON ci.wagon_booking_allocation_id = a.id AND ci.deleted_at IS NULL
LEFT JOIN freight.container_types cit ON cit.id = ci.container_type_id
LEFT JOIN freight.booking_container bc
ON bc.id = ci.booking_container_id AND bc.deleted_at IS NULL
LEFT JOIN freight.booking_container_units bcu
ON bcu.container_number = ci.container_number
AND bcu.booking_container_id = bc.id
AND bcu.deleted_at IS NULL
LEFT JOIN freight.wagon_allocation_bulk_loads bl
ON bl.wagon_booking_allocation_id = a.id AND bl.deleted_at IS NULL
LEFT JOIN freight.yards so ON so.id = s.origin_station_id
@@ -3857,47 +3828,13 @@ export class TrainSchedulingService {
[scheduleId],
);
// "number" is the printed line number of the sheet, not the wagon sequence —
// a two-container wagon occupies two lines, and the reader counts lines.
const sheetRows = rows.map((row, index) => ({
number: index + 1,
wagonNumber: row.wagonNumber ?? '—',
containerNumber:
row.containerNumber ??
(row.loadType === 'BULK' ? (row.bulkCargoDescription ?? 'Bulk') : '—'),
vgmTons: row.vgmTons === null ? null : Number(row.vgmTons),
originLabel: row.originLabel ?? '—',
destinationLabel: row.destinationLabel ?? '—',
customerName: row.customerName ?? '—',
}));
const totalVgm = sheetRows.reduce((sum, r) => sum + (r.vgmTons ?? 0), 0);
const reference = schedule.reference ?? schedule.trainNumber ?? schedule.id;
const buffer = await this.tabularExport.toXlsx({
title: `Wagons ${reference}`.slice(0, 31),
description: `Wagon list for train ${reference}`,
label: 'train-schedule:wagon-list',
kpis: [
{ label: 'Lines', value: sheetRows.length },
{
label: 'Wagons',
value: new Set(rows.map((r) => r.sequenceNo)).size,
},
{ label: 'Total VGM', value: Number(totalVgm.toFixed(3)), unit: 't' },
],
columns: [
{ key: 'number', label: 'No.', type: 'number' },
{ key: 'wagonNumber', label: 'Wagon', type: 'string' },
{ key: 'containerNumber', label: 'Container number', type: 'string' },
{ key: 'vgmTons', label: 'VGM', type: 'tons' },
{ key: 'originLabel', label: 'Origin', type: 'string' },
{ key: 'destinationLabel', label: 'Destination', type: 'string' },
{ key: 'customerName', label: 'Customer', type: 'string' },
],
rows: sheetRows,
const { groups, totalWagons } = groupWagonListLines(lines);
const buffer = await buildWagonListWorkbook({
trainLabel: schedule.trainNumber ?? schedule.reference ?? schedule.id,
groups,
totalWagons,
});
const reference = schedule.reference ?? schedule.trainNumber ?? schedule.id;
return {
filename: `wagon-list-${this.safeDocumentName(reference)}.xlsx`,
buffer,
@@ -6717,11 +6654,6 @@ export class TrainSchedulingService {
)),
);
const placementRules = {
max20ftContainerWeightTons: trainLimits.max20ftContainerWeightTons,
max20ftPairWeightDiffTons: trainLimits.max20ftPairWeightDiffTons,
};
// With forceAssign, capacity-shaped rules (train limits, total weight,
// locomotive capability) become warnings — staff owns the override. Physical
// impossibilities (no wagon of the required type at the yard, wrong route,
@@ -6754,6 +6686,11 @@ export class TrainSchedulingService {
);
if (requireContainerPlacements && resolvedMode !== 'BULK') {
const containerBookings = fittingBookings.filter((b) => b.freightType === 'CONTAINER');
const placementRules: ContainerPlacementRules = {
maxContainerWeightTonsByLineId:
await this.containerCapacityCeilingsByLine(containerBookings),
max20ftPairWeightDiffTons: trainLimits.max20ftPairWeightDiffTons,
};
violations.push(
...validateContainerPlacements(
containerBookings,
@@ -6901,6 +6838,70 @@ export class TrainSchedulingService {
}
}
/**
* Hard per-box ceiling for every container line of the given bookings, from
* the rule engine's weight limit rule (`max_capacity_tons`) matching the
* line's container type and the booking's trade direction (a `BOTH` rule
* applies to either direction; an exact-direction rule wins over it). Lines
* whose rule has no capacity set get no entry — capacity is optional.
*/
private async containerCapacityCeilingsByLine(
bookings: Booking[],
): Promise<Record<string, number>> {
const lines: Array<{ lineId: string; containerTypeId: string; tradeDirection: string }> = [];
for (const booking of bookings) {
const direction = String(booking.tradeDirection ?? '').toUpperCase();
for (const line of booking.bookingContainers ?? []) {
if (!line.containerTypeId) continue;
lines.push({ lineId: line.id, containerTypeId: line.containerTypeId, tradeDirection: direction });
}
}
if (!lines.length) return {};
const typeIds = [...new Set(lines.map((l) => l.containerTypeId))];
const rules = await this.dataSource
.getRepository(WeightLimitRule)
.find({ where: { containerTypeId: In(typeIds) } });
const ceilings: Record<string, number> = {};
for (const { lineId, containerTypeId, tradeDirection } of lines) {
const candidates = rules.filter(
(r) => r.containerTypeId === containerTypeId && r.maxCapacityTons != null,
);
const rule =
candidates.find((r) => r.tradeDirection === tradeDirection) ??
candidates.find((r) => r.tradeDirection === 'BOTH');
const cap = Number(rule?.maxCapacityTons);
if (Number.isFinite(cap) && cap > 0) ceilings[lineId] = cap;
}
return ceilings;
}
/**
* Limits for a train that has no locomotive assigned yet: the strongest
* in-service locomotive on each axis, so planning assumes the most capable
* power that could be coupled. Null when no locomotive is configured at all.
*/
private async strongestFleetLocomotiveLimits(): Promise<LocomotiveLimits | null> {
const fleet = await this.locomotivesRepository.findAll({
where: { status: Not('OUT_OF_SERVICE' as Locomotive['status']) },
});
const pulls = fleet.map((l) => Number(l.maxPullWeightTons)).filter((v) => v > 0);
const lengths = fleet.map((l) => Number(l.maxTrainLengthMeters)).filter((v) => v > 0);
if (!pulls.length && !lengths.length) return null;
const strongest = (axis: number[], pick: (l: Locomotive) => number) =>
fleet.find((l) => pick(l) === Math.max(...axis));
return {
maxPullWeightTons: pulls.length ? Math.max(...pulls) : Infinity,
maxTrainLengthMeters: lengths.length ? Math.max(...lengths) : Infinity,
overageToleranceTons:
Number(strongest(pulls, (l) => Number(l.maxPullWeightTons))?.overageToleranceTons) || 0,
overageToleranceMeters:
Number(strongest(lengths, (l) => Number(l.maxTrainLengthMeters))?.overageToleranceMeters) ||
0,
};
}
private async resolveTrainLimitConfig(
dto?: {
maxTrainWeightTons?: number;
@@ -6911,24 +6912,14 @@ export class TrainSchedulingService {
builtWagonCount?: number,
): Promise<Required<TrainLimitConfig>> {
const row = await this.loadGlobalRulesRow();
const configured = this.configService?.get<{
maxTrainWeightTons?: number;
maxTrainLengthMeters?: number;
maxWagonsPerTrain?: number;
}>('app.trainScheduling');
const ruleWeightCap =
dto?.maxTrainWeightTons ??
(row?.maxTrainWeightTons != null
? Number(row.maxTrainWeightTons)
: configured?.maxTrainWeightTons);
const ruleLengthCap =
dto?.maxTrainLengthMeters ??
(row?.maxTrainLengthMeters != null
? Number(row.maxTrainLengthMeters)
: configured?.maxTrainLengthMeters);
const configured = this.configService?.get<{ maxWagonsPerTrain?: number }>(
'app.trainScheduling',
);
const wagonTypes = await this.loadSchedulingWagonTypeDimensions();
const max20ftPairWeightDiffTons = this.positiveNumber(
undefined,
Number(row?.max20ftPairWeightDiffTons) || DEFAULT_20FT_PAIR_WEIGHT_DIFF_TONS,
);
if (locomotive) {
// With a locomotive assigned its own limits are the single source of
@@ -6963,52 +6954,40 @@ export class TrainSchedulingService {
: builtWagonCount && builtWagonCount > 0
? builtWagonCount
: derived.maxWagonSlots,
max20ftContainerWeightTons: this.positiveNumber(
undefined,
Number(row?.max20ftContainerWeightTons) ||
DEFAULT_TRAIN_LIMITS.max20ftContainerWeightTons,
),
max20ftPairWeightDiffTons: this.positiveNumber(
undefined,
Number(row?.max20ftPairWeightDiffTons) ||
DEFAULT_TRAIN_LIMITS.max20ftPairWeightDiffTons,
),
max20ftPairWeightDiffTons,
};
}
const maxWeightTons = this.positiveNumber(
dto?.maxTrainWeightTons,
ruleWeightCap ?? DEFAULT_TRAIN_LIMITS.maxWeightTons,
);
const maxLengthMeters = this.positiveNumber(
dto?.maxTrainLengthMeters,
ruleLengthCap ?? DEFAULT_TRAIN_LIMITS.maxLengthMeters,
);
const derivedWithoutLoco = deriveTrainCapacityFromLocomotive(
{ maxPullWeightTons: maxWeightTons, maxTrainLengthMeters: maxLengthMeters },
// No locomotive on the set yet: plan against the strongest in-service
// locomotive's configuration. An explicit dto override still narrows it.
const fleet = await this.strongestFleetLocomotiveLimits();
if (!fleet) {
this.logger.warn(
'No in-service locomotive is configured — train weight/length limits fall back to ' +
`${MAX_FALLBACK_WEIGHT}T / ${MAX_FALLBACK_LENGTH}m until a locomotive is added`,
);
}
const derived = deriveTrainCapacityFromLocomotive(
fleet ?? { maxPullWeightTons: MAX_FALLBACK_WEIGHT, maxTrainLengthMeters: MAX_FALLBACK_LENGTH },
wagonTypes,
{
maxTrainWeightTons: dto?.maxTrainWeightTons,
maxTrainLengthMeters: dto?.maxTrainLengthMeters,
},
);
return {
maxWeightTons,
maxLengthMeters,
maxWeightTons: derived.maxWeightTons,
maxLengthMeters: derived.maxLengthMeters,
maxWagonsPerTrain: Math.floor(
this.positiveNumber(
dto?.maxWagonsPerTrain,
row?.maxWagonsPerTrain != null
? Number(row.maxWagonsPerTrain)
: configured?.maxWagonsPerTrain ?? derivedWithoutLoco.maxWagonSlots,
: configured?.maxWagonsPerTrain ?? derived.maxWagonSlots,
),
),
max20ftContainerWeightTons: this.positiveNumber(
undefined,
Number(row?.max20ftContainerWeightTons) || DEFAULT_TRAIN_LIMITS.max20ftContainerWeightTons,
),
max20ftPairWeightDiffTons: this.positiveNumber(
undefined,
Number(row?.max20ftPairWeightDiffTons) ||
DEFAULT_TRAIN_LIMITS.max20ftPairWeightDiffTons,
),
max20ftPairWeightDiffTons,
};
}