Refactor wagon specifications to rely on wagon type; remove tare weight and max payload from wagon entity and related components

This commit is contained in:
Marshal
2026-07-09 07:42:02 +00:00
parent cd8fb2b321
commit 61ec67cc2e
13 changed files with 99 additions and 50 deletions

View File

@@ -0,0 +1,53 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
/**
* Wagon spec belongs to the wagon TYPE, not to each physical wagon.
*
* `wagons.tare_weight` and `wagons.max_payload_weight` duplicated
* `wagon_types.tare_weight_tons` / `wagon_types.capacity_tons` on all 1100 rows,
* with nothing keeping them in step. They had drifted completely: every wagon
* disagreed with its type's tare (seeded ~20T against a real 22.4T NW5), and a
* third disagreed on payload (NW5 wagons claiming 22T70T against a flat 70T).
* None of those numbers came from the railway.
*
* Nothing reads them for capacity — that math resolves tare and capacity through
* `wagon_type_id` — so dropping them removes a source of fiction rather than a
* source of truth. `wagon_type_id` is NOT NULL with no orphans, so the type is
* always reachable.
*
* A wagon re-tared after repair would need a nullable override column on
* `wagons` falling back to the type; deliberately not added, since no such
* per-wagon value exists today.
*/
export class DropWagonSpecColumns2080000000000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE freight.wagons
DROP COLUMN IF EXISTS tare_weight,
DROP COLUMN IF EXISTS max_payload_weight;
`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
// Re-add nullable, backfill from the owning type, then restore NOT NULL.
// The pre-drop values were drifted seed data and are not recoverable — the
// type's spec is what they should always have held.
await queryRunner.query(`
ALTER TABLE freight.wagons
ADD COLUMN IF NOT EXISTS tare_weight NUMERIC(10, 2),
ADD COLUMN IF NOT EXISTS max_payload_weight NUMERIC(10, 2);
`);
await queryRunner.query(`
UPDATE freight.wagons w
SET tare_weight = t.tare_weight_tons,
max_payload_weight = t.capacity_tons
FROM freight.wagon_types t
WHERE t.id = w.wagon_type_id;
`);
await queryRunner.query(`
ALTER TABLE freight.wagons
ALTER COLUMN tare_weight SET NOT NULL,
ALTER COLUMN max_payload_weight SET NOT NULL;
`);
}
}

View File

@@ -1900,7 +1900,7 @@ export class TrainSchedulingService {
<td>${esc(wagon.physicalWagon?.wagonNumber)}</td> <td>${esc(wagon.physicalWagon?.wagonNumber)}</td>
<td>${esc(wagon.wagonType?.code ?? wagon.wagonType?.name)}</td> <td>${esc(wagon.wagonType?.code ?? wagon.wagonType?.name)}</td>
<td class="num">${esc(Number(wagon.lengthMeters || 0).toFixed(3))}</td> <td class="num">${esc(Number(wagon.lengthMeters || 0).toFixed(3))}</td>
<td class="num">${esc(Number(wagon.physicalWagon?.tareWeight ?? 0).toFixed(2))}</td> <td class="num">${esc(Number(wagon.wagonType?.tareWeightTons ?? 0).toFixed(2))}</td>
<td class="num">${esc(Number(wagon.capacityTons || 0).toFixed(3))}</td> <td class="num">${esc(Number(wagon.capacityTons || 0).toFixed(3))}</td>
<td>${esc(company?.name ?? company?.legalName ?? company?.tradeName ?? booking?.companyId)}</td> <td>${esc(company?.name ?? company?.legalName ?? company?.tradeName ?? booking?.companyId)}</td>
<td>${esc(booking?.companyId)}</td> <td>${esc(booking?.companyId)}</td>

View File

@@ -1,5 +1,5 @@
import { WagonStatus } from '@edr/types'; import { WagonStatus } from '@edr/types';
import { IsString, IsUUID, IsOptional, IsInt, Min, IsNumber, IsEnum } from 'class-validator'; import { IsString, IsUUID, IsOptional, IsInt, Min, IsEnum } from 'class-validator';
export class CreateWagonDto { export class CreateWagonDto {
@IsString() @IsString()
@@ -17,13 +17,8 @@ export class CreateWagonDto {
@Min(1) @Min(1)
sequenceNumber?: number; sequenceNumber?: number;
@IsNumber() // Tare weight and payload capacity are not accepted here: they belong to the
@Min(0) // wagon type and are resolved through wagonTypeId.
tareWeight!: number;
@IsNumber()
@Min(0)
maxPayloadWeight!: number;
@IsOptional() @IsOptional()
@IsEnum(WagonStatus) @IsEnum(WagonStatus)

View File

@@ -7,6 +7,7 @@ import { TrainSchedule } from '../../train-schedules/entities/train-schedule.ent
import { TrainSetWagon } from '../../train-sets/entities/train-set-wagon.entity'; import { TrainSetWagon } from '../../train-sets/entities/train-set-wagon.entity';
import { Container } from '../../container-management/entities/container.entity'; import { Container } from '../../container-management/entities/container.entity';
import { Yard } from '../../rule-engine/entities/yard.entity'; import { Yard } from '../../rule-engine/entities/yard.entity';
import { WagonType } from '../../wagon-types/entities/wagon-type.entity';
export const WAGON_STATUSES = [ export const WAGON_STATUSES = [
WagonStatus.Available, WagonStatus.Available,
@@ -28,17 +29,19 @@ export class Wagon extends BaseEntity {
@Column({ name: 'wagon_type_id', type: 'uuid' }) @Column({ name: 'wagon_type_id', type: 'uuid' })
wagonTypeId!: string; wagonTypeId!: string;
/** Owns this wagon's spec: tare weight, payload capacity, length. */
@ManyToOne(() => WagonType)
@JoinColumn({ name: 'wagon_type_id' })
wagonType?: WagonType;
@Column({ name: 'train_id', type: 'uuid', nullable: true }) @Column({ name: 'train_id', type: 'uuid', nullable: true })
trainId!: string | null; trainId!: string | null;
@Column({ name: 'sequence_number', type: 'int', nullable: true }) @Column({ name: 'sequence_number', type: 'int', nullable: true })
sequenceNumber!: number | null; sequenceNumber!: number | null;
@Column({ name: 'tare_weight', type: 'decimal', precision: 10, scale: 2 }) // Tare weight and payload capacity are properties of the wagon TYPE — read them
tareWeight!: number; // through `wagonType`, never off the individual wagon.
@Column({ name: 'max_payload_weight', type: 'decimal', precision: 10, scale: 2 })
maxPayloadWeight!: number;
@Column({ type: 'varchar', length: 20, default: WagonStatus.Available }) @Column({ type: 'varchar', length: 20, default: WagonStatus.Available })
status!: WagonStatusType; status!: WagonStatusType;

View File

@@ -52,14 +52,23 @@ export class WagonsService {
}); });
} }
const sortBy = ['wagonNumber', 'tareWeight', 'maxPayloadWeight', 'status', 'currentYardId', 'sequenceNumber'].includes(query.sortBy ?? '') // Spec columns (tare, payload) are no longer sortable here — they live on the
// wagon type, so sorting by them is sorting by wagonTypeId.
const sortable: Array<keyof Wagon> = [
'wagonNumber',
'status',
'currentYardId',
'sequenceNumber',
'wagonTypeId',
];
const sortBy = sortable.includes((query.sortBy ?? '') as keyof Wagon)
? (query.sortBy as keyof Wagon) ? (query.sortBy as keyof Wagon)
: 'wagonNumber'; : 'wagonNumber';
const sortOrder = query.sortOrder?.toUpperCase() === 'DESC' ? 'DESC' : 'ASC'; const sortOrder = query.sortOrder?.toUpperCase() === 'DESC' ? 'DESC' : 'ASC';
return this.wagonRepo.find({ return this.wagonRepo.find({
where: search ? where : filters, where: search ? where : filters,
relations: { currentYard: true }, relations: { currentYard: true, wagonType: true },
order: { [sortBy]: sortOrder } as FindOptionsOrder<Wagon>, order: { [sortBy]: sortOrder } as FindOptionsOrder<Wagon>,
skip: query.page && query.limit ? (Number(query.page) - 1) * Number(query.limit) : undefined, skip: query.page && query.limit ? (Number(query.page) - 1) * Number(query.limit) : undefined,
take: query.limit ? Number(query.limit) : undefined, take: query.limit ? Number(query.limit) : undefined,
@@ -69,7 +78,7 @@ export class WagonsService {
async findById(id: string): Promise<Wagon> { async findById(id: string): Promise<Wagon> {
const wagon = await this.wagonRepo.findOne({ const wagon = await this.wagonRepo.findOne({
where: { id }, where: { id },
relations: { currentYard: true }, relations: { currentYard: true, wagonType: true },
}); });
if (!wagon) throw new NotFoundException(`Wagon ${id} not found`); if (!wagon) throw new NotFoundException(`Wagon ${id} not found`);
return wagon; return wagon;

View File

@@ -419,8 +419,6 @@ async function ensureWagon(manager: any, scenario: ScenarioTrain, sequenceNo: nu
wagonTypeId, wagonTypeId,
trainId: null, trainId: null,
sequenceNumber: sequenceNo, sequenceNumber: sequenceNo,
tareWeight: 20,
maxPayloadWeight: 70,
status: WagonStatus.Assigned, status: WagonStatus.Assigned,
currentYardId: yardId, currentYardId: yardId,
currentTrainScheduleId: scheduleId, currentTrainScheduleId: scheduleId,

View File

@@ -306,8 +306,6 @@ async function main() {
wagonTypeId: wagonType.id, wagonTypeId: wagonType.id,
trainId: null, trainId: null,
sequenceNumber: sequenceNo, sequenceNumber: sequenceNo,
tareWeight: 20,
maxPayloadWeight: 70,
status: WagonStatus.Assigned, status: WagonStatus.Assigned,
currentYardId: indode.id, currentYardId: indode.id,
notes: 'Demo wagon for Negad to Indode marshalling', notes: 'Demo wagon for Negad to Indode marshalling',

View File

@@ -504,8 +504,6 @@ export class DemoBookingsSeeder {
wagonTypeId: nw5.id, wagonTypeId: nw5.id,
trainId: null, trainId: null,
sequenceNumber: null, sequenceNumber: null,
tareWeight: 20,
maxPayloadWeight: 70,
status: WagonStatus.Available, status: WagonStatus.Available,
currentYardId: index % 2 === 0 ? djibouti.id : addis.id, currentYardId: index % 2 === 0 ? djibouti.id : addis.id,
notes: "Demo wagon for train scheduling", notes: "Demo wagon for train scheduling",

View File

@@ -76,15 +76,11 @@ export class DemoFreightDataSeeder {
} }
const toCreate = MIN_WAGONS_PER_TYPE - existing; const toCreate = MIN_WAGONS_PER_TYPE - existing;
const tare = Number(type.tareWeightTons ?? 20);
const maxPayload = Number(type.capacityTons ?? 60);
const rows = Array.from({ length: toCreate }, (_, i) => { const rows = Array.from({ length: toCreate }, (_, i) => {
const seq = existing + i + 1; const seq = existing + i + 1;
return wagonRepo.create({ return wagonRepo.create({
wagonNumber: `${type.code}-${String(seq).padStart(4, '0')}`, wagonNumber: `${type.code}-${String(seq).padStart(4, '0')}`,
wagonTypeId: type.id, wagonTypeId: type.id,
tareWeight: tare,
maxPayloadWeight: maxPayload,
status: WagonStatus.Available, status: WagonStatus.Available,
}); });
}); });

View File

@@ -203,7 +203,6 @@ export class MarshallingDemoTrainsSeeder {
const totalWeight = bookingWeights.reduce((sum, weight) => sum + weight, 0); const totalWeight = bookingWeights.reduce((sum, weight) => sum + weight, 0);
const wagonCapacity = Number(refs.wagonType.capacityTons) || 70; const wagonCapacity = Number(refs.wagonType.capacityTons) || 70;
const wagonLength = Number(refs.wagonType.lengthMeters) || 14; const wagonLength = Number(refs.wagonType.lengthMeters) || 14;
const tareWeight = Number(refs.wagonType.tareWeightTons) || 14;
const trainSet = await trainSetRepo.save( const trainSet = await trainSetRepo.save(
trainSetRepo.create({ trainSetRepo.create({
@@ -275,8 +274,6 @@ export class MarshallingDemoTrainsSeeder {
wagonTypeId: refs.wagonType.id, wagonTypeId: refs.wagonType.id,
yardId: originYard.id, yardId: originYard.id,
trainScheduleId: schedule.id, trainScheduleId: schedule.id,
tareWeight,
capacityTons: wagonCapacity,
dispatched: hasDeparted, dispatched: hasDeparted,
}); });
@@ -420,8 +417,6 @@ export class MarshallingDemoTrainsSeeder {
wagonTypeId: string; wagonTypeId: string;
yardId: string; yardId: string;
trainScheduleId: string; trainScheduleId: string;
tareWeight: number;
capacityTons: number;
dispatched: boolean; dispatched: boolean;
}): Promise<Wagon> { }): Promise<Wagon> {
const repo = this.dataSource.getRepository(Wagon); const repo = this.dataSource.getRepository(Wagon);
@@ -433,8 +428,6 @@ export class MarshallingDemoTrainsSeeder {
wagonTypeId: input.wagonTypeId, wagonTypeId: input.wagonTypeId,
currentYardId: input.yardId, currentYardId: input.yardId,
currentTrainScheduleId: input.trainScheduleId, currentTrainScheduleId: input.trainScheduleId,
tareWeight: input.tareWeight,
maxPayloadWeight: input.capacityTons,
status: WagonStatus.Assigned, status: WagonStatus.Assigned,
notes: 'Marshalling demo seed wagon', notes: 'Marshalling demo seed wagon',
}), }),

View File

@@ -107,6 +107,10 @@ const normalizePayload = (values: Record<string, FormValue>) =>
.filter(([, value]) => value !== '' && !(Array.isArray(value) && value.length === 0)), .filter(([, value]) => value !== '' && !(Array.isArray(value) && value.length === 0)),
); );
/** Render a spec value inherited from the wagon type; em dash when the type isn't loaded. */
const fmtTypeSpec = (value: number | undefined | null, unit: string) =>
value == null ? '—' : `${Number(value)} ${unit}`;
const extractBackendErrors = (error: unknown) => { const extractBackendErrors = (error: unknown) => {
const responseData = (error as { response?: { data?: unknown } })?.response?.data; const responseData = (error as { response?: { data?: unknown } })?.response?.data;
const data = responseData && typeof responseData === 'object' ? responseData as Record<string, unknown> : undefined; const data = responseData && typeof responseData === 'object' ? responseData as Record<string, unknown> : undefined;
@@ -922,7 +926,17 @@ export function WagonsCrudPage() {
? `${wagon.currentLocationYard.label ?? wagon.currentLocationYard.code} (${wagon.currentLocationYard.country ?? '-'})` ? `${wagon.currentLocationYard.label ?? wagon.currentLocationYard.code} (${wagon.currentLocationYard.country ?? '-'})`
: '-', : '-',
}, },
{ key: 'maxPayloadWeight', label: 'Max payload' }, {
// Read-only: the spec lives on the wagon type, so it is displayed, never edited here.
key: 'tareWeight',
label: 'Tare weight',
render: (wagon) => fmtTypeSpec(wagon.wagonType?.tareWeightTons, 't'),
},
{
key: 'maxPayloadWeight',
label: 'Max payload',
render: (wagon) => fmtTypeSpec(wagon.wagonType?.capacityTons, 't'),
},
{ key: 'status', label: 'Status', render: (wagon) => statusBadge(wagon.status) }, { key: 'status', label: 'Status', render: (wagon) => statusBadge(wagon.status) },
]} ]}
fields={[ fields={[
@@ -933,11 +947,6 @@ export function WagonsCrudPage() {
type: 'select', type: 'select',
required: true, required: true,
options: wagonTypeOptions, options: wagonTypeOptions,
onValueChange: (value, current) => {
const selectedType = wagonTypes.find((type: any) => type.id === value);
if (!selectedType || Number(current.maxPayloadWeight) > 0) return {};
return { maxPayloadWeight: Number(selectedType.capacityTons) };
},
}, },
{ {
key: 'currentLocationYardId', key: 'currentLocationYardId',
@@ -946,8 +955,6 @@ export function WagonsCrudPage() {
required: true, required: true,
options: yardOptions, options: yardOptions,
}, },
{ key: 'tareWeight', label: 'Tare weight', type: 'number', required: true },
{ key: 'maxPayloadWeight', label: 'Max payload weight', type: 'number', required: true },
{ {
key: 'status', key: 'status',
label: 'Status', label: 'Status',
@@ -963,7 +970,7 @@ export function WagonsCrudPage() {
}, },
{ key: 'notes', label: 'Notes' }, { key: 'notes', label: 'Notes' },
]} ]}
emptyValues={{ wagonNumber: '', wagonTypeId: '', currentLocationYardId: '', tareWeight: 0, maxPayloadWeight: 0, status: 'AVAILABLE', notes: '' }} emptyValues={{ wagonNumber: '', wagonTypeId: '', currentLocationYardId: '', status: 'AVAILABLE', notes: '' }}
/> />
); );
} }

View File

@@ -263,17 +263,16 @@ export const FLEET_RESOURCES: FleetResourceConfig[] = [
cardSubtitleKey: "currentYard", cardSubtitleKey: "currentYard",
searchKeys: ["wagonNumber", "wagonTypeId", "trainId", "status", "currentYardId"], searchKeys: ["wagonNumber", "wagonTypeId", "trainId", "status", "currentYardId"],
columns: [ columns: [
// Tare weight and payload capacity are not wagon columns — they belong to the
// wagon type and are shown through it (see WagonsCrudPage in FleetCrudPages).
{ id: "wagonNumber", header: "Number", accessorKey: "wagonNumber", format: "code" }, { id: "wagonNumber", header: "Number", accessorKey: "wagonNumber", format: "code" },
{ id: "wagonTypeId", header: "Type", accessorKey: "wagonTypeId", format: "entityLabel" }, { id: "wagonTypeId", header: "Type", accessorKey: "wagonTypeId", format: "entityLabel" },
{ id: "maxPayloadWeight", header: "Max payload", accessorKey: "maxPayloadWeight", format: "number" },
{ id: "currentYard", header: "Current Yard", accessorKey: "currentYard", format: "entityLabel" }, { id: "currentYard", header: "Current Yard", accessorKey: "currentYard", format: "entityLabel" },
{ id: "status", header: "Status", accessorKey: "status", format: "statusBadge" }, { id: "status", header: "Status", accessorKey: "status", format: "statusBadge" },
], ],
formFields: [ formFields: [
{ name: "wagonNumber", label: "Wagon number", type: "text", required: true }, { name: "wagonNumber", label: "Wagon number", type: "text", required: true },
{ name: "wagonTypeId", label: "Wagon type", type: "select", required: true, dynamicOptions: "wagonTypes" }, { name: "wagonTypeId", label: "Wagon type", type: "select", required: true, dynamicOptions: "wagonTypes" },
{ name: "tareWeight", label: "Tare weight", type: "number", required: true },
{ name: "maxPayloadWeight", label: "Max payload weight", type: "number", required: true },
{ name: "currentYardId", label: "Current Yard", type: "select", dynamicOptions: "yards" }, { name: "currentYardId", label: "Current Yard", type: "select", dynamicOptions: "yards" },
{ name: "status", label: "Status", type: "select", required: true, options: WAGON_STATUS_OPTIONS }, { name: "status", label: "Status", type: "select", required: true, options: WAGON_STATUS_OPTIONS },
{ name: "notes", label: "Notes", type: "textarea" }, { name: "notes", label: "Notes", type: "textarea" },
@@ -281,8 +280,6 @@ export const FLEET_RESOURCES: FleetResourceConfig[] = [
emptyValues: { emptyValues: {
wagonNumber: "", wagonNumber: "",
wagonTypeId: "", wagonTypeId: "",
tareWeight: 0,
maxPayloadWeight: 0,
currentYardId: "", currentYardId: "",
status: Freight.WagonStatus.Available, status: Freight.WagonStatus.Available,
notes: "", notes: "",

View File

@@ -15,14 +15,16 @@ export interface Wagon {
label: string; label: string;
country?: string; country?: string;
} | null; } | null;
/** Owns this wagon's spec — tare, capacity, length are read from here, never off the wagon. */
wagonType?: { wagonType?: {
id: string; id: string;
code: string; code: string;
name: string; name: string;
supportedLoadTypes?: string[]; supportedLoadTypes?: string[];
tareWeightTons?: number;
capacityTons?: number;
lengthMeters?: number;
} | null; } | null;
tareWeight: number;
maxPayloadWeight: number;
status: Freight.WagonStatus; status: Freight.WagonStatus;
currentYardId: string | null; currentYardId: string | null;
currentYard?: { id: string; label?: string; code?: string } | null; currentYard?: { id: string; label?: string; code?: string } | null;