mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-29 21:08:12 +00:00
feat: full wagon cancel, leg board, wagon dates
feat(freight): editable train leg times, SL invoice payer
This commit is contained in:
@@ -174,7 +174,11 @@ import {
|
||||
import { TrainCheckpointEvent } from '../entities/train-checkpoint-event.entity';
|
||||
import { BookingJourneyService } from '../booking-journey.service';
|
||||
import { TrainCheckpointEventsRepository } from '../repositories/train-checkpoint-events.repository';
|
||||
import { RecordCheckpointDto } from '../dto/record-checkpoint.dto';
|
||||
import {
|
||||
DispatchScheduleDto,
|
||||
RecordCheckpointDto,
|
||||
UpdateCheckpointDto,
|
||||
} from '../dto/record-checkpoint.dto';
|
||||
import { RouteMilestone } from '../../routes/entities/route-milestone.entity';
|
||||
import { deriveTradeDirection } from '../../../common/derive-trade-direction.util';
|
||||
import { WarehouseInventoryService } from '../../warehouses/warehouse-inventory.service';
|
||||
@@ -2645,7 +2649,7 @@ export class TrainSchedulingService {
|
||||
return this.getTrainScheduleById(scheduleId);
|
||||
}
|
||||
|
||||
async dispatchSchedule(scheduleId: string) {
|
||||
async dispatchSchedule(scheduleId: string, dto: DispatchScheduleDto = {}) {
|
||||
const schedule = await this.trainSchedulesRepository.findByIdWithFullGraph(scheduleId);
|
||||
if (!schedule) {
|
||||
throw new NotFoundException(`Train schedule ${scheduleId} not found`);
|
||||
@@ -2653,6 +2657,9 @@ export class TrainSchedulingService {
|
||||
if (schedule.status !== TrainScheduleStatusEnum.Scheduled) {
|
||||
throw new BadRequestException('Only SCHEDULED trains can be dispatched');
|
||||
}
|
||||
// Staff may record the departure after the fact — past is fine, future is not.
|
||||
const now = dto.actualDepartureAt ? new Date(dto.actualDepartureAt) : new Date();
|
||||
this.assertNotFuture(now, 'Departure time');
|
||||
await this.assertImportDjiboutiMayDepart(schedule);
|
||||
// Cargo readiness (in the warehouse, not inspected, not loaded onto a wagon)
|
||||
// never blocks departure — the dispatch confirm dialog warns and staff decide.
|
||||
@@ -2677,7 +2684,6 @@ export class TrainSchedulingService {
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
await this.dataSource.transaction(async (manager) => {
|
||||
const trainNumber = await this.assignTrainNumber(manager, schedule);
|
||||
if (setLocomotiveIds.length) {
|
||||
@@ -4160,6 +4166,7 @@ export class TrainSchedulingService {
|
||||
? TrainCheckpointKind.Arrived
|
||||
: TrainCheckpointKind.Passed);
|
||||
const occurredAt = dto.occurredAt ? new Date(dto.occurredAt) : new Date();
|
||||
await this.assertCheckpointTime(schedule, stations, dto.sequenceNo, occurredAt);
|
||||
|
||||
// Upsert by (scheduleId, sequenceNo) so re-logging a station updates rather than duplicates.
|
||||
const [existing] = await this.trainCheckpointEventsRepository.findAll({
|
||||
@@ -4183,8 +4190,14 @@ export class TrainSchedulingService {
|
||||
});
|
||||
}
|
||||
|
||||
// The origin DEPARTED checkpoint IS the departure — keep the schedule's
|
||||
// headline timestamp on the same clock the operator just entered.
|
||||
if (dto.sequenceNo === 0) {
|
||||
await this.trainSchedulesRepository.update(scheduleId, { actualDepartureAt: occurredAt });
|
||||
}
|
||||
|
||||
if (dto.sequenceNo === finalSeq) {
|
||||
await this.arriveSchedule(scheduleId);
|
||||
await this.arriveSchedule(scheduleId, occurredAt);
|
||||
} else {
|
||||
// Mid-corridor auto-unload: bookings destined for this yard alight the
|
||||
// moment the train is recorded here — the yard operator no longer has to
|
||||
@@ -4220,11 +4233,133 @@ export class TrainSchedulingService {
|
||||
return this.getScheduleCheckpoints(scheduleId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Correct an already-logged leg's time/note. Pure edit: no auto-unload, no
|
||||
* position fix, no arrival — those already happened when the leg was logged.
|
||||
* Allowed on DISPATCHED and ARRIVED trains (a journey is corrected after the
|
||||
* fact as often as during it). The origin/final legs also re-stamp the
|
||||
* schedule's departure/arrival so the headline figures follow the edit.
|
||||
*/
|
||||
async updateCheckpoint(scheduleId: string, sequenceNo: number, dto: UpdateCheckpointDto) {
|
||||
const schedule = await this.trainSchedulesRepository.findByIdWithFullGraph(scheduleId);
|
||||
if (!schedule) {
|
||||
throw new NotFoundException(`Train schedule ${scheduleId} not found`);
|
||||
}
|
||||
if (
|
||||
schedule.status !== TrainScheduleStatusEnum.Dispatched &&
|
||||
schedule.status !== TrainScheduleStatusEnum.Arrived
|
||||
) {
|
||||
throw new BadRequestException('Only DISPATCHED or ARRIVED trains have checkpoints to edit');
|
||||
}
|
||||
const stations = await this.buildScheduleStations(schedule);
|
||||
const station = stations.find((s) => s.sequenceNo === sequenceNo);
|
||||
if (!station) {
|
||||
throw new BadRequestException(`Station ${sequenceNo} is not on this route`);
|
||||
}
|
||||
// Match by yard, like getScheduleCheckpoints — legacy rows may carry an
|
||||
// older station numbering.
|
||||
const events = await this.trainCheckpointEventsRepository.findBySchedule(scheduleId);
|
||||
const existing =
|
||||
events.find((e) => e.yardId === station.yardId) ??
|
||||
events.find((e) => e.sequenceNo === sequenceNo);
|
||||
if (!existing) {
|
||||
throw new BadRequestException(`Station ${station.label} has not been logged yet`);
|
||||
}
|
||||
|
||||
const patch: Partial<TrainCheckpointEvent> = {};
|
||||
if (dto.occurredAt) {
|
||||
const occurredAt = new Date(dto.occurredAt);
|
||||
await this.assertCheckpointTime(schedule, stations, sequenceNo, occurredAt, existing.id);
|
||||
patch.occurredAt = occurredAt;
|
||||
}
|
||||
if (dto.note !== undefined) patch.note = dto.note;
|
||||
if (Object.keys(patch).length) {
|
||||
await this.trainCheckpointEventsRepository.update(existing.id, patch);
|
||||
}
|
||||
|
||||
if (patch.occurredAt) {
|
||||
const finalSeq = stations[stations.length - 1].sequenceNo;
|
||||
if (sequenceNo === 0) {
|
||||
await this.trainSchedulesRepository.update(scheduleId, {
|
||||
actualDepartureAt: patch.occurredAt,
|
||||
});
|
||||
} else if (sequenceNo === finalSeq && schedule.status === TrainScheduleStatusEnum.Arrived) {
|
||||
await this.trainSchedulesRepository.update(scheduleId, {
|
||||
actualArrivalAt: patch.occurredAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return this.getScheduleCheckpoints(scheduleId);
|
||||
}
|
||||
|
||||
private assertNotFuture(at: Date, what: string) {
|
||||
if (Number.isNaN(at.getTime())) {
|
||||
throw new BadRequestException(`${what} is not a valid date`);
|
||||
}
|
||||
// Small skew allowance so an honest "now" from a client clock passes.
|
||||
if (at.getTime() > Date.now() + 60_000) {
|
||||
throw new BadRequestException(`${what} cannot be in the future`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A leg's time must not be in the future and must sit in corridor order:
|
||||
* no earlier than every logged leg before it (and the dispatch time, for
|
||||
* legs after the origin), no later than every logged leg after it.
|
||||
* `ignoreEventId` excludes the row being edited from its own bounds.
|
||||
*/
|
||||
private async assertCheckpointTime(
|
||||
schedule: TrainSchedule,
|
||||
stations: { sequenceNo: number; yardId: string; label: string }[],
|
||||
sequenceNo: number,
|
||||
occurredAt: Date,
|
||||
ignoreEventId?: string,
|
||||
) {
|
||||
this.assertNotFuture(occurredAt, 'Checkpoint time');
|
||||
|
||||
const seqByYard = new Map(stations.map((s) => [s.yardId, s.sequenceNo]));
|
||||
const labelBySeq = new Map(stations.map((s) => [s.sequenceNo, s.label]));
|
||||
const events = (await this.trainCheckpointEventsRepository.findBySchedule(schedule.id)).filter(
|
||||
(e) => e.id !== ignoreEventId,
|
||||
);
|
||||
const seqOf = (e: TrainCheckpointEvent) => seqByYard.get(e.yardId) ?? e.sequenceNo;
|
||||
const fmt = (d: Date) => d.toISOString().replace('T', ' ').slice(0, 16) + ' UTC';
|
||||
|
||||
let floor: { at: Date; label: string } | null = null;
|
||||
let ceil: { at: Date; label: string } | null = null;
|
||||
for (const e of events) {
|
||||
const s = seqOf(e);
|
||||
if (s < sequenceNo && (!floor || e.occurredAt > floor.at)) {
|
||||
floor = { at: e.occurredAt, label: labelBySeq.get(s) ?? `station ${s}` };
|
||||
}
|
||||
if (s > sequenceNo && (!ceil || e.occurredAt < ceil.at)) {
|
||||
ceil = { at: e.occurredAt, label: labelBySeq.get(s) ?? `station ${s}` };
|
||||
}
|
||||
}
|
||||
// The origin leg rewrites the departure itself; every later leg must
|
||||
// follow it.
|
||||
if (sequenceNo > 0 && schedule.actualDepartureAt && (!floor || schedule.actualDepartureAt > floor.at)) {
|
||||
floor = { at: schedule.actualDepartureAt, label: 'departure' };
|
||||
}
|
||||
|
||||
if (floor && occurredAt < floor.at) {
|
||||
throw new BadRequestException(
|
||||
`Checkpoint time cannot be earlier than ${floor.label} (${fmt(floor.at)})`,
|
||||
);
|
||||
}
|
||||
if (ceil && occurredAt > ceil.at) {
|
||||
throw new BadRequestException(
|
||||
`Checkpoint time cannot be later than ${ceil.label} (${fmt(ceil.at)})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark a dispatched train arrived: close out the schedule, move the locomotive
|
||||
* and wagons to the destination yard, and free the assets for re-use.
|
||||
*/
|
||||
async arriveSchedule(scheduleId: string) {
|
||||
async arriveSchedule(scheduleId: string, arrivedAt?: Date) {
|
||||
const schedule = await this.trainSchedulesRepository.findByIdWithFullGraph(scheduleId);
|
||||
if (!schedule) {
|
||||
throw new NotFoundException(`Train schedule ${scheduleId} not found`);
|
||||
@@ -4233,7 +4368,9 @@ export class TrainSchedulingService {
|
||||
throw new BadRequestException('Only DISPATCHED trains can arrive');
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
// The arrival clock: the operator's entered time when arriving via the final
|
||||
// checkpoint (already order/future-checked there), else now.
|
||||
const now = arrivedAt ?? new Date();
|
||||
|
||||
await this.dataSource.transaction(async (manager) => {
|
||||
await this.trainSchedulesRepository.updateStatus(
|
||||
@@ -9025,33 +9162,88 @@ export class TrainSchedulingService {
|
||||
throw new BadRequestException('Source wagon has no load to move');
|
||||
}
|
||||
|
||||
// Target: a slot of this train set, or an empty consist-only wagon of the
|
||||
// built train (physical wagon with no slot row yet).
|
||||
// Leg spans: a physical wagon carries one slot PER LEG (cross-leg sharing —
|
||||
// Gelan→Adama and Adama→Doraleh loads ride the same wagon in two slots), so
|
||||
// "the slot on that wagon" only means the one whose leg overlaps the moving
|
||||
// load's leg. Null board/alight = the schedule's own endpoints.
|
||||
const stops = await this.stopYardsForSchedule(schedule);
|
||||
const spanOf = (slot: {
|
||||
boardYardId?: string | null;
|
||||
alightYardId?: string | null;
|
||||
}): [number, number] => {
|
||||
const from = slot.boardYardId ? stops.indexOf(slot.boardYardId) : 0;
|
||||
const to = slot.alightYardId ? stops.indexOf(slot.alightYardId) : stops.length - 1;
|
||||
return [from < 0 ? 0 : from, to < 0 ? Math.max(1, stops.length - 1) : to];
|
||||
};
|
||||
const overlaps = (a: [number, number], b: [number, number]) => a[0] < b[1] && b[0] < a[1];
|
||||
const sourceSpan = spanOf(source);
|
||||
|
||||
// Target: a slot of this train set, or a physical wagon of this train —
|
||||
// coupled-but-empty consist wagon (built train), or a wagon already pinned
|
||||
// by another slot of this set (then: the overlapping-leg slot, or a fresh
|
||||
// slot for a free leg).
|
||||
const slotById = slots.find((w) => w.id === dto.targetWagonId) ?? null;
|
||||
const wagonForTarget = slotById
|
||||
? null
|
||||
: schedule.trainSet?.trainId
|
||||
? await this.dataSource.getRepository(Wagon).findOne({
|
||||
where: { id: dto.targetWagonId, trainId: schedule.trainSet.trainId },
|
||||
relations: { wagonType: true },
|
||||
})
|
||||
: null;
|
||||
let wagonForTarget: Wagon | null = null;
|
||||
if (!slotById) {
|
||||
const wagon = await this.dataSource.getRepository(Wagon).findOne({
|
||||
where: { id: dto.targetWagonId },
|
||||
relations: { wagonType: true },
|
||||
});
|
||||
const onThisTrain =
|
||||
!!wagon &&
|
||||
((!!schedule.trainSet?.trainId && wagon.trainId === schedule.trainSet.trainId) ||
|
||||
slots.some((w) => w.physicalWagonId === wagon.id));
|
||||
wagonForTarget = onThisTrain ? wagon : null;
|
||||
}
|
||||
if (!slotById && !wagonForTarget) {
|
||||
throw new NotFoundException('Target wagon is not part of this schedule');
|
||||
}
|
||||
// A physical wagon holds at most one slot. When the caller addressed the
|
||||
// wagon directly but a slot is already pinned to it, move into that slot
|
||||
// rather than minting a second one on the same wagon.
|
||||
const targetSlot =
|
||||
slotById ??
|
||||
(wagonForTarget
|
||||
? (slots.find((w) => w.physicalWagonId === wagonForTarget.id) ?? null)
|
||||
? (slots.find(
|
||||
(w) =>
|
||||
w.physicalWagonId === wagonForTarget.id && overlaps(spanOf(w), sourceSpan),
|
||||
) ?? null)
|
||||
: null);
|
||||
const consistWagon = targetSlot ? null : wagonForTarget;
|
||||
|
||||
// Leg clash guard: after the move, no two slots on one physical wagon may
|
||||
// ride the same edge. Source load → target wagon; on a swap, target load →
|
||||
// source wagon.
|
||||
const targetPhysicalId = targetSlot?.physicalWagonId ?? consistWagon?.id ?? null;
|
||||
const clashOn = (
|
||||
physicalWagonId: string | null,
|
||||
excludeSlotId: string | null,
|
||||
span: [number, number],
|
||||
) =>
|
||||
!!physicalWagonId &&
|
||||
slots.some(
|
||||
(w) =>
|
||||
w.physicalWagonId === physicalWagonId &&
|
||||
w.id !== excludeSlotId &&
|
||||
w.id !== source.id &&
|
||||
(w.allocations?.length ?? 0) > 0 &&
|
||||
overlaps(spanOf(w), span),
|
||||
);
|
||||
if (clashOn(targetPhysicalId, targetSlot?.id ?? null, sourceSpan)) {
|
||||
throw new BadRequestException(
|
||||
'That wagon already carries another load on the same leg — pick a wagon free on that leg.',
|
||||
);
|
||||
}
|
||||
const targetAllocs = targetSlot ? await loadAllocations(targetSlot.id) : [];
|
||||
if (targetSlot && targetSlot.id === source.id) {
|
||||
return this.getTrainScheduleById(scheduleId);
|
||||
}
|
||||
if (
|
||||
targetSlot &&
|
||||
targetAllocs.length &&
|
||||
clashOn(source.physicalWagonId ?? null, source.id, spanOf(targetSlot))
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'Swap refused: the source wagon already carries another load on the incoming load’s leg.',
|
||||
);
|
||||
}
|
||||
|
||||
const loadTypesOf = (allocs: WagonBookingAllocation[]) => [
|
||||
...new Set(allocs.map((a) => (a.loadType ?? 'CONTAINER').toUpperCase())),
|
||||
|
||||
Reference in New Issue
Block a user