- 📱 Show the QR code at the gate for easy check-in. Arrive at least 30 minutes before departure.
+ 📱 Show the QR code at the gate for easy check-in. Arrive at least 2 hours before departure.
@@ -225,7 +225,7 @@ export default function HowToGuidePage() {
What should I bring on the day of travel?
- Bring your ticket (digital or printed), valid ID/passport, and arrive 30 minutes before departure.
+ Bring your ticket (digital or printed), valid ID/passport, and arrive 2 hours before departure.
diff --git a/apps/edr-passenger-web/portal/src/lib/generate-voucher.ts b/apps/edr-passenger-web/portal/src/lib/generate-voucher.ts
index 47ee3fdcc..dab5bba26 100644
--- a/apps/edr-passenger-web/portal/src/lib/generate-voucher.ts
+++ b/apps/edr-passenger-web/portal/src/lib/generate-voucher.ts
@@ -374,7 +374,7 @@ function drawInstructions(doc: jsPDF, y: number, margin: number, pageWidth: numb
doc.text('BEFORE YOU TRAVEL', margin + padX, y + 6, { charSpace: 0.3 });
doc.setFont('helvetica', 'normal'); doc.setFontSize(8);
doc.text('Present this voucher (printed or on your phone) at the terminal for boarding.', margin + padX, y + 11);
- doc.text('Please arrive at least 30 minutes before scheduled departure.', margin + padX, y + 15);
+ doc.text('Please arrive at least 2 hours before scheduled departure.', margin + padX, y + 15);
return y + cardH + 4;
}
From b5a97d344a6fbb98f5d84603765a48b17d590cc3 Mon Sep 17 00:00:00 2001
From: Marshal
Date: Tue, 14 Jul 2026 13:10:00 +0000
Subject: [PATCH 07/13] train
---
apps/edr-freight-api/src/app.module.ts | 139 +++++++------
.../src/common/booking-guards.ts | 4 +
...0000-LinkWagonMovementToTransferRequest.ts | 54 ++++++
.../train-scheduling/booking-batch.service.ts | 24 ++-
.../train-scheduling.service.ts | 56 ++++--
.../trains/dto/update-train-yard.dto.ts | 12 ++
.../trains/train-builder.controller.ts | 11 ++
.../modules/trains/train-builder.service.ts | 73 +++++--
.../wagons/entities/wagon-movement.entity.ts | 9 +
.../wagon-transfer-requests.controller.ts | 25 +++
.../wagons/wagon-transfer-requests.service.ts | 50 ++++-
.../src/modules/wagons/wagons.module.ts | 11 +-
.../src/modules/wagons/wagons.service.ts | 2 +
.../src/seed/freight-permissions.registry.ts | 4 +
.../contracts/GlCreateBookingForm.tsx | 33 ++++
.../trainBuilder/ChangeYardModal.tsx | 103 ++++++++++
.../trainBuilder/TrainConsistStrip.tsx | 159 ---------------
.../TrainCompositionDiagram.tsx | 54 ++++--
.../wagons/WagonTransferRequestsModal.tsx | 183 +++++++++++++++++-
.../backoffice/src/lib/permissions.ts | 3 +
.../contracts/ContractClearanceListPage.tsx | 91 ++++++++-
.../trainBuilder/TrainBuilderDetailPage.tsx | 73 ++++---
.../trainBuilder/TrainBuilderListPage.tsx | 2 +-
.../BatchScheduleDetailPage.tsx | 6 +
.../TrainScheduleV2DetailPage.tsx | 13 +-
.../backoffice/src/services/api.ts | 25 +++
.../src/services/trainBuilder.service.ts | 14 +-
.../backoffice/src/services/wagon.service.ts | 17 ++
.../backoffice/src/types/trainScheduling.ts | 14 ++
.../components/UpcomingWindowsSection.tsx | 26 ++-
.../BookingDetailPage/ReadonlyBookingView.tsx | 17 +-
.../ContractBookingWindowsSection.tsx | 31 ++-
.../contracts/NewShipmentRequestPage.tsx | 100 ++++++++--
.../src/pages/contracts/booking-window.ts | 10 +
.../portal/src/services/bookings.service.ts | 6 +
packages/types/src/freight/index.ts | 2 +
36 files changed, 1101 insertions(+), 355 deletions(-)
create mode 100644 apps/edr-freight-api/src/migrations/2180000000000-LinkWagonMovementToTransferRequest.ts
create mode 100644 apps/edr-freight-api/src/modules/trains/dto/update-train-yard.dto.ts
create mode 100644 apps/edr-freight-web/backoffice/src/components/trainBuilder/ChangeYardModal.tsx
delete mode 100644 apps/edr-freight-web/backoffice/src/components/trainBuilder/TrainConsistStrip.tsx
diff --git a/apps/edr-freight-api/src/app.module.ts b/apps/edr-freight-api/src/app.module.ts
index afb214137..6c31c4f08 100644
--- a/apps/edr-freight-api/src/app.module.ts
+++ b/apps/edr-freight-api/src/app.module.ts
@@ -53,22 +53,23 @@ import {
} from "./seed/edr-freight.seed";
import { EdrOrgSeeder } from "./seed/edr-org.seeder";
import { FreightPositionsSeeder } from "./seed/freight-positions.seeder";
-import { DemoUsersSeeder } from "./seed/demo-users.seeder";
-import { FreightStaffUsersSeeder } from "./seed/freight-staff-users.seeder";
+// Disabled seeds — imports commented out with their provider/injection/run below.
+// import { DemoUsersSeeder } from "./seed/demo-users.seeder";
+// import { FreightStaffUsersSeeder } from "./seed/freight-staff-users.seeder";
import { PaymentModule } from "./modules/payment/payment.module";
-import { PricingDataSeeder } from "./seed/pricing-data.seeder";
+// import { PricingDataSeeder } from "./seed/pricing-data.seeder";
import { FileUploadSettingsSeeder } from "./seed/file-upload-settings.seeder";
-import { IndodeFacilitySeeder } from "./seed/indode-facility.seeder";
-import { Batch14TestDataSeeder } from "./seed/batch1-4-test-data.seeder";
-import { Batch5TestDataSeeder } from "./seed/batch5-test-data.seeder";
-import { Batch7TestDataSeeder } from "./seed/batch7-test-data.seeder";
-import { Batch8TestDataSeeder } from "./seed/batch8-test-data.seeder";
-import { WarehouseDemoSeeder } from "./seed/warehouse-demo.seeder";
-import { ExportDjiboutiInterchangeDemoSeeder } from "./seed/export-djibouti-interchange-demo.seeder";
-import { MarshallingDemoTrainsSeeder } from "./seed/marshalling-demo-trains.seeder";
+// import { IndodeFacilitySeeder } from "./seed/indode-facility.seeder";
+// import { Batch14TestDataSeeder } from "./seed/batch1-4-test-data.seeder";
+// import { Batch5TestDataSeeder } from "./seed/batch5-test-data.seeder";
+// import { Batch7TestDataSeeder } from "./seed/batch7-test-data.seeder";
+// import { Batch8TestDataSeeder } from "./seed/batch8-test-data.seeder";
+// import { WarehouseDemoSeeder } from "./seed/warehouse-demo.seeder";
+// import { ExportDjiboutiInterchangeDemoSeeder } from "./seed/export-djibouti-interchange-demo.seeder";
+// import { MarshallingDemoTrainsSeeder } from "./seed/marshalling-demo-trains.seeder";
import { FreightPermissionKeyMigrationSeeder } from "./seed/freight-permission-key-migration.seeder";
-import { DemoFreightDataSeeder } from "./seed/demo-freight-data.seeder";
-import { GovCompaniesSeeder } from "./seed/gov-companies.seeder";
+// import { DemoFreightDataSeeder } from "./seed/demo-freight-data.seeder";
+// import { GovCompaniesSeeder } from "./seed/gov-companies.seeder";
import { ApprovedFirstLastMileDemoBookingsSeeder } from "./seed/approved-first-lastmile-demo-bookings.seeder";
import { PaidImportExportMileDemoSeeder } from "./seed/paid-import-export-mile-demo.seeder";
//New Trains, Wagons, Container and Cargo management modules
@@ -192,21 +193,22 @@ import { LoggerMiddleware } from "./logger.middleware";
providers: [
EdrOrgSeeder,
FreightPositionsSeeder,
- DemoUsersSeeder,
- FreightStaffUsersSeeder,
- PricingDataSeeder,
FileUploadSettingsSeeder,
FreightPermissionKeyMigrationSeeder,
- DemoFreightDataSeeder,
- GovCompaniesSeeder,
- IndodeFacilitySeeder,
- Batch14TestDataSeeder,
- Batch5TestDataSeeder,
- Batch7TestDataSeeder,
- Batch8TestDataSeeder,
- WarehouseDemoSeeder,
- ExportDjiboutiInterchangeDemoSeeder,
- MarshallingDemoTrainsSeeder,
+ // Disabled seeds — providers commented out (imports/injection/run too):
+ // DemoUsersSeeder,
+ // FreightStaffUsersSeeder,
+ // PricingDataSeeder,
+ // DemoFreightDataSeeder,
+ // GovCompaniesSeeder,
+ // IndodeFacilitySeeder,
+ // Batch14TestDataSeeder,
+ // Batch5TestDataSeeder,
+ // Batch7TestDataSeeder,
+ // Batch8TestDataSeeder,
+ // WarehouseDemoSeeder,
+ // ExportDjiboutiInterchangeDemoSeeder,
+ // MarshallingDemoTrainsSeeder,
ApprovedFirstLastMileDemoBookingsSeeder,
PaidImportExportMileDemoSeeder,
],
@@ -216,51 +218,66 @@ export class AppModule implements OnApplicationBootstrap {
private readonly seeder: DataSeeder,
private readonly edrOrgSeeder: EdrOrgSeeder,
private readonly freightPositionsSeeder: FreightPositionsSeeder,
- private readonly demoUsersSeeder: DemoUsersSeeder,
- private readonly freightStaffUsersSeeder: FreightStaffUsersSeeder,
- private readonly pricingDataSeeder: PricingDataSeeder,
private readonly fileUploadSettingsSeeder: FileUploadSettingsSeeder,
- private readonly indodeFacilitySeeder: IndodeFacilitySeeder,
- private readonly batch14TestDataSeeder: Batch14TestDataSeeder,
- private readonly batch5TestDataSeeder: Batch5TestDataSeeder,
- private readonly batch7TestDataSeeder: Batch7TestDataSeeder,
- private readonly batch8TestDataSeeder: Batch8TestDataSeeder,
- private readonly warehouseDemoSeeder: WarehouseDemoSeeder,
- private readonly exportDjiboutiInterchangeDemoSeeder: ExportDjiboutiInterchangeDemoSeeder,
- private readonly marshallingDemoTrainsSeeder: MarshallingDemoTrainsSeeder,
private readonly freightPermissionKeyMigrationSeeder: FreightPermissionKeyMigrationSeeder,
- private readonly demoFreightDataSeeder: DemoFreightDataSeeder,
- private readonly govCompaniesSeeder: GovCompaniesSeeder,
+ // Disabled seeds — injections commented out (imports/provider/run too):
+ // private readonly demoUsersSeeder: DemoUsersSeeder,
+ // private readonly freightStaffUsersSeeder: FreightStaffUsersSeeder,
+ // private readonly pricingDataSeeder: PricingDataSeeder,
+ // private readonly indodeFacilitySeeder: IndodeFacilitySeeder,
+ // private readonly batch14TestDataSeeder: Batch14TestDataSeeder,
+ // private readonly batch5TestDataSeeder: Batch5TestDataSeeder,
+ // private readonly batch7TestDataSeeder: Batch7TestDataSeeder,
+ // private readonly batch8TestDataSeeder: Batch8TestDataSeeder,
+ // private readonly warehouseDemoSeeder: WarehouseDemoSeeder,
+ // private readonly exportDjiboutiInterchangeDemoSeeder: ExportDjiboutiInterchangeDemoSeeder,
+ // private readonly marshallingDemoTrainsSeeder: MarshallingDemoTrainsSeeder,
+ // private readonly demoFreightDataSeeder: DemoFreightDataSeeder,
+ // private readonly govCompaniesSeeder: GovCompaniesSeeder,
) { }
async onApplicationBootstrap() {
+ // ── Enabled: permissions + file-upload settings (+ dropdown settings) only ──
+ // Everything else below is intentionally disabled. Seeders stay registered
+ // as providers and injected; only their .run() calls are commented out, so
+ // re-enabling any of them is a one-line uncomment.
+
+ // Permissions foundation — keep enabled:
+ // freightPermissionKeyMigration → renames legacy permission keys
+ // seeder (IAM DataSeeder) → seeds the IAM app, roles, permissions
+ // edrOrgSeeder → seeds org/unit + the Permission catalog
+ // freightPositionsSeeder → seeds Position + PositionPermission rows
+ // (depends on edrOrgSeeder, must run after)
await this.freightPermissionKeyMigrationSeeder.run();
await this.seeder.run();
await this.edrOrgSeeder.run();
await this.freightPositionsSeeder.run();
- await this.demoUsersSeeder.run();
- await this.freightStaffUsersSeeder.run();
- await this.pricingDataSeeder.run();
+
+ // File upload settings — keep enabled.
await this.fileUploadSettingsSeeder.run();
- await this.indodeFacilitySeeder.run();
- await this.batch14TestDataSeeder.run();
- await this.batch5TestDataSeeder.run();
- await this.batch7TestDataSeeder.run();
- await this.batch8TestDataSeeder.run();
- await this.warehouseDemoSeeder.run();
- await this.exportDjiboutiInterchangeDemoSeeder.run();
- await this.marshallingDemoTrainsSeeder.run();
- // Idempotent demo data: ≥100 wagons/type, approval chains, 4 staff users.
- // Each block self-guards on an empty-table check, so this is safe every boot.
- // Demo data seeds (DemoBookingsSeeder, PricingDataSeeder,
- // FileUploadSettingsSeeder) are intentionally disabled — they stay
- // registered as providers but are not run. Re-inject + call .run() to enable.
- // demoFreightDataSeeder now seeds ONLY the 4 staff users (wagons + approval
- // rules are disabled inside the seeder). Kept running for the staff users.
- await this.demoFreightDataSeeder.run();
- // Government entities (with importer/exporter profiles) that government
- // bookings bill to. Idempotent — keyed by fixed IDs.
- await this.govCompaniesSeeder.run();
+
+ // Dropdown settings are not seeded on boot; run them with
+ // `pnpm seed:dropdown-settings` (src/scripts/seed-dropdown-settings.ts).
+
+ // ── Disabled: demo / test / reference data seeds ──
+ // Uncomment a line to re-enable that seed.
+ // await this.demoUsersSeeder.run();
+ // await this.freightStaffUsersSeeder.run();
+ // await this.pricingDataSeeder.run();
+ // await this.indodeFacilitySeeder.run();
+ // await this.batch14TestDataSeeder.run();
+ // await this.batch5TestDataSeeder.run();
+ // await this.batch7TestDataSeeder.run();
+ // await this.batch8TestDataSeeder.run();
+ // await this.warehouseDemoSeeder.run();
+ // await this.exportDjiboutiInterchangeDemoSeeder.run();
+ // await this.marshallingDemoTrainsSeeder.run();
+ // demoFreightDataSeeder seeds ONLY the 4 staff users (wagons + approval
+ // rules are already disabled inside the seeder).
+ // await this.demoFreightDataSeeder.run();
+ // Government entities (importer/exporter profiles) that government bookings
+ // bill to. Idempotent — keyed by fixed IDs.
+ // await this.govCompaniesSeeder.run();
}
configure(consumer: MiddlewareConsumer) {
diff --git a/apps/edr-freight-api/src/common/booking-guards.ts b/apps/edr-freight-api/src/common/booking-guards.ts
index d3344aa5a..9769a7f18 100644
--- a/apps/edr-freight-api/src/common/booking-guards.ts
+++ b/apps/edr-freight-api/src/common/booking-guards.ts
@@ -34,6 +34,10 @@ export const WagonTransferRequest = () =>
export const WagonTransferFulfill = () =>
BookingStaff(FREIGHT_PERMS.wagons.transferFulfill);
+/** Admin: read every staffer's wagon-transfer history (not just one's own). */
+export const WagonTransferHistoryAll = () =>
+ BookingStaff(FREIGHT_PERMS.wagons.transferHistoryAll);
+
/** Org-administration endpoints (user mgmt, billing config, company CRUD, settings). */
export const FreightAdmin = () => BookingStaff(FREIGHT_PERMS.admin);
diff --git a/apps/edr-freight-api/src/migrations/2180000000000-LinkWagonMovementToTransferRequest.ts b/apps/edr-freight-api/src/migrations/2180000000000-LinkWagonMovementToTransferRequest.ts
new file mode 100644
index 000000000..3f10fa874
--- /dev/null
+++ b/apps/edr-freight-api/src/migrations/2180000000000-LinkWagonMovementToTransferRequest.ts
@@ -0,0 +1,54 @@
+import { MigrationInterface, QueryRunner } from 'typeorm';
+
+/**
+ * Link each physical wagon move back to the transfer request that drove it, so
+ * the history can show "Request S→K, 3× NX70 → wagons W101, W102, W103".
+ * Nullable — legacy moves and non-request manual corrections carry no request.
+ * Also indexes `moved_by_user_id` for the per-user history queries.
+ */
+export class LinkWagonMovementToTransferRequest2180000000000
+ implements MigrationInterface
+{
+ name = 'LinkWagonMovementToTransferRequest2180000000000';
+
+ public async up(queryRunner: QueryRunner): Promise {
+ await queryRunner.query(`
+ ALTER TABLE freight.wagon_movements
+ ADD COLUMN IF NOT EXISTS transfer_request_id uuid NULL
+ `);
+ await queryRunner.query(`
+ DO $$
+ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint WHERE conname = 'fk_wm_transfer_request'
+ ) THEN
+ ALTER TABLE freight.wagon_movements
+ ADD CONSTRAINT fk_wm_transfer_request
+ FOREIGN KEY (transfer_request_id)
+ REFERENCES freight.wagon_transfer_requests (id) ON DELETE SET NULL;
+ END IF;
+ END $$;
+ `);
+ await queryRunner.query(`
+ CREATE INDEX IF NOT EXISTS idx_wm_transfer_request
+ ON freight.wagon_movements (transfer_request_id)
+ `);
+ await queryRunner.query(`
+ CREATE INDEX IF NOT EXISTS idx_wm_moved_by
+ ON freight.wagon_movements (moved_by_user_id)
+ `);
+ }
+
+ public async down(queryRunner: QueryRunner): Promise {
+ await queryRunner.query(`DROP INDEX IF EXISTS freight.idx_wm_moved_by`);
+ await queryRunner.query(`DROP INDEX IF EXISTS freight.idx_wm_transfer_request`);
+ await queryRunner.query(`
+ ALTER TABLE freight.wagon_movements
+ DROP CONSTRAINT IF EXISTS fk_wm_transfer_request
+ `);
+ await queryRunner.query(`
+ ALTER TABLE freight.wagon_movements
+ DROP COLUMN IF EXISTS transfer_request_id
+ `);
+ }
+}
diff --git a/apps/edr-freight-api/src/modules/train-scheduling/booking-batch.service.ts b/apps/edr-freight-api/src/modules/train-scheduling/booking-batch.service.ts
index a9711c1e5..e51d4ad23 100644
--- a/apps/edr-freight-api/src/modules/train-scheduling/booking-batch.service.ts
+++ b/apps/edr-freight-api/src/modules/train-scheduling/booking-batch.service.ts
@@ -208,6 +208,8 @@ export interface BatchBoardScheduleDetail {
docReviewEndsAt: string | null;
paymentPhaseEndsAt: string | null;
bookingCycleNo: number;
+ /** Built train (Train Builder) behind this departure, when scheduled by train. */
+ train: BatchBoardSchedule["train"];
locomotive: BatchBoardSchedule["locomotive"];
capacity: BatchBoardSchedule["capacity"];
counts: BatchBoardSchedule["counts"];
@@ -235,6 +237,12 @@ export interface BatchBoardSchedule {
docReviewEndsAt: string | null;
paymentPhaseEndsAt: string | null;
bookingCycleNo: number;
+ /** Built train (Train Builder) behind this departure, when scheduled by train. */
+ train: {
+ id: string;
+ code: string;
+ trainName: string | null;
+ } | null;
locomotive: {
code: string;
name: string | null;
@@ -877,7 +885,7 @@ export class BookingBatchService implements OnModuleInit {
const [schedules, total] = await this.trainSchedulesRepository.findAndCount({
where,
relations: {
- trainSet: { locomotive: true },
+ trainSet: { locomotive: true, train: true },
originStation: true,
destinationStation: true,
// Yards supply the route's display name for `routeName` below;
@@ -1128,6 +1136,13 @@ export class BookingBatchService implements OnModuleInit {
? s.paymentPhaseEndsAt.toISOString()
: null,
bookingCycleNo: s.bookingCycleNo ?? 0,
+ train: s.trainSet?.train
+ ? {
+ id: s.trainSet.train.id,
+ code: s.trainSet.train.code,
+ trainName: s.trainSet.train.trainName ?? null,
+ }
+ : null,
locomotive: loco
? {
code: loco.code,
@@ -1247,6 +1262,13 @@ export class BookingBatchService implements OnModuleInit {
? s.paymentPhaseEndsAt.toISOString()
: null,
bookingCycleNo: s.bookingCycleNo ?? 0,
+ train: s.trainSet?.train
+ ? {
+ id: s.trainSet.train.id,
+ code: s.trainSet.train.code,
+ trainName: s.trainSet.train.trainName ?? null,
+ }
+ : null,
locomotive: loco
? {
code: loco.code,
diff --git a/apps/edr-freight-api/src/modules/train-scheduling/train-scheduling.service.ts b/apps/edr-freight-api/src/modules/train-scheduling/train-scheduling.service.ts
index 874516548..7e0720238 100644
--- a/apps/edr-freight-api/src/modules/train-scheduling/train-scheduling.service.ts
+++ b/apps/edr-freight-api/src/modules/train-scheduling/train-scheduling.service.ts
@@ -282,6 +282,8 @@ interface BookingWindowRow {
origin_code: string | null;
destination_label: string | null;
destination_code: string | null;
+ /** Full ordered corridor (origin → milestones → destination) from the schedule's route. */
+ route_stations: string[] | null;
}
@Injectable()
@@ -1329,9 +1331,15 @@ export class TrainSchedulingService {
limitLoco.maxPullWeightTons + (Number(limitLoco.overageToleranceTons) || 0);
const lengthCapWithOverage =
limitLoco.maxTrainLengthMeters + (Number(limitLoco.overageToleranceMeters) || 0);
- if (!dto.forceAssign && weightCapWithOverage < totalWeightTons) {
+ // The locomotives pull GROSS weight: the customers' cargo plus the empty
+ // weight of every planned wagon — cargo-only comparison understates the load.
+ const planTareTons = roundTons(
+ wagonPlan.reduce((sum, slot) => sum + Number(slot.tareWeightTons ?? 0), 0),
+ );
+ const grossWeightTons = roundTons(totalWeightTons + planTareTons);
+ if (!dto.forceAssign && weightCapWithOverage < grossWeightTons) {
throw new BadRequestException(
- `Train set locomotives cannot pull ${totalWeightTons}T`,
+ `Train set locomotives cannot pull ${grossWeightTons}T gross (${totalWeightTons}T cargo + ${planTareTons}T wagon tare)`,
);
}
if (!dto.forceAssign && lengthCapWithOverage < totalLengthMeters) {
@@ -4605,14 +4613,8 @@ export class TrainSchedulingService {
name: link.locomotive!.name ?? null,
})),
wagonCount: wagons.length,
- maxGrossTons: roundTons(
- wagons.reduce(
- (sum, w) =>
- sum +
- (Number(w.wagonType?.tareWeightTons) || 0) +
- (Number(w.wagonType?.capacityTons) || 0),
- 0,
- ),
+ totalTareTons: roundTons(
+ wagons.reduce((sum, w) => sum + (Number(w.wagonType?.tareWeightTons) || 0), 0),
),
totalLengthMeters: roundTons(
wagons.reduce((sum, w) => sum + (Number(w.wagonType?.lengthMeters) || 0), 0),
@@ -4725,7 +4727,11 @@ export class TrainSchedulingService {
ts.booking_cycle_no,
ts.scheduled_departure_date,
oy.label AS origin_label, oy.code AS origin_code,
- dy.label AS destination_label, dy.code AS destination_code
+ dy.label AS destination_label, dy.code AS destination_code,
+ (SELECT array_agg(COALESCE(rmy.label, rmy.code) ORDER BY rm.sequence_no)
+ FROM freight.route_milestones rm
+ JOIN freight.yards rmy ON rmy.id = rm.yard_id
+ WHERE rm.route_id = ts.route_id) AS route_stations
FROM freight.train_schedules ts
LEFT JOIN freight.contract_routes cr
ON cr.deleted_at IS NULL
@@ -4777,7 +4783,11 @@ export class TrainSchedulingService {
ts.booking_cycle_no,
ts.scheduled_departure_date,
oy.label AS origin_label, oy.code AS origin_code,
- dy.label AS destination_label, dy.code AS destination_code
+ dy.label AS destination_label, dy.code AS destination_code,
+ (SELECT array_agg(COALESCE(rmy.label, rmy.code) ORDER BY rm.sequence_no)
+ FROM freight.route_milestones rm
+ JOIN freight.yards rmy ON rmy.id = rm.yard_id
+ WHERE rm.route_id = ts.route_id) AS route_stations
FROM freight.train_schedules ts
JOIN freight.contract_routes cr
ON cr.contract_id = $1
@@ -4823,7 +4833,11 @@ export class TrainSchedulingService {
ts.booking_cycle_no,
ts.scheduled_departure_date,
oy.label AS origin_label, oy.code AS origin_code,
- dy.label AS destination_label, dy.code AS destination_code
+ dy.label AS destination_label, dy.code AS destination_code,
+ (SELECT array_agg(COALESCE(rmy.label, rmy.code) ORDER BY rm.sequence_no)
+ FROM freight.route_milestones rm
+ JOIN freight.yards rmy ON rmy.id = rm.yard_id
+ WHERE rm.route_id = ts.route_id) AS route_stations
FROM freight.train_schedules ts
LEFT JOIN freight.yards oy ON oy.id = ts.origin_station_id
LEFT JOIN freight.yards dy ON dy.id = ts.destination_station_id
@@ -4845,6 +4859,17 @@ export class TrainSchedulingService {
}
private mapBookingWindowRow(r: BookingWindowRow) {
+ const origin = r.origin_label ?? r.origin_code ?? null;
+ const destination = r.destination_label ?? r.destination_code ?? null;
+ // Full corridor from the route's milestones (origin → stops → destination).
+ // Falls back to the schedule's origin/destination when no milestones exist.
+ const milestoneStops = (r.route_stations ?? []).filter(
+ (s): s is string => Boolean(s),
+ );
+ const routeStations =
+ milestoneStops.length >= 2
+ ? milestoneStops
+ : [origin, destination].filter((s): s is string => Boolean(s));
return {
scheduleId: r.schedule_id,
reference: r.reference ?? null,
@@ -4860,8 +4885,9 @@ export class TrainSchedulingService {
bookingWindowStatus: r.booking_window_status,
bookingCycleNo: r.booking_cycle_no,
departureDate: r.scheduled_departure_date,
- origin: r.origin_label ?? r.origin_code ?? null,
- destination: r.destination_label ?? r.destination_code ?? null,
+ origin,
+ destination,
+ routeStations,
};
}
diff --git a/apps/edr-freight-api/src/modules/trains/dto/update-train-yard.dto.ts b/apps/edr-freight-api/src/modules/trains/dto/update-train-yard.dto.ts
new file mode 100644
index 000000000..428651288
--- /dev/null
+++ b/apps/edr-freight-api/src/modules/trains/dto/update-train-yard.dto.ts
@@ -0,0 +1,12 @@
+import { ApiProperty } from '@nestjs/swagger';
+import { IsUUID } from 'class-validator';
+
+export class UpdateTrainYardDto {
+ @ApiProperty({
+ format: 'uuid',
+ description:
+ 'Yard the train now sits in. The coupled locomotives and wagons are relocated with it.',
+ })
+ @IsUUID()
+ currentYardId!: string;
+}
diff --git a/apps/edr-freight-api/src/modules/trains/train-builder.controller.ts b/apps/edr-freight-api/src/modules/trains/train-builder.controller.ts
index 7281aca31..7ed3e4c42 100644
--- a/apps/edr-freight-api/src/modules/trains/train-builder.controller.ts
+++ b/apps/edr-freight-api/src/modules/trains/train-builder.controller.ts
@@ -7,6 +7,7 @@ import {
HttpStatus,
Param,
ParseUUIDPipe,
+ Patch,
Post,
Put,
Query,
@@ -19,6 +20,7 @@ import { BuildTrainDto } from './dto/build-train.dto';
import { ListBuiltTrainsQueryDto } from './dto/list-built-trains-query.dto';
import { ReorderTrainWagonsDto } from './dto/reorder-train-wagons.dto';
import { UpdateTrainLocomotivesDto } from './dto/update-train-locomotives.dto';
+import { UpdateTrainYardDto } from './dto/update-train-yard.dto';
import { TrainBuilderService } from './train-builder.service';
@ApiTags('train-builder')
@@ -57,6 +59,15 @@ export class TrainBuilderController {
return this.trainBuilderService.setLocomotives(id, dto);
}
+ @Patch(':id/yard')
+ @FleetManage()
+ @ApiOperation({
+ summary: 'Relocate the train — its locomotives and wagons move to the new yard with it',
+ })
+ setYard(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateTrainYardDto) {
+ return this.trainBuilderService.setYard(id, dto.currentYardId);
+ }
+
@Post(':id/wagons')
@FleetManage()
@ApiOperation({ summary: "Append AVAILABLE wagons from the train's yard to the consist" })
diff --git a/apps/edr-freight-api/src/modules/trains/train-builder.service.ts b/apps/edr-freight-api/src/modules/trains/train-builder.service.ts
index c28873234..b92ab21d6 100644
--- a/apps/edr-freight-api/src/modules/trains/train-builder.service.ts
+++ b/apps/edr-freight-api/src/modules/trains/train-builder.service.ts
@@ -1,4 +1,4 @@
-import { Freight, WagonStatus } from '@edr/types';
+import { Freight, WagonMovementKind, WagonStatus } from '@edr/types';
import {
BadRequestException,
ConflictException,
@@ -10,6 +10,7 @@ import { DataSource, EntityManager, ILike, In } from 'typeorm';
import { Locomotive } from '../locomotives/entities/locomotive.entity';
import { Yard } from '../rule-engine/entities/yard.entity';
import { minLocomotiveLimits } from '../train-scheduling/train-capacity.util';
+import { WagonMovement } from '../wagons/entities/wagon-movement.entity';
import { Wagon } from '../wagons/entities/wagon.entity';
import { AssignTrainWagonsDto } from './dto/assign-train-wagons.dto';
import { BuildTrainDto } from './dto/build-train.dto';
@@ -202,7 +203,6 @@ export class TrainBuilderService {
const totalLengthMeters = round(
wagons.reduce((sum, w) => sum + (w.wagonType?.lengthMeters ?? 0), 0),
);
- const maxGrossTons = round(totalTareTons + totalCapacityTons);
const maxPullWeightTons = round(limits?.maxPullWeightTons ?? 0);
const maxTrainLengthMeters = round(limits?.maxTrainLengthMeters ?? 0);
@@ -221,14 +221,17 @@ export class TrainBuilderService {
totals: {
wagonCount: wagons.length,
totalTareTons,
+ // Informational only — building never checks against full capacity;
+ // the real gross check (cargo + tare vs haul limit) runs at allocation.
totalCapacityTons,
- maxGrossTons,
totalLengthMeters,
maxPullWeightTons,
maxTrainLengthMeters,
- // Fully loaded gross vs. what the weakest locomotive can haul.
- weightUtilizationPct: maxPullWeightTons
- ? round((maxGrossTons / maxPullWeightTons) * 100)
+ // Cargo the locomotives can still haul once pulling the empty consist.
+ payloadCapacityTons: round(Math.max(0, maxPullWeightTons - totalTareTons)),
+ // Share of the haul limit consumed by the empty wagons alone.
+ tareUtilizationPct: maxPullWeightTons
+ ? round((totalTareTons / maxPullWeightTons) * 100)
: null,
lengthUtilizationPct: maxTrainLengthMeters
? round((totalLengthMeters / maxTrainLengthMeters) * 100)
@@ -269,6 +272,54 @@ export class TrainBuilderService {
return this.getComposition(id);
}
+ /**
+ * Relocate the train to another yard. The consist moves as one unit: every
+ * coupled locomotive and wagon follows to the new yard (so their current
+ * yards always match the train's), and each wagon gets a movement-ledger row.
+ * Blocked while the train is out on a dispatched run.
+ */
+ async setYard(id: string, currentYardId: string) {
+ await this.dataSource.transaction(async (manager) => {
+ const train = await this.getEditableTrain(manager, id);
+ if (train.currentYardId === currentYardId) return;
+ const yard = await manager.getRepository(Yard).findOne({ where: { id: currentYardId } });
+ if (!yard) throw new NotFoundException(`Yard ${currentYardId} not found`);
+
+ await manager.getRepository(Train).update(train.id, { currentYardId: yard.id });
+
+ const links = await manager
+ .getRepository(TrainLocomotive)
+ .find({ where: { trainId: train.id } });
+ if (links.length) {
+ await manager
+ .getRepository(Locomotive)
+ .update(
+ { id: In(links.map((link) => link.locomotiveId)) },
+ { currentYardId: yard.id },
+ );
+ }
+
+ const wagons = await manager.getRepository(Wagon).find({ where: { trainId: train.id } });
+ const now = new Date();
+ for (const wagon of wagons) {
+ if (wagon.currentYardId === yard.id) continue;
+ await manager.getRepository(Wagon).update(wagon.id, { currentYardId: yard.id });
+ // Ledger row keeps the wagon's yard history auditable (mirrors the
+ // manual-relocation path in the wagons service).
+ await manager.getRepository(WagonMovement).save(
+ manager.getRepository(WagonMovement).create({
+ wagonId: wagon.id,
+ fromYardId: wagon.currentYardId ?? null,
+ toYardId: yard.id,
+ kind: WagonMovementKind.Manual,
+ occurredAt: now,
+ }),
+ );
+ }
+ });
+ return this.getComposition(id);
+ }
+
/** Append AVAILABLE wagons from the train's own yard to the consist. */
async assignWagons(id: string, dto: AssignTrainWagonsDto) {
await this.dataSource.transaction(async (manager) => {
@@ -361,12 +412,8 @@ export class TrainBuilderService {
.map((link) => link.locomotive)
.filter((loco): loco is Locomotive => Boolean(loco));
const wagons = train.wagons ?? [];
- const maxGrossTons = round(
- wagons.reduce(
- (sum, w) =>
- sum + (Number(w.wagonType?.tareWeightTons) || 0) + (Number(w.wagonType?.capacityTons) || 0),
- 0,
- ),
+ const totalTareTons = round(
+ wagons.reduce((sum, w) => sum + (Number(w.wagonType?.tareWeightTons) || 0), 0),
);
return {
id: train.id,
@@ -379,7 +426,7 @@ export class TrainBuilderService {
: null,
locomotives: locomotives.map((loco) => ({ id: loco.id, code: loco.code, name: loco.name ?? null })),
wagonCount: wagons.length,
- maxGrossTons,
+ totalTareTons,
totalLengthMeters: round(
wagons.reduce((sum, w) => sum + (Number(w.wagonType?.lengthMeters) || 0), 0),
),
diff --git a/apps/edr-freight-api/src/modules/wagons/entities/wagon-movement.entity.ts b/apps/edr-freight-api/src/modules/wagons/entities/wagon-movement.entity.ts
index 7c5ed092c..a36e5deea 100644
--- a/apps/edr-freight-api/src/modules/wagons/entities/wagon-movement.entity.ts
+++ b/apps/edr-freight-api/src/modules/wagons/entities/wagon-movement.entity.ts
@@ -4,6 +4,7 @@ import { Column, Entity, Index, JoinColumn, ManyToOne } from 'typeorm';
import { Yard } from '../../rule-engine/entities/yard.entity';
import { Wagon } from './wagon.entity';
+import { WagonTransferRequest } from './wagon-transfer-request.entity';
/**
* Ledger of every physical wagon relocation between yards — one row per move.
@@ -51,6 +52,14 @@ export class WagonMovement extends BaseEntity {
@Column({ name: 'moved_by_user_id', type: 'uuid', nullable: true })
movedByUserId?: string | null;
+ /** The transfer request this move fulfilled, when it came from one. */
+ @Column({ name: 'transfer_request_id', type: 'uuid', nullable: true })
+ transferRequestId?: string | null;
+
+ @ManyToOne(() => WagonTransferRequest, { nullable: true })
+ @JoinColumn({ name: 'transfer_request_id' })
+ transferRequest?: WagonTransferRequest | null;
+
@Column({ name: 'occurred_at', type: 'timestamptz' })
occurredAt!: Date;
diff --git a/apps/edr-freight-api/src/modules/wagons/wagon-transfer-requests.controller.ts b/apps/edr-freight-api/src/modules/wagons/wagon-transfer-requests.controller.ts
index 07557f431..12fdaf27c 100644
--- a/apps/edr-freight-api/src/modules/wagons/wagon-transfer-requests.controller.ts
+++ b/apps/edr-freight-api/src/modules/wagons/wagon-transfer-requests.controller.ts
@@ -16,6 +16,7 @@ import {
FleetManage,
FleetView,
WagonTransferFulfill,
+ WagonTransferHistoryAll,
WagonTransferRequest,
} from '../../common/booking-guards';
import { CreateTransferRequestDto } from './dto/create-transfer-request.dto';
@@ -50,6 +51,30 @@ export class WagonTransferRequestsController {
return this.service.listRequests(status);
}
+ // NOTE: the two `history` routes MUST stay above `@Get(':id')` — Express
+ // matches in declaration order, so `/history` would otherwise be captured by
+ // the `:id` param route (and rejected by ParseUUIDPipe).
+ @Get('history')
+ @ApiOperation({
+ summary: "Caller's own transfer history (requests filed/fulfilled + wagons moved)",
+ })
+ myHistory(@CurrentUser() user: TCurrentUser) {
+ // Never fall through to the all-staff view: getHistory(undefined) means
+ // "everyone", so a missing caller id must return empty, not leak scope.
+ if (!user?.id) return { requests: [], movements: [] };
+ return this.service.getHistory(user.id);
+ }
+
+ @Get('history/all')
+ @WagonTransferHistoryAll()
+ @ApiQuery({ name: 'userId', required: false })
+ @ApiOperation({
+ summary: "Admin: any/all staff's transfer history (optional ?userId filter)",
+ })
+ allHistory(@Query('userId') userId?: string) {
+ return this.service.getHistory(userId);
+ }
+
@Get(':id')
@ApiOperation({ summary: 'Get one transfer request' })
findOne(@Param('id', ParseUUIDPipe) id: string) {
diff --git a/apps/edr-freight-api/src/modules/wagons/wagon-transfer-requests.service.ts b/apps/edr-freight-api/src/modules/wagons/wagon-transfer-requests.service.ts
index 64b408b6a..bf69d767d 100644
--- a/apps/edr-freight-api/src/modules/wagons/wagon-transfer-requests.service.ts
+++ b/apps/edr-freight-api/src/modules/wagons/wagon-transfer-requests.service.ts
@@ -6,14 +6,24 @@ import {
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
-import { In, Repository } from 'typeorm';
+import { In, IsNull, Not, Repository } from 'typeorm';
import { CreateTransferRequestDto } from './dto/create-transfer-request.dto';
import { FulfillTransferRequestDto } from './dto/fulfill-transfer-request.dto';
import { Wagon } from './entities/wagon.entity';
+import { WagonMovement } from './entities/wagon-movement.entity';
import { WagonTransferRequest } from './entities/wagon-transfer-request.entity';
import { WagonsService } from './wagons.service';
+/** Bundled per-user activity: requests they touched + wagons they moved. */
+export interface TransferHistory {
+ requests: WagonTransferRequest[];
+ movements: WagonMovement[];
+}
+
+/** How many ledger rows the history returns at most (newest first). */
+const HISTORY_LIMIT = 500;
+
const REQUEST_RELATIONS = {
fromYard: true,
toYard: true,
@@ -33,6 +43,8 @@ export class WagonTransferRequestsService {
private readonly requestRepo: Repository,
@InjectRepository(Wagon)
private readonly wagonRepo: Repository,
+ @InjectRepository(WagonMovement)
+ private readonly movementRepo: Repository,
private readonly wagonsService: WagonsService,
) {}
@@ -125,10 +137,12 @@ export class WagonTransferRequestsService {
);
}
- // Reuse the audited bulk-transfer path (writes wagon_movements ledger rows).
+ // Reuse the audited bulk-transfer path (writes wagon_movements ledger rows,
+ // each stamped with this request's id so history can link them back).
await this.wagonsService.bulkTransfer(
{ wagonIds, toYardId: request.toYardId },
userId,
+ { transferRequestId: request.id },
);
request.status = WagonTransferRequestStatus.Fulfilled;
@@ -138,6 +152,38 @@ export class WagonTransferRequestsService {
return this.findById(id);
}
+ /**
+ * Per-user transfer history: the requests a user filed OR fulfilled, plus the
+ * individual wagons they physically moved (linked back to their request when
+ * one drove the move). Pass a `userId` to scope to one staffer; pass
+ * `undefined` for the admin all-staff view. Scope is decided by the CALLER
+ * (the controller passes the caller's id unless they hold the history-all
+ * permission) — this method trusts its argument.
+ */
+ async getHistory(userId?: string | null): Promise {
+ const requests = await this.requestRepo.find({
+ where: userId
+ ? [{ requestedByUserId: userId }, { fulfilledByUserId: userId }]
+ : {},
+ relations: REQUEST_RELATIONS,
+ order: { createdAt: 'DESC' },
+ take: HISTORY_LIMIT,
+ });
+
+ const movements = await this.movementRepo.find({
+ // Own view: moves I made. All view: every user-attributed move (skip the
+ // system-written loaded/reposition legs that carry no mover).
+ where: userId
+ ? { movedByUserId: userId }
+ : { movedByUserId: Not(IsNull()) },
+ relations: { wagon: true, fromYard: true, toYard: true, transferRequest: true },
+ order: { occurredAt: 'DESC' },
+ take: HISTORY_LIMIT,
+ });
+
+ return { requests, movements };
+ }
+
/** Withdraw a still-PENDING request. */
async cancelRequest(id: string): Promise {
const request = await this.findById(id);
diff --git a/apps/edr-freight-api/src/modules/wagons/wagons.module.ts b/apps/edr-freight-api/src/modules/wagons/wagons.module.ts
index 4bb1afd33..107a31e7e 100644
--- a/apps/edr-freight-api/src/modules/wagons/wagons.module.ts
+++ b/apps/edr-freight-api/src/modules/wagons/wagons.module.ts
@@ -1,6 +1,7 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Wagon } from './entities/wagon.entity';
+import { WagonMovement } from './entities/wagon-movement.entity';
import { WagonTransferRequest } from './entities/wagon-transfer-request.entity';
import { Train } from '../trains/entities/train.entity';
import { Yard } from '../rule-engine/entities/yard.entity';
@@ -10,7 +11,15 @@ import { WagonsService } from './wagons.service';
import { WagonTransferRequestsService } from './wagon-transfer-requests.service';
@Module({
- imports: [TypeOrmModule.forFeature([Wagon, WagonTransferRequest, Train, Yard])],
+ imports: [
+ TypeOrmModule.forFeature([
+ Wagon,
+ WagonMovement,
+ WagonTransferRequest,
+ Train,
+ Yard,
+ ]),
+ ],
controllers: [
WagonsController,
TrainWagonsReorderController,
diff --git a/apps/edr-freight-api/src/modules/wagons/wagons.service.ts b/apps/edr-freight-api/src/modules/wagons/wagons.service.ts
index ad39fbf7a..55dc177c9 100644
--- a/apps/edr-freight-api/src/modules/wagons/wagons.service.ts
+++ b/apps/edr-freight-api/src/modules/wagons/wagons.service.ts
@@ -180,6 +180,7 @@ export class WagonsService {
async bulkTransfer(
dto: BulkTransferWagonsDto,
userId?: string | null,
+ opts?: { transferRequestId?: string | null },
): Promise<{ moved: number }> {
const { wagonIds, toYardId } = dto;
if (!wagonIds.length) return { moved: 0 };
@@ -215,6 +216,7 @@ export class WagonsService {
toYardId,
kind: WagonMovementKind.Manual,
movedByUserId: userId ?? null,
+ transferRequestId: opts?.transferRequestId ?? null,
occurredAt: new Date(),
}),
);
diff --git a/apps/edr-freight-api/src/seed/freight-permissions.registry.ts b/apps/edr-freight-api/src/seed/freight-permissions.registry.ts
index 7c3fe0700..6e4ec81b1 100644
--- a/apps/edr-freight-api/src/seed/freight-permissions.registry.ts
+++ b/apps/edr-freight-api/src/seed/freight-permissions.registry.ts
@@ -177,6 +177,7 @@ export const FLEET_RAIL_PERMISSIONS: FreightPermissionSeed[] = [
perm('e1b00001-0001-4000-8000-000000000004', 'edr_freight_app:wagons:delete', 'Delete wagon'),
perm('e1b00001-0001-4000-8000-000000000005', 'edr_freight_app:wagons:transfer_request', 'Request wagon transfer'),
perm('e1b00001-0001-4000-8000-000000000006', 'edr_freight_app:wagons:transfer_fulfill', 'Fulfil wagon transfer (OCC)'),
+ perm('e1b00001-0001-4000-8000-000000000007', 'edr_freight_app:wagons:transfer_history_all', "View all staff's transfer history"),
perm('e1c00001-0001-4000-8000-000000000001', 'edr_freight_app:trains:view', 'View trains'),
perm('e1c00001-0001-4000-8000-000000000002', 'edr_freight_app:trains:create', 'Create train'),
perm('e1c00001-0001-4000-8000-000000000003', 'edr_freight_app:trains:update', 'Update train'),
@@ -446,6 +447,9 @@ export const FREIGHT_PERMS = {
// executes the move). Distinct keys so OCC can hold fulfil without request.
transferRequest: 'edr_freight_app:wagons:transfer_request',
transferFulfill: 'edr_freight_app:wagons:transfer_fulfill',
+ // Admin: read every staffer's transfer history. Without it, a user only sees
+ // their own (the /history endpoint uses the caller id, backend-enforced).
+ transferHistoryAll: 'edr_freight_app:wagons:transfer_history_all',
},
trains: {
view: 'edr_freight_app:trains:view',
diff --git a/apps/edr-freight-web/backoffice/src/components/contracts/GlCreateBookingForm.tsx b/apps/edr-freight-web/backoffice/src/components/contracts/GlCreateBookingForm.tsx
index 223b357c1..0cd00d63b 100644
--- a/apps/edr-freight-web/backoffice/src/components/contracts/GlCreateBookingForm.tsx
+++ b/apps/edr-freight-web/backoffice/src/components/contracts/GlCreateBookingForm.tsx
@@ -49,6 +49,7 @@ import { api } from "@/services/api";
import { PageContainer } from "@/components/page";
import { PageHeader } from "@/components/page/PageHeader";
import { contractsService } from "@/services/contracts.service";
+import { bookingsService } from "@/services/bookings.service";
import {
useContractCapacity,
useContractDetail,
@@ -180,6 +181,9 @@ export default function GlCreateBookingForm() {
}>();
const [searchParams] = useSearchParams();
const requestIdParam = searchParams.get("requestId");
+ // Rebook: copy an EXPIRED booking's cargo into a fresh booking on the same
+ // contract (GL only picks a new schedule). Set by the clearance Rebook action.
+ const copyFromParam = searchParams.get("copyFrom");
const navigate = useNavigate();
const { data: contract, isLoading } = useContractDetail(id);
const mutations = useContractMutations(id ?? "");
@@ -205,6 +209,13 @@ export default function GlCreateBookingForm() {
enabled: Boolean(requestId),
});
+ // The expired booking a Rebook is copying from (its cargo seeds the form).
+ const { data: copyFromBooking } = useQuery({
+ queryKey: ["rebook-copy-from", copyFromParam],
+ queryFn: () => bookingsService.getById(copyFromParam!),
+ enabled: Boolean(copyFromParam),
+ });
+
// Same window-gating the customer sees: booking is only allowed while a
// window is OPEN for one of the contract's routes. Intercity contracts are
// never window-gated — the shipment rides a passing train staff pick later.
@@ -363,6 +374,28 @@ export default function GlCreateBookingForm() {
if (bookingRequest.notes) setNotes(bookingRequest.notes);
}, [bookingRequest, prefilled]);
+ // Rebook seed: copy the source booking's container lines once. (Bulk weight /
+ // item count isn't on the booking payload yet, so bulk rebooks fall through to
+ // the normal contract seed and GL re-enters the quantity.)
+ useEffect(() => {
+ if (!copyFromBooking || prefilled) return;
+ const lines = copyFromBooking.bookingContainers ?? [];
+ if (!lines.length) return;
+ setPrefilled(true);
+ setContainerLines(
+ lines.map((c) => {
+ const qty = Math.max(1, c.quantity);
+ return {
+ containerSize: String(c.containerType?.sizeFt ?? ""),
+ quantity: String(qty),
+ hazardousQuantity: "0",
+ reeferQuantity: "0",
+ units: Array.from({ length: qty }, emptyUnit),
+ };
+ }),
+ );
+ }, [copyFromBooking, prefilled]);
+
// Seed one shipment line per contracted size exactly once — same seeding the
// portal form does. Subsequent renders reuse the lines.
useEffect(() => {
diff --git a/apps/edr-freight-web/backoffice/src/components/trainBuilder/ChangeYardModal.tsx b/apps/edr-freight-web/backoffice/src/components/trainBuilder/ChangeYardModal.tsx
new file mode 100644
index 000000000..0e4bddbc3
--- /dev/null
+++ b/apps/edr-freight-web/backoffice/src/components/trainBuilder/ChangeYardModal.tsx
@@ -0,0 +1,103 @@
+import { Alert, Button, Group, Modal, Select, Stack, Text } from "@mantine/core";
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { isAxiosError } from "axios";
+import { MapPin } from "lucide-react";
+import { useEffect, useState } from "react";
+
+import { api } from "@/services/api";
+import type { TrainComposition } from "@/services/trainBuilder.service";
+import { useToast } from "@/hooks/use-toast";
+
+const parseError = (error: unknown, fallback: string) => {
+ if (isAxiosError(error)) {
+ const message = error.response?.data?.message;
+ if (Array.isArray(message)) return message.join(", ");
+ if (typeof message === "string") return message;
+ }
+ return fallback;
+};
+
+/**
+ * Relocate the train to another yard. The consist moves as one unit — every
+ * coupled locomotive and wagon follows, so their current yards always match
+ * the train's.
+ */
+export default function ChangeYardModal({ composition, opened, onClose }: ChangeYardModalProps) {
+ const { toast } = useToast();
+ const [yardId, setYardId] = useState("");
+
+ const yardsQuery = useQuery(api.routes.yards.queryOptions({ staleTime: 5 * 60_000 }));
+ const setYard = useMutation(api.trainBuilder.setYard.mutationOptions());
+
+ useEffect(() => {
+ if (opened) setYardId(composition?.currentYard?.id ?? "");
+ }, [opened, composition]);
+
+ const handleSave = async () => {
+ if (!composition || !yardId) return;
+ try {
+ await setYard.mutateAsync({ id: composition.id, currentYardId: yardId });
+ toast({ title: "Train relocated" });
+ onClose();
+ } catch (err) {
+ toast({
+ title: "Relocation failed",
+ description: parseError(err, "Could not change the yard"),
+ variant: "destructive",
+ });
+ }
+ };
+
+ const memberCount =
+ (composition?.locomotives.length ?? 0) + (composition?.totals.wagonCount ?? 0);
+
+ return (
+ Change yard — train {composition?.code}}
+ radius="lg"
+ centered
+ >
+
+ }>
+ The whole consist moves with the train: {composition?.locomotives.length ?? 0}{" "}
+ locomotive{(composition?.locomotives.length ?? 0) === 1 ? "" : "s"} and{" "}
+ {composition?.totals.wagonCount ?? 0} wagon
+ {(composition?.totals.wagonCount ?? 0) === 1 ? "" : "s"} ({memberCount} vehicles)
+ are relocated so their current yard always matches the train's. Wagon moves are
+ recorded in the movement ledger.
+
+
+
+ );
+}
+
+export interface ChangeYardModalProps {
+ composition: TrainComposition | null;
+ opened: boolean;
+ onClose: () => void;
+}
diff --git a/apps/edr-freight-web/backoffice/src/components/trainBuilder/TrainConsistStrip.tsx b/apps/edr-freight-web/backoffice/src/components/trainBuilder/TrainConsistStrip.tsx
deleted file mode 100644
index c86dbc8ef..000000000
--- a/apps/edr-freight-web/backoffice/src/components/trainBuilder/TrainConsistStrip.tsx
+++ /dev/null
@@ -1,159 +0,0 @@
-import { Box, Group, Stack, Text, Tooltip } from "@mantine/core";
-import { Train as TrainIcon } from "lucide-react";
-
-import type {
- TrainCompositionLocomotive,
- TrainCompositionWagon,
-} from "@/services/trainBuilder.service";
-
-/**
- * Visual consist: locomotives + wagons drawn in order on a rail, the way the
- * train would leave the yard. Scrolls horizontally for long consists.
- */
-export default function TrainConsistStrip({
- locomotives,
- wagons,
- emptyHint = "No wagons attached yet — add wagons from the yard below.",
-}: TrainConsistStripProps) {
- return (
-
-
-
- {locomotives.map((loco, index) => (
-
- {index > 0 ? : null}
-
-
- ))}
- {wagons.map((wagon) => (
-
-
-
-
- ))}
-
- {/* The rail */}
-
- {!wagons.length ? (
-
- {emptyHint}
-
- ) : null}
-
-
- );
-}
-
-export interface TrainConsistStripProps {
- locomotives: TrainCompositionLocomotive[];
- wagons: TrainCompositionWagon[];
- emptyHint?: string;
-}
-
-function Coupler() {
- return (
-
- );
-}
-
-function LocomotiveCar({ locomotive }: { locomotive: TrainCompositionLocomotive }) {
- return (
-
-
-
-
-
- {locomotive.code}
-
-
-
- {locomotive.role === "LEAD" ? "Lead loco" : "Assist loco"}
-
-
-
- );
-}
-
-function WagonCar({ wagon }: { wagon: TrainCompositionWagon }) {
- return (
-
-
-
- #{wagon.sequenceNumber ?? "—"}
-
-
- {wagon.wagonNumber}
-
-
- {wagon.wagonType?.code ?? "—"}
-
-
-
- );
-}
diff --git a/apps/edr-freight-web/backoffice/src/components/trainScheduling/TrainCompositionDiagram.tsx b/apps/edr-freight-web/backoffice/src/components/trainScheduling/TrainCompositionDiagram.tsx
index 6ba1a0e29..2805ba60a 100644
--- a/apps/edr-freight-web/backoffice/src/components/trainScheduling/TrainCompositionDiagram.tsx
+++ b/apps/edr-freight-web/backoffice/src/components/trainScheduling/TrainCompositionDiagram.tsx
@@ -506,12 +506,19 @@ function TrackBed() {
export function TrainCompositionDiagram({
locomotive,
+ locomotives,
wagons,
freightType,
trainNumber,
totalLengthMeters,
}: {
locomotive?: { code?: string | null; name?: string | null; maxPullWeightTons?: number | null } | null;
+ /** Full locomotive set (built trains, ≥2). Takes precedence over `locomotive`. */
+ locomotives?: Array<{
+ code?: string | null;
+ name?: string | null;
+ maxPullWeightTons?: number | null;
+ }> | null;
wagons: DiagramWagonInput[];
freightType?: string | null;
trainNumber?: string | null;
@@ -519,6 +526,11 @@ export function TrainCompositionDiagram({
}) {
const { ref, width } = useElementSize();
+ const locos = useMemo(
+ () => (locomotives?.length ? locomotives : locomotive ? [locomotive] : []),
+ [locomotives, locomotive],
+ );
+
const normalized = useMemo(
() => wagons.map((w) => normalizeWagon(w, freightType)),
[wagons, freightType],
@@ -533,6 +545,11 @@ export function TrainCompositionDiagram({
// ceiling the allocation engine spends from.
const totalTare = normalized.reduce((s, w) => s + w.tareWeightTons, 0);
const grossWeight = totalWeight + totalTare;
+ // Weakest locomotive caps the set — same rule the allocation engine applies.
+ const pullLimits = locos
+ .map((l) => Number(l.maxPullWeightTons))
+ .filter((v) => Number.isFinite(v) && v > 0);
+ const pullLimit = pullLimits.length ? Math.min(...pullLimits) : null;
return {
total: normalized.length,
assigned,
@@ -541,22 +558,25 @@ export function TrainCompositionDiagram({
totalTare: Math.round(totalTare * 100) / 100,
grossWeight: Math.round(grossWeight * 100) / 100,
totalCapacity,
- pullUtil:
- locomotive?.maxPullWeightTons && locomotive.maxPullWeightTons > 0
- ? Math.min(100, Math.round((grossWeight / locomotive.maxPullWeightTons) * 100))
- : null,
+ pullLimit,
+ pullUtil: pullLimit
+ ? Math.min(100, Math.round((grossWeight / pullLimit) * 100))
+ : null,
};
- }, [normalized, locomotive]);
+ }, [normalized, locos]);
- // cars-per-row from measured width; locomotive counts as one car
+ // cars-per-row from measured width; each locomotive counts as one car
const perRow = Math.max(1, Math.floor((width || CAR_WIDTH) / CAR_WIDTH));
const cars = useMemo(
- () => [{ kind: "loco" as const }, ...normalized.map((w) => ({ kind: "wagon" as const, w }))],
- [normalized],
+ () => [
+ ...locos.map((l) => ({ kind: "loco" as const, l })),
+ ...normalized.map((w) => ({ kind: "wagon" as const, w })),
+ ],
+ [locos, normalized],
);
const rows = useMemo(() => chunk(cars, perRow), [cars, perRow]);
- if (!locomotive && !wagons.length) return null;
+ if (!locos.length && !wagons.length) return null;
return (
Locomotive load ·{" "}
{stats.totalTare > 0
- ? `${stats.grossWeight}T of ${locomotive?.maxPullWeightTons}T (${stats.totalWeight}T cargo + ${stats.totalTare}T tare)`
- : `${stats.totalWeight}T of ${locomotive?.maxPullWeightTons}T`}
+ ? `${stats.grossWeight}T of ${stats.pullLimit}T (${stats.totalWeight}T cargo + ${stats.totalTare}T tare)`
+ : `${stats.totalWeight}T of ${stats.pullLimit}T`}
95 ? "red.7" : "edr-green.7"}>
@@ -702,13 +722,11 @@ export function TrainCompositionDiagram({
{carIndex > 0 ? : null}
{car.kind === "loco" ? (
- locomotive ? (
-
- ) : null
+
) : (
)}
diff --git a/apps/edr-freight-web/backoffice/src/components/wagons/WagonTransferRequestsModal.tsx b/apps/edr-freight-web/backoffice/src/components/wagons/WagonTransferRequestsModal.tsx
index 01e65deb2..f17c74d9a 100644
--- a/apps/edr-freight-web/backoffice/src/components/wagons/WagonTransferRequestsModal.tsx
+++ b/apps/edr-freight-web/backoffice/src/components/wagons/WagonTransferRequestsModal.tsx
@@ -10,6 +10,8 @@ import {
Modal,
ScrollArea,
Stack,
+ Switch,
+ Tabs,
Text,
ThemeIcon,
} from "@mantine/core";
@@ -17,6 +19,7 @@ import { useMutation, useQuery } from "@tanstack/react-query";
import {
ArrowRight,
ChevronLeft,
+ History,
Inbox,
PackageCheck,
Warehouse,
@@ -25,8 +28,13 @@ import {
import { useMemo, useState } from "react";
import { api } from "@/services/api";
+import { useAuth } from "@/auth/useAuth";
+import { FREIGHT_PERMS, hasPermission } from "@/lib/permissions";
import { useToast } from "@/hooks/use-toast";
-import type { WagonTransferRequest } from "@/services/wagon.service";
+import type {
+ WagonMovementRecord,
+ WagonTransferRequest,
+} from "@/services/wagon.service";
export interface WagonTransferRequestsModalProps {
opened: boolean;
@@ -57,16 +65,172 @@ const RequestSummary = ({ r }: { r: WagonTransferRequest }) => (
);
+const STATUS_COLOR: Record = {
+ PENDING: "gray",
+ FULFILLED: "teal",
+ CANCELLED: "red",
+};
+
+const fmtDateTime = (iso: string) =>
+ new Date(iso).toLocaleString("en-GB", {
+ day: "numeric",
+ month: "short",
+ hour: "2-digit",
+ minute: "2-digit",
+ hour12: false,
+ });
+
+/**
+ * Per-user transfer history. A staffer sees their OWN activity — the requests
+ * they filed or fulfilled, and the individual wagons they moved. Holders of
+ * `transfer_history_all` get an "All staff" toggle that widens the view; the
+ * backend enforces the scope regardless of the toggle.
+ */
+function HistoryPanel({ opened }: { opened: boolean }) {
+ const { user } = useAuth();
+ const canSeeAll = hasPermission(
+ user,
+ FREIGHT_PERMS.wagons.transferHistoryAll,
+ );
+ const myId = (user as { id?: string } | null | undefined)?.id;
+ const [allStaff, setAllStaff] = useState(false);
+ const scopeAll = canSeeAll && allStaff;
+
+ const mine = useQuery({
+ ...api.wagonTransferRequests.history.queryOptions(),
+ enabled: opened && !scopeAll,
+ });
+ const all = useQuery({
+ ...api.wagonTransferRequests.historyAll.queryOptions({ input: {} }),
+ enabled: opened && scopeAll,
+ });
+ const source = scopeAll ? all : mine;
+ const requests = source.data?.requests ?? [];
+ const movements: WagonMovementRecord[] = source.data?.movements ?? [];
+
+ const roleBadge = (r: WagonTransferRequest) => {
+ if (myId && r.fulfilledByUserId === myId)
+ return (
+
+ fulfilled
+
+ );
+ if (myId && r.requestedByUserId === myId)
+ return (
+
+ requested
+
+ );
+ return null;
+ };
+
+ return (
+
+ {canSeeAll ? (
+
+ setAllStaff(e.currentTarget.checked)}
+ label="All staff"
+ color="edr-green"
+ />
+
+ ) : null}
+
+ {source.isLoading ? (
+
+
+
+ ) : (
+ <>
+
+ >
+ )}
+
+ );
+}
+
/**
* OCC fulfilment queue for wagon-transfer requests. Lists PENDING requests; open
* one to hand-pick exactly the requested number of wagons from the source yard
* (of the requested type) and execute the move, or cancel the request.
+ * A second tab shows per-user transfer history.
*/
const WagonTransferRequestsModal = ({
opened,
onClose,
}: WagonTransferRequestsModalProps) => {
const { toast } = useToast();
+ const [tab, setTab] = useState("queue");
const [active, setActive] = useState(null);
const [picked, setPicked] = useState>(new Set());
@@ -175,6 +339,17 @@ const WagonTransferRequestsModal = ({
}
>
+
+
+ }>
+ Queue
+
+ }>
+ History
+
+
+
+
{!active ? (
// ---- Pending queue ----
isLoading ? (
@@ -337,6 +512,12 @@ const WagonTransferRequestsModal = ({
)}
+
+
+
+
+
+
);
};
diff --git a/apps/edr-freight-web/backoffice/src/lib/permissions.ts b/apps/edr-freight-web/backoffice/src/lib/permissions.ts
index 92fe85ad7..9bf9aab6e 100644
--- a/apps/edr-freight-web/backoffice/src/lib/permissions.ts
+++ b/apps/edr-freight-web/backoffice/src/lib/permissions.ts
@@ -106,6 +106,9 @@ export const FREIGHT_PERMS = {
create: "edr_freight_app:wagons:create",
update: "edr_freight_app:wagons:update",
delete: "edr_freight_app:wagons:delete",
+ transferRequest: "edr_freight_app:wagons:transfer_request",
+ transferFulfill: "edr_freight_app:wagons:transfer_fulfill",
+ transferHistoryAll: "edr_freight_app:wagons:transfer_history_all",
},
trains: {
view: "edr_freight_app:trains:view",
diff --git a/apps/edr-freight-web/backoffice/src/pages/contracts/ContractClearanceListPage.tsx b/apps/edr-freight-web/backoffice/src/pages/contracts/ContractClearanceListPage.tsx
index 142173298..91d944ffc 100644
--- a/apps/edr-freight-web/backoffice/src/pages/contracts/ContractClearanceListPage.tsx
+++ b/apps/edr-freight-web/backoffice/src/pages/contracts/ContractClearanceListPage.tsx
@@ -1,4 +1,11 @@
-import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
+import {
+ Fragment,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+ type ReactNode,
+} from "react";
import { useNavigate } from "react-router-dom";
import {
ActionIcon,
@@ -75,6 +82,8 @@ interface ClearanceRow {
freightType: string;
originLabel: string;
destinationLabel: string;
+ /** Full ordered corridor across the contract's route legs (origin → … → destination). */
+ routeStops: string[];
contractKind: string;
serviceTypeName: string;
customs: boolean;
@@ -93,6 +102,25 @@ function yardLabel(
return yard.label ?? yard.name ?? yard.code ?? fallback;
}
+/**
+ * Chain the contract's ordered route legs into one corridor of stops —
+ * origin of the first leg, then each leg's destination (Djibouti → Adama →
+ * Dire Dawa). A leg whose origin differs from the previous destination inserts
+ * that stop too, so gapped route lists stay readable.
+ */
+function contractRouteStops(routes: Freight.IContractRoute[]): string[] {
+ const stops: string[] = [];
+ for (const r of routes) {
+ const origin = yardLabel(r.originYard);
+ const destination = yardLabel(r.destinationYard);
+ if (stops.length === 0 || stops[stops.length - 1] !== origin) {
+ stops.push(origin);
+ }
+ stops.push(destination);
+ }
+ return stops;
+}
+
function toClearanceRow(contract: Freight.IContract): ClearanceRow {
const routes = [...(contract.routes ?? [])].sort(
(a, b) => a.sortOrder - b.sortOrder,
@@ -109,6 +137,7 @@ function toClearanceRow(contract: Freight.IContract): ClearanceRow {
freightType: contract.freightType ?? "—",
originLabel: yardLabel(first?.originYard),
destinationLabel: yardLabel(last?.destinationYard),
+ routeStops: contractRouteStops(routes),
contractKind: contract.contractKind,
serviceTypeName: contract.serviceType?.serviceName ?? "—",
customs:
@@ -412,14 +441,23 @@ export default function ContractClearanceListPage() {
const r = row.original;
return (
-
-
- {r.originLabel}
-
-
-
- {r.destinationLabel}
-
+
+ {(r.routeStops.length >= 2
+ ? r.routeStops
+ : [r.originLabel, r.destinationLabel]
+ ).map((stop, i) => (
+
+ {i > 0 ? (
+
+ ) : null}
+
+ {stop}
+
+
+ ))}
@@ -638,6 +676,11 @@ export default function ContractClearanceListPage() {
`/dashboard/contracts/${row.contractId}/bookings/${row.id}/complete`,
)
}
+ onRebook={(row) =>
+ navigate(
+ `/dashboard/contracts/${row.contractId}/create-booking?copyFrom=${row.id}`,
+ )
+ }
onViewContract={(contractId) =>
navigate(`/dashboard/contracts/clearance/${contractId}`)
}
@@ -731,6 +774,7 @@ function ShipmentBookingsTable({
canCreateBooking,
onOpen,
onCreateBooking,
+ onRebook,
onViewContract,
}: {
rows: ShipmentBookingRow[];
@@ -739,6 +783,7 @@ function ShipmentBookingsTable({
canCreateBooking: boolean;
onOpen: (id: string) => void;
onCreateBooking: (row: ShipmentBookingRow) => void;
+ onRebook: (row: ShipmentBookingRow) => void;
onViewContract: (contractId: string) => void;
}) {
// A bare initiated instance that has cleared but not yet been created by GL.
@@ -748,6 +793,14 @@ function ShipmentBookingsTable({
!r.bookingCreated &&
r.status === "CLEARANCE_READY";
+ // A customs shipment whose booking lost its slot — GL rebooks it (customer
+ // can't self-rebook a customs booking). Copies the expired booking's cargo.
+ const isRebookable = (r: ShipmentBookingRow) =>
+ canCreateBooking &&
+ Boolean(r.contractId) &&
+ r.customs &&
+ r.status === "EXPIRED";
+
const columns = useMemo[]>(
() => [
{
@@ -877,6 +930,7 @@ function ShipmentBookingsTable({
cell: ({ row }) => {
const r = row.original;
const bookable = isBookable(r);
+ const rebookable = isRebookable(r);
return (
) : null}
+ {rebookable ? (
+ }
+ onClick={() => onRebook(r)}
+ >
+ Rebook
+
+ ) : null}
{composition.editable ? (
@@ -297,6 +314,12 @@ export default function TrainBuilderDetailPage() {
onClose={() => setLocoModalOpen(false)}
/>
+ setYardModalOpen(false)}
+ />
+
setDisbandOpen(false)}
diff --git a/apps/edr-freight-web/backoffice/src/pages/trainBuilder/TrainBuilderListPage.tsx b/apps/edr-freight-web/backoffice/src/pages/trainBuilder/TrainBuilderListPage.tsx
index 9799bf6e4..53bd1a818 100644
--- a/apps/edr-freight-web/backoffice/src/pages/trainBuilder/TrainBuilderListPage.tsx
+++ b/apps/edr-freight-web/backoffice/src/pages/trainBuilder/TrainBuilderListPage.tsx
@@ -183,7 +183,7 @@ export default function TrainBuilderListPage() {
meta: { headerClassName, cellClassName },
cell: ({ row }) => (
- {row.original.wagonCount} wagons · {row.original.maxGrossTons}T ·{" "}
+ {row.original.wagonCount} wagons · {row.original.totalTareTons}T tare ·{" "}
{row.original.totalLengthMeters}m
),
diff --git a/apps/edr-freight-web/backoffice/src/pages/trainScheduling/BatchScheduleDetailPage.tsx b/apps/edr-freight-web/backoffice/src/pages/trainScheduling/BatchScheduleDetailPage.tsx
index ae75debb1..0f80e423a 100644
--- a/apps/edr-freight-web/backoffice/src/pages/trainScheduling/BatchScheduleDetailPage.tsx
+++ b/apps/edr-freight-web/backoffice/src/pages/trainScheduling/BatchScheduleDetailPage.tsx
@@ -838,6 +838,12 @@ export default function BatchScheduleDetailPage() {
}).format(new Date(data.scheduleDate)) + " EAT"
: "No date"}
+ {data.train ? (
+ }>
+ Train {data.train.code}
+ {data.train.trainName ? ` — ${data.train.trainName}` : ""}
+
+ ) : null}
{data.locomotive ? (
}>
Loco {data.locomotive.code} ·{" "}
diff --git a/apps/edr-freight-web/backoffice/src/pages/trainScheduling/TrainScheduleV2DetailPage.tsx b/apps/edr-freight-web/backoffice/src/pages/trainScheduling/TrainScheduleV2DetailPage.tsx
index f4cd3be02..c9c4a042a 100644
--- a/apps/edr-freight-web/backoffice/src/pages/trainScheduling/TrainScheduleV2DetailPage.tsx
+++ b/apps/edr-freight-web/backoffice/src/pages/trainScheduling/TrainScheduleV2DetailPage.tsx
@@ -757,13 +757,14 @@ export default function TrainScheduleV2DetailPage() {
1 ? "Locomotives" : "Locomotive",
value: locomotives.length
diff --git a/apps/edr-freight-web/backoffice/src/services/api.ts b/apps/edr-freight-web/backoffice/src/services/api.ts
index af6263e58..d0e14d4a5 100644
--- a/apps/edr-freight-web/backoffice/src/services/api.ts
+++ b/apps/edr-freight-web/backoffice/src/services/api.ts
@@ -200,6 +200,7 @@ import {
type WagonMovementRecord,
type WagonTransferRequest,
type CreateTransferRequestPayload,
+ type TransferHistory,
} from "./wagon.service";
import { warehouseService } from "./warehouse.service";
@@ -1701,6 +1702,21 @@ export const api = {
undefined,
() => [["wagonTransferRequests"]],
),
+
+ history: endpoint(
+ "wagonTransferRequests",
+ "history",
+ () => wagonTransferRequestService.myHistory().then((r) => r.data),
+ () => ["wagonTransferRequests", "history", "mine"],
+ ),
+
+ historyAll: endpoint<{ userId?: string }, TransferHistory>(
+ "wagonTransferRequests",
+ "historyAll",
+ ({ userId }) =>
+ wagonTransferRequestService.allHistory(userId).then((r) => r.data),
+ ({ userId }) => ["wagonTransferRequests", "history", "all", userId ?? ""],
+ ),
},
trains: {
@@ -1781,6 +1797,15 @@ export const api = {
() => TRAIN_BUILDER_INVALIDATIONS,
),
+ setYard: endpoint<{ id: string; currentYardId: string }, TrainComposition>(
+ "train-builder",
+ "setYard",
+ ({ id, currentYardId }) =>
+ trainBuilderService.setYard(id, currentYardId).then((r) => r.data),
+ undefined,
+ () => TRAIN_BUILDER_INVALIDATIONS,
+ ),
+
assignWagons: endpoint<{ id: string; wagonIds: string[] }, TrainComposition>(
"train-builder",
"assignWagons",
diff --git a/apps/edr-freight-web/backoffice/src/services/trainBuilder.service.ts b/apps/edr-freight-web/backoffice/src/services/trainBuilder.service.ts
index f94bd6ff7..e6c462992 100644
--- a/apps/edr-freight-web/backoffice/src/services/trainBuilder.service.ts
+++ b/apps/edr-freight-web/backoffice/src/services/trainBuilder.service.ts
@@ -26,7 +26,7 @@ export interface BuiltTrainSummary {
currentYard: YardRefLite | null;
locomotives: Array<{ id: string; code: string; name: string | null }>;
wagonCount: number;
- maxGrossTons: number;
+ totalTareTons: number;
totalLengthMeters: number;
maxPullWeightTons: number;
}
@@ -63,12 +63,15 @@ export interface TrainCompositionWagon {
export interface TrainCompositionTotals {
wagonCount: number;
totalTareTons: number;
+ /** Informational only — building never checks against full capacity. */
totalCapacityTons: number;
- maxGrossTons: number;
totalLengthMeters: number;
maxPullWeightTons: number;
maxTrainLengthMeters: number;
- weightUtilizationPct: number | null;
+ /** Cargo the locomotives can still haul once pulling the empty consist. */
+ payloadCapacityTons: number;
+ /** Share of the haul limit consumed by the empty wagons alone. */
+ tareUtilizationPct: number | null;
lengthUtilizationPct: number | null;
}
@@ -126,7 +129,7 @@ export interface AvailableTrain {
currentYard: YardRefLite | null;
locomotives: Array<{ id: string; code: string; name: string | null }>;
wagonCount: number;
- maxGrossTons: number;
+ totalTareTons: number;
totalLengthMeters: number;
maxPullWeightTons: number;
atOriginYard: boolean;
@@ -157,6 +160,9 @@ export const trainBuilderService = {
build: (payload: BuildTrainPayload) => apiClient.post(BASE, payload),
setLocomotives: (id: string, locomotiveIds: string[]) =>
apiClient.put(`${BASE}/${id}/locomotives`, { locomotiveIds }),
+ /** Relocate the train — coupled locomotives and wagons move with it. */
+ setYard: (id: string, currentYardId: string) =>
+ apiClient.patch(`${BASE}/${id}/yard`, { currentYardId }),
assignWagons: (id: string, wagonIds: string[]) =>
apiClient.post(`${BASE}/${id}/wagons`, { wagonIds }),
removeWagon: (id: string, wagonId: string) =>
diff --git a/apps/edr-freight-web/backoffice/src/services/wagon.service.ts b/apps/edr-freight-web/backoffice/src/services/wagon.service.ts
index 6464b94f5..e818467f5 100644
--- a/apps/edr-freight-web/backoffice/src/services/wagon.service.ts
+++ b/apps/edr-freight-web/backoffice/src/services/wagon.service.ts
@@ -55,9 +55,12 @@ export interface WagonMovementRecord {
bookingId: string | null;
kind: Freight.WagonMovementKind;
movedByUserId: string | null;
+ /** The transfer request this move fulfilled, when one drove it. */
+ transferRequestId: string | null;
occurredAt: string;
note: string | null;
createdAt: string;
+ wagon?: { id: string; wagonNumber?: string } | null;
}
export const wagonService = {
@@ -120,11 +123,25 @@ export interface CreateTransferRequestPayload {
note?: string;
}
+/** Per-user activity: requests filed/fulfilled + the wagons physically moved. */
+export interface TransferHistory {
+ requests: WagonTransferRequest[];
+ movements: WagonMovementRecord[];
+}
+
export const wagonTransferRequestService = {
list: (status?: Freight.WagonTransferRequestStatus) =>
apiClient.get(
`/wagon-transfer-requests${status ? `?status=${status}` : ''}`,
),
+ /** The caller's own history (both roles: requests they filed and fulfilled). */
+ myHistory: () =>
+ apiClient.get('/wagon-transfer-requests/history'),
+ /** Admin: any/all staff's history (optional userId filter). */
+ allHistory: (userId?: string) =>
+ apiClient.get(
+ `/wagon-transfer-requests/history/all${userId ? `?userId=${userId}` : ''}`,
+ ),
getById: (id: string) =>
apiClient.get(`/wagon-transfer-requests/${id}`),
create: (data: CreateTransferRequestPayload) =>
diff --git a/apps/edr-freight-web/backoffice/src/types/trainScheduling.ts b/apps/edr-freight-web/backoffice/src/types/trainScheduling.ts
index 154db034c..ee301b970 100644
--- a/apps/edr-freight-web/backoffice/src/types/trainScheduling.ts
+++ b/apps/edr-freight-web/backoffice/src/types/trainScheduling.ts
@@ -309,6 +309,12 @@ export interface BatchBoardSchedule {
docReviewEndsAt: string | null;
paymentPhaseEndsAt: string | null;
bookingCycleNo: number;
+ /** Built train (Train Builder) behind this departure, when scheduled by train. */
+ train: {
+ id: string;
+ code: string;
+ trainName: string | null;
+ } | null;
locomotive: {
code: string;
name: string | null;
@@ -417,6 +423,8 @@ export interface BatchBoardScheduleDetail {
docReviewEndsAt: string | null;
paymentPhaseEndsAt: string | null;
bookingCycleNo: number;
+ /** Built train (Train Builder) behind this departure, when scheduled by train. */
+ train: BatchBoardSchedule["train"];
locomotive: BatchBoardSchedule["locomotive"];
capacity: BatchBoardSchedule["capacity"];
counts: BatchBoardSchedule["counts"];
@@ -511,6 +519,12 @@ export interface TrainScheduleDetail {
deferredBookings?: DeferredBookingRow[];
freightType?: FreightType | null;
trainNumber?: string | null;
+ /** Built train (Train Builder) behind this departure, when scheduled by train. */
+ train?: {
+ id: string;
+ code: string;
+ trainName?: string | null;
+ } | null;
direction?: string | null;
/** True when this schedule needs loading confirmed before dispatch (import-Djibouti). */
requiresLoadingConfirmation?: boolean;
diff --git a/apps/edr-freight-web/portal/src/pages/MyPortalPage/components/UpcomingWindowsSection.tsx b/apps/edr-freight-web/portal/src/pages/MyPortalPage/components/UpcomingWindowsSection.tsx
index ad2d5ace9..f9a3dd246 100644
--- a/apps/edr-freight-web/portal/src/pages/MyPortalPage/components/UpcomingWindowsSection.tsx
+++ b/apps/edr-freight-web/portal/src/pages/MyPortalPage/components/UpcomingWindowsSection.tsx
@@ -1,5 +1,5 @@
import { ActionIcon, Box, Group, Skeleton, Stack, Text } from "@mantine/core";
-import { memo, useMemo, useState } from "react";
+import { Fragment, memo, useMemo, useState } from "react";
import {
ArrowRight,
CalendarClock,
@@ -8,6 +8,7 @@ import {
} from "lucide-react";
import { CountdownTimer } from "@edr/ui-common";
import type { MyBookingWindow } from "@/services/bookings.service";
+import { windowRouteStops } from "@/pages/contracts/booking-window";
import { Card } from "./Card";
const INK = "#10202F";
@@ -284,14 +285,21 @@ export const UpcomingWindowsSection = memo(function UpcomingWindowsSection({
}}
>
-
-
- {w.origin ?? "—"}
-
-
-
- {w.destination ?? "—"}
-
+
+ {windowRouteStops(w).map((stop, i) => (
+
+ {i > 0 ? (
+
+ ) : null}
+
+ {stop}
+
+
+ ))}
{w.reference && (
navigate("/support"),
}}
/>
@@ -181,14 +186,18 @@ export function ReadonlyBookingView({
: "This booking process has been terminated."
}
reason={booking.latestChangeRequestNote}
- onRebook={onRebook}
+ onRebook={canSelfRebook ? onRebook : undefined}
/>
) : isExpired ? (
) : isPendingConsolidation ? (
-
-
- {w.origin ?? "—"}
-
-
-
- {w.destination ?? "—"}
-
+
+ {windowRouteStops(w).map((stop, i) => (
+
+ {i > 0 ? (
+
+ ) : null}
+
+ {stop}
+
+
+ ))}
diff --git a/apps/edr-freight-web/portal/src/pages/contracts/NewShipmentRequestPage.tsx b/apps/edr-freight-web/portal/src/pages/contracts/NewShipmentRequestPage.tsx
index c0bfbfc4c..0b5c1796c 100644
--- a/apps/edr-freight-web/portal/src/pages/contracts/NewShipmentRequestPage.tsx
+++ b/apps/edr-freight-web/portal/src/pages/contracts/NewShipmentRequestPage.tsx
@@ -26,7 +26,12 @@ export default function NewShipmentRequestPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [scheduledDate, setScheduledDate] = useState("");
- const [quantity, setQuantity] = useState(1);
+ // Container contracts: one quantity per enabled size (e.g. 20ft + 40ft).
+ const [qtyBySize, setQtyBySize] = useState>(
+ {},
+ );
+ // Bulk contracts: a single amount — tons (PER_TON) or item count (PER_ITEM).
+ const [bulkAmount, setBulkAmount] = useState("");
const [notes, setNotes] = useState("");
const { data: contract, isLoading } = useQuery({
@@ -76,6 +81,22 @@ export default function NewShipmentRequestPage() {
contract.contractKind === "GENERAL" &&
(contract.serviceType?.includesCustoms ?? contract.customsClearingEnabled);
+ // Only the container sizes the contract was scoped for (20ft, 40ft, or both).
+ const SIZE_ORDER = ["20ft", "40ft"];
+ const enabledSizes = SIZE_ORDER.filter((s) =>
+ contract.cargoScope?.some(
+ (l) => (l.containerSize ?? "").toLowerCase() === s,
+ ),
+ );
+ // A CONTAINER contract should always carry scope lines; fall back to both.
+ const sizes = enabledSizes.length ? enabledSizes : SIZE_ORDER;
+
+ // Bulk: pick the bulk scope line and read how it's measured.
+ const bulkScope =
+ contract.cargoScope?.find((l) => !l.containerSize) ??
+ contract.cargoScope?.[0];
+ const isPerItem = bulkScope?.cargoType?.unitOfMeasure === "PER_ITEM";
+
const handleSubmit = () => {
const dto: Freight.CreateBookingRequestDto = {
contractRouteId: route?.id,
@@ -84,17 +105,24 @@ export default function NewShipmentRequestPage() {
};
if (isContainer) {
- const size = contract.cargoScope?.[0]?.containerSize ?? "20FT";
- dto.containers = [
- {
- containerSize: size,
- quantity: Number(quantity) || 1,
- },
- ];
+ // One line per size the user filled; 0 (or blank) sizes are dropped.
+ const containers = sizes
+ .map((size) => ({ containerSize: size, quantity: Number(qtyBySize[size]) || 0 }))
+ .filter((line) => line.quantity > 0);
+ if (containers.length === 0) {
+ toast.error("Enter a quantity for at least one container size");
+ return;
+ }
+ dto.containers = containers;
} else {
+ const amount = Number(bulkAmount) || 0;
+ if (amount <= 0) {
+ toast.error(isPerItem ? "Enter the number of items" : "Enter the cargo weight");
+ return;
+ }
dto.bulk = {
- cargoTypeId: contract.cargoScope?.[0]?.cargoTypeId ?? null,
- cargoWeightTons: Number(quantity) || undefined,
+ cargoTypeId: bulkScope?.cargoTypeId ?? null,
+ ...(isPerItem ? { itemCount: amount } : { cargoWeightTons: amount }),
};
}
@@ -131,17 +159,47 @@ export default function NewShipmentRequestPage() {
/>
)}
-
+ {isContainer ? (
+
+ {sizes.map((size) => (
+
+ setQtyBySize((prev) => ({ ...prev, [size]: v }))
+ }
+ min={0}
+ allowDecimal={false}
+ />
+ ))}
+ {sizes.length > 1 ? (
+
+ Enter a quantity for each size you need — leave a size at 0 if
+ you don't need it.
+
+ ) : null}
+ {hasCustoms ? (
+
+ Global Logistics schedules the shipment date during customs
+ clearance — you only state the quantity.
+
+ ) : null}
+
+ ) : (
+
+ )}
{capacity?.length ? (
diff --git a/apps/edr-freight-web/portal/src/pages/contracts/booking-window.ts b/apps/edr-freight-web/portal/src/pages/contracts/booking-window.ts
index ab25284ba..1f0825f57 100644
--- a/apps/edr-freight-web/portal/src/pages/contracts/booking-window.ts
+++ b/apps/edr-freight-web/portal/src/pages/contracts/booking-window.ts
@@ -25,6 +25,16 @@ export function hasOpenWindow(windows: MyBookingWindow[]): boolean {
return windows.some((w) => w.isOpenNow);
}
+/**
+ * Full ordered corridor for a window — every stop from origin through the
+ * intermediate milestones to the destination. Falls back to origin/destination
+ * when the backend sends no milestone chain (older schedules, routeless windows).
+ */
+export function windowRouteStops(w: MyBookingWindow): string[] {
+ if (w.routeStations && w.routeStations.length >= 2) return w.routeStations;
+ return [w.origin ?? "—", w.destination ?? "—"];
+}
+
/**
* The next upcoming (not-yet-open) window the customer should come back for —
* the one that OPENS soonest from now. Two guards matter here:
diff --git a/apps/edr-freight-web/portal/src/services/bookings.service.ts b/apps/edr-freight-web/portal/src/services/bookings.service.ts
index 1128b0883..af2c8e4a5 100644
--- a/apps/edr-freight-web/portal/src/services/bookings.service.ts
+++ b/apps/edr-freight-web/portal/src/services/bookings.service.ts
@@ -94,6 +94,12 @@ export interface MyBookingWindow {
departureDate: string;
origin: string | null;
destination: string | null;
+ /**
+ * Full ordered corridor for the window's route — origin, every intermediate
+ * milestone stop, then destination (e.g. Djibouti → Adama → Dire Dawa).
+ * Falls back to [origin, destination] when the route has no milestones.
+ */
+ routeStations: string[];
}
export interface GeneratePriceResponse {
diff --git a/packages/types/src/freight/index.ts b/packages/types/src/freight/index.ts
index 9addde7dc..39e8985ee 100644
--- a/packages/types/src/freight/index.ts
+++ b/packages/types/src/freight/index.ts
@@ -327,6 +327,8 @@ export interface IWagonMovement extends BaseEntity {
bookingId?: string | null;
kind: WagonMovementKind;
movedByUserId?: string | null;
+ /** The transfer request this move fulfilled, when it came from one. */
+ transferRequestId?: string | null;
occurredAt: string;
note?: string | null;
}
From ae07b461f095323233d90ae1331f7ca696128fdb Mon Sep 17 00:00:00 2001
From: Yonas Tewabe
Date: Tue, 14 Jul 2026 16:30:23 +0300
Subject: [PATCH 08/13] Update docker-compose.yaml
---
docker-compose.yaml | 2 --
1 file changed, 2 deletions(-)
diff --git a/docker-compose.yaml b/docker-compose.yaml
index c0b58b44c..7637c500a 100644
--- a/docker-compose.yaml
+++ b/docker-compose.yaml
@@ -24,8 +24,6 @@ services:
dockerfile: apps/edr-gps-tracker/Dockerfile
secrets:
- npmrc
- depends_on:
- - freight-api
ports:
- "${GT06_TCP_PORT:-5023}:5023"
environment:
From 5cffe2860cd279c9c01d6efed8b28fd8422dc73b Mon Sep 17 00:00:00 2001
From: Marshal
Date: Tue, 14 Jul 2026 13:49:39 +0000
Subject: [PATCH 09/13] fix train builder and consolidation
---
...70000000000-ScheduleWagonAdjustmentLogs.ts | 50 +++
.../schedule-wagon-adjustment-log.entity.ts | 38 ++
.../dto/adjust-schedule-consist.dto.ts | 26 ++
.../train-scheduling.controller.ts | 29 ++
.../train-scheduling.service.ts | 315 +++++++++++++-
.../modules/trains/train-builder.service.ts | 71 +++-
.../trainScheduling/AdjustConsistModal.tsx | 396 ++++++++++++++++++
.../src/pages/bookings/NewBookingPage.tsx | 32 +-
.../trainBuilder/TrainBuilderDetailPage.tsx | 4 +-
.../BatchScheduleDetailPage.tsx | 19 +
.../TrainScheduleV2DetailPage.tsx | 20 +
.../backoffice/src/services/api.ts | 26 ++
.../src/services/trainBuilder.service.ts | 67 +++
.../new-booking-form/step5-cargo-details.tsx | 16 +-
14 files changed, 1092 insertions(+), 17 deletions(-)
create mode 100644 apps/edr-freight-api/src/migrations/2170000000000-ScheduleWagonAdjustmentLogs.ts
create mode 100644 apps/edr-freight-api/src/modules/train-schedules/entities/schedule-wagon-adjustment-log.entity.ts
create mode 100644 apps/edr-freight-api/src/modules/train-scheduling/dto/adjust-schedule-consist.dto.ts
create mode 100644 apps/edr-freight-web/backoffice/src/components/trainScheduling/AdjustConsistModal.tsx
diff --git a/apps/edr-freight-api/src/migrations/2170000000000-ScheduleWagonAdjustmentLogs.ts b/apps/edr-freight-api/src/migrations/2170000000000-ScheduleWagonAdjustmentLogs.ts
new file mode 100644
index 000000000..7fecfccbb
--- /dev/null
+++ b/apps/edr-freight-api/src/migrations/2170000000000-ScheduleWagonAdjustmentLogs.ts
@@ -0,0 +1,50 @@
+import { MigrationInterface, QueryRunner } from 'typeorm';
+
+/**
+ * Consist adjustments from a schedule: staff can trim free wagons off a built
+ * train when their tare pushes gross weight over the locomotives' pull limit
+ * (incl. overage tolerance), or couple extra yard wagons on while weight and
+ * length headroom remain. Each add/remove is logged here so the schedule keeps
+ * an auditable history; the built train itself is updated in place.
+ *
+ * Plain columns (no FKs) so the history survives wagon/train deletion.
+ *
+ * NOTE: the shared dev DB has no applied migration history, so this is also
+ * hand-applied there. IF NOT EXISTS keeps that idempotent.
+ */
+export class ScheduleWagonAdjustmentLogs2170000000000 implements MigrationInterface {
+ name = 'ScheduleWagonAdjustmentLogs2170000000000';
+
+ public async up(queryRunner: QueryRunner): Promise {
+ await queryRunner.query(`
+ CREATE TABLE IF NOT EXISTS freight.schedule_wagon_adjustment_logs (
+ id uuid NOT NULL DEFAULT uuid_generate_v4(),
+ train_schedule_id uuid NOT NULL,
+ train_id uuid NOT NULL,
+ action varchar(10) NOT NULL,
+ wagon_id uuid NOT NULL,
+ wagon_number varchar(50) NOT NULL,
+ adjusted_by_user_id uuid,
+ occurred_at timestamptz NOT NULL DEFAULT now(),
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ deleted_at timestamptz,
+ CONSTRAINT "PK_schedule_wagon_adjustment_logs" PRIMARY KEY (id)
+ );
+ `);
+ await queryRunner.query(`
+ CREATE INDEX IF NOT EXISTS "IDX_swal_train_schedule_id"
+ ON freight.schedule_wagon_adjustment_logs (train_schedule_id);
+ `);
+ await queryRunner.query(`
+ CREATE INDEX IF NOT EXISTS "IDX_swal_train_id"
+ ON freight.schedule_wagon_adjustment_logs (train_id);
+ `);
+ }
+
+ public async down(queryRunner: QueryRunner): Promise {
+ await queryRunner.query(`DROP INDEX IF EXISTS freight."IDX_swal_train_id";`);
+ await queryRunner.query(`DROP INDEX IF EXISTS freight."IDX_swal_train_schedule_id";`);
+ await queryRunner.query(`DROP TABLE IF EXISTS freight.schedule_wagon_adjustment_logs;`);
+ }
+}
diff --git a/apps/edr-freight-api/src/modules/train-schedules/entities/schedule-wagon-adjustment-log.entity.ts b/apps/edr-freight-api/src/modules/train-schedules/entities/schedule-wagon-adjustment-log.entity.ts
new file mode 100644
index 000000000..485d29452
--- /dev/null
+++ b/apps/edr-freight-api/src/modules/train-schedules/entities/schedule-wagon-adjustment-log.entity.ts
@@ -0,0 +1,38 @@
+import { BaseEntity } from '@edr/api-common';
+import { Column, Entity, Index } from 'typeorm';
+
+export const WAGON_ADJUSTMENT_ACTIONS = ['ADD', 'REMOVE'] as const;
+export type WagonAdjustmentAction = (typeof WAGON_ADJUSTMENT_ACTIONS)[number];
+
+/**
+ * History row for a consist adjustment made from a schedule: staff coupled a
+ * wagon onto (ADD) or detached one from (REMOVE) the schedule's built train —
+ * e.g. trimming free wagons whose tare pushed gross weight over the
+ * locomotives' pull limit. Plain columns (no FK relations) so the history
+ * survives the wagon or train being deleted later.
+ */
+@Entity({ schema: 'freight', name: 'schedule_wagon_adjustment_logs' })
+@Index(['trainScheduleId'])
+@Index(['trainId'])
+export class ScheduleWagonAdjustmentLog extends BaseEntity {
+ @Column({ name: 'train_schedule_id', type: 'uuid' })
+ trainScheduleId!: string;
+
+ @Column({ name: 'train_id', type: 'uuid' })
+ trainId!: string;
+
+ @Column({ name: 'action', type: 'varchar', length: 10 })
+ action!: WagonAdjustmentAction;
+
+ @Column({ name: 'wagon_id', type: 'uuid' })
+ wagonId!: string;
+
+ @Column({ name: 'wagon_number', type: 'varchar', length: 50 })
+ wagonNumber!: string;
+
+ @Column({ name: 'adjusted_by_user_id', type: 'uuid', nullable: true })
+ adjustedByUserId!: string | null;
+
+ @Column({ name: 'occurred_at', type: 'timestamptz', default: () => 'now()' })
+ occurredAt!: Date;
+}
diff --git a/apps/edr-freight-api/src/modules/train-scheduling/dto/adjust-schedule-consist.dto.ts b/apps/edr-freight-api/src/modules/train-scheduling/dto/adjust-schedule-consist.dto.ts
new file mode 100644
index 000000000..e031bf9f0
--- /dev/null
+++ b/apps/edr-freight-api/src/modules/train-scheduling/dto/adjust-schedule-consist.dto.ts
@@ -0,0 +1,26 @@
+import { ApiPropertyOptional } from '@nestjs/swagger';
+import { IsArray, IsOptional, IsUUID } from 'class-validator';
+
+export class AdjustScheduleConsistDto {
+ @ApiPropertyOptional({
+ type: [String],
+ format: 'uuid',
+ description:
+ "AVAILABLE wagons from the train's current yard to couple onto the built train (blocked when they push gross weight or length past the locomotive limits incl. tolerance).",
+ })
+ @IsOptional()
+ @IsArray()
+ @IsUUID('all', { each: true })
+ addWagonIds?: string[];
+
+ @ApiPropertyOptional({
+ type: [String],
+ format: 'uuid',
+ description:
+ 'Free (unloaded) wagons to detach permanently from the built train — e.g. trimming tare when gross weight exceeds the pull limit.',
+ })
+ @IsOptional()
+ @IsArray()
+ @IsUUID('all', { each: true })
+ removeWagonIds?: string[];
+}
diff --git a/apps/edr-freight-api/src/modules/train-scheduling/train-scheduling.controller.ts b/apps/edr-freight-api/src/modules/train-scheduling/train-scheduling.controller.ts
index f8cc7e3d1..c6e22589f 100644
--- a/apps/edr-freight-api/src/modules/train-scheduling/train-scheduling.controller.ts
+++ b/apps/edr-freight-api/src/modules/train-scheduling/train-scheduling.controller.ts
@@ -39,6 +39,7 @@ import {
UploadImportDjiboutiDocumentDto,
} from "./dto/import-djibouti-operation.dto";
import { AvailableLocomotivesQueryDto } from "./dto/available-locomotives-query.dto";
+import { AdjustScheduleConsistDto } from "./dto/adjust-schedule-consist.dto";
import { AvailableTrainsQueryDto } from "./dto/available-trains-query.dto";
import { BatchBoardQueryDto } from "./dto/batch-board-query.dto";
import { BookableSchedulesQueryDto } from "./dto/bookable-schedules-query.dto";
@@ -166,6 +167,34 @@ export class TrainSchedulingController {
);
}
+ @Get("schedules/:id/consist")
+ @TrainSchedulingView()
+ @ApiOperation({
+ summary:
+ "Built-train consist snapshot for a schedule: gross weight/length vs locomotive limits (incl. tolerance), trimmable + addable wagons, adjustment history",
+ })
+ getScheduleConsist(@Param("id", ParseUUIDPipe) id: string) {
+ return this.trainSchedulingService.getScheduleConsist(id);
+ }
+
+ @Post("schedules/:id/adjust-consist")
+ @TrainSchedulingManage()
+ @ApiOperation({
+ summary:
+ "Permanently trim free wagons off / couple yard wagons onto the schedule's built train (weight & length limits incl. tolerance enforced, every change logged)",
+ })
+ adjustScheduleConsist(
+ @Param("id", ParseUUIDPipe) id: string,
+ @Body() dto: AdjustScheduleConsistDto,
+ @CurrentUser() user: AuthUserPayload,
+ ) {
+ return this.trainSchedulingService.adjustScheduleConsist(
+ id,
+ dto,
+ resolveAuthUserId(user),
+ );
+ }
+
@Get("bookable-schedules")
// No staff guard: customers hit this while creating a booking to find OPEN
// same-route schedules. Do not attach train_scheduling permissions here.
diff --git a/apps/edr-freight-api/src/modules/train-scheduling/train-scheduling.service.ts b/apps/edr-freight-api/src/modules/train-scheduling/train-scheduling.service.ts
index 7e0720238..04583c777 100644
--- a/apps/edr-freight-api/src/modules/train-scheduling/train-scheduling.service.ts
+++ b/apps/edr-freight-api/src/modules/train-scheduling/train-scheduling.service.ts
@@ -25,6 +25,7 @@ import {
FindOptionsWhere,
ILike,
In,
+ IsNull,
Not,
QueryFailedError,
Raw,
@@ -48,6 +49,7 @@ import { Train } from '../trains/entities/train.entity';
import { TrainSetLocomotive } from '../train-sets/entities/train-set-locomotive.entity';
import { TrainSetWagon } from '../train-sets/entities/train-set-wagon.entity';
import { TrainSet } from '../train-sets/entities/train-set.entity';
+import { ScheduleWagonAdjustmentLog } from '../train-schedules/entities/schedule-wagon-adjustment-log.entity';
import { TrainScheduleBooking } from '../train-schedules/entities/train-schedule-booking.entity';
import { TrainSchedule } from '../train-schedules/entities/train-schedule.entity';
import { WagonAllocationContainerItem } from '../train-schedules/entities/wagon-allocation-container-item.entity';
@@ -61,6 +63,7 @@ import { WagonBookingAllocationsRepository } from '../train-schedules/wagon-book
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 { AdjustScheduleConsistDto } from './dto/adjust-schedule-consist.dto';
import { AssignBookingsDto } from './dto/assign-bookings.dto';
import { CreateContainerTrainScheduleDto } from './dto/create-container-train-schedule.dto';
import { GetEligibleBookingsDto } from './dto/get-eligible-bookings.dto';
@@ -1331,11 +1334,25 @@ export class TrainSchedulingService {
limitLoco.maxPullWeightTons + (Number(limitLoco.overageToleranceTons) || 0);
const lengthCapWithOverage =
limitLoco.maxTrainLengthMeters + (Number(limitLoco.overageToleranceMeters) || 0);
- // The locomotives pull GROSS weight: the customers' cargo plus the empty
- // weight of every planned wagon — cargo-only comparison understates the load.
- const planTareTons = roundTons(
- wagonPlan.reduce((sum, slot) => sum + Number(slot.tareWeightTons ?? 0), 0),
- );
+ // The locomotives pull GROSS weight: the customers' cargo plus wagon tare.
+ // A built train hauls EVERY coupled wagon's tare — empty ones included —
+ // so train-bound schedules count the full consist, not just planned slots.
+ const consistWagons = schedule.trainSet?.trainId
+ ? await this.dataSource.getRepository(Wagon).find({
+ where: { trainId: schedule.trainSet.trainId },
+ relations: { wagonType: true },
+ })
+ : null;
+ const planTareTons = consistWagons
+ ? roundTons(
+ consistWagons.reduce(
+ (sum, wagon) => sum + Number(wagon.wagonType?.tareWeightTons ?? 0),
+ 0,
+ ),
+ )
+ : roundTons(
+ wagonPlan.reduce((sum, slot) => sum + Number(slot.tareWeightTons ?? 0), 0),
+ );
const grossWeightTons = roundTons(totalWeightTons + planTareTons);
if (!dto.forceAssign && weightCapWithOverage < grossWeightTons) {
throw new BadRequestException(
@@ -4626,6 +4643,294 @@ export class TrainSchedulingService {
});
}
+ /**
+ * Consist snapshot for the adjust-consist UI: the built train's wagons with
+ * loaded/removable flags, gross weight (cargo + FULL consist tare) and length
+ * against the locomotive limits incl. overage tolerance, addable yard wagons,
+ * and the adjustment history.
+ */
+ async getScheduleConsist(scheduleId: string) {
+ const schedule = await this.trainSchedulesRepository.findByIdWithFullGraph(scheduleId);
+ if (!schedule) throw new NotFoundException(`Train schedule ${scheduleId} not found`);
+ const builtTrain = schedule.trainSet?.train;
+ if (!builtTrain) {
+ throw new BadRequestException(
+ 'This schedule was not created from a built train — its consist cannot be adjusted here',
+ );
+ }
+
+ const wagons = await this.dataSource.getRepository(Wagon).find({
+ where: { trainId: builtTrain.id },
+ relations: { wagonType: true },
+ order: { sequenceNumber: 'ASC' },
+ });
+ const addableWagons = await this.dataSource.getRepository(Wagon).find({
+ where: {
+ trainId: IsNull(),
+ status: WagonStatus.Available,
+ currentYardId: builtTrain.currentYardId ?? undefined,
+ },
+ relations: { wagonType: true },
+ order: { wagonNumber: 'ASC' },
+ });
+ const adjustments = await this.dataSource
+ .getRepository(ScheduleWagonAdjustmentLog)
+ .find({ where: { trainScheduleId: scheduleId }, order: { occurredAt: 'DESC' }, take: 30 });
+
+ // Slots with cargo aboard — their physical wagons are "loaded" and can
+ // never be trimmed.
+ const loadedWagonIds = new Set(
+ (schedule.trainSet?.wagons ?? [])
+ .filter((slot) => slot.physicalWagonId && (slot.allocations?.length ?? 0) > 0)
+ .map((slot) => slot.physicalWagonId as string),
+ );
+
+ const limits = minLocomotiveLimits(this.locomotivesOfTrainSet(schedule.trainSet));
+ const maxPullWeightTons = roundTons(Number(limits?.maxPullWeightTons ?? 0));
+ const overageToleranceTons = roundTons(Number(limits?.overageToleranceTons) || 0);
+ const maxTrainLengthMeters = roundTons(Number(limits?.maxTrainLengthMeters ?? 0));
+ const overageToleranceMeters = roundTons(Number(limits?.overageToleranceMeters) || 0);
+
+ const cargoTons = roundTons(Number(schedule.trainSet?.totalWeightTons ?? 0));
+ const consistTareTons = roundTons(
+ wagons.reduce((sum, w) => sum + Number(w.wagonType?.tareWeightTons ?? 0), 0),
+ );
+ const consistLengthMeters = roundTons(
+ wagons.reduce((sum, w) => sum + Number(w.wagonType?.lengthMeters ?? 0), 0),
+ );
+
+ const mapWagon = (wagon: Wagon) => ({
+ id: wagon.id,
+ wagonNumber: wagon.wagonNumber,
+ sequenceNumber: wagon.sequenceNumber,
+ wagonType: wagon.wagonType
+ ? {
+ id: wagon.wagonType.id,
+ code: wagon.wagonType.code,
+ tareWeightTons: roundTons(Number(wagon.wagonType.tareWeightTons ?? 0)),
+ capacityTons: roundTons(Number(wagon.wagonType.capacityTons ?? 0)),
+ lengthMeters: roundTons(Number(wagon.wagonType.lengthMeters ?? 0)),
+ }
+ : null,
+ });
+
+ return {
+ schedule: { id: schedule.id, reference: schedule.reference ?? null, status: schedule.status },
+ train: {
+ id: builtTrain.id,
+ code: builtTrain.code,
+ trainName: builtTrain.trainName ?? null,
+ currentYardId: builtTrain.currentYardId ?? null,
+ },
+ limits: {
+ maxPullWeightTons,
+ overageToleranceTons,
+ pullCapTons: roundTons(maxPullWeightTons + overageToleranceTons),
+ maxTrainLengthMeters,
+ overageToleranceMeters,
+ lengthCapMeters: roundTons(maxTrainLengthMeters + overageToleranceMeters),
+ },
+ totals: {
+ wagonCount: wagons.length,
+ cargoTons,
+ consistTareTons,
+ grossTons: roundTons(cargoTons + consistTareTons),
+ consistLengthMeters,
+ },
+ wagons: wagons.map((wagon) => ({
+ ...mapWagon(wagon),
+ loaded: loadedWagonIds.has(wagon.id),
+ // Free = not pinned to any run; only free wagons can be trimmed.
+ removable: wagon.currentTrainScheduleId == null && !loadedWagonIds.has(wagon.id),
+ })),
+ addableWagons: addableWagons.map(mapWagon),
+ adjustments: adjustments.map((log) => ({
+ id: log.id,
+ action: log.action,
+ wagonId: log.wagonId,
+ wagonNumber: log.wagonNumber,
+ adjustedByUserId: log.adjustedByUserId,
+ occurredAt: log.occurredAt,
+ })),
+ editable: ['DRAFT', 'SCHEDULED'].includes(schedule.status),
+ };
+ }
+
+ /**
+ * Permanently adjust the built train's consist from a schedule: trim free
+ * wagons (their tare no longer rides — the usual fix when gross weight beats
+ * the pull limit) and/or couple extra AVAILABLE yard wagons while weight and
+ * length headroom remain (limits incl. overage tolerance). The built train
+ * updates in place, the schedule's wagon cap follows, and every change is
+ * logged for the schedule's history.
+ */
+ async adjustScheduleConsist(
+ scheduleId: string,
+ dto: AdjustScheduleConsistDto,
+ userId?: string | null,
+ ) {
+ const addWagonIds = [...new Set(dto.addWagonIds ?? [])];
+ const removeWagonIds = [...new Set(dto.removeWagonIds ?? [])];
+ if (!addWagonIds.length && !removeWagonIds.length) {
+ throw new BadRequestException('Nothing to adjust — pass wagons to add and/or remove');
+ }
+ const overlap = addWagonIds.filter((id) => removeWagonIds.includes(id));
+ if (overlap.length) {
+ throw new BadRequestException('A wagon cannot be added and removed in the same adjustment');
+ }
+
+ const schedule = await this.trainSchedulesRepository.findByIdWithFullGraph(scheduleId);
+ if (!schedule) throw new NotFoundException(`Train schedule ${scheduleId} not found`);
+ if (!['DRAFT', 'SCHEDULED'].includes(schedule.status)) {
+ throw new BadRequestException(
+ 'The consist is frozen once the train is dispatched — adjust before departure',
+ );
+ }
+ const builtTrainRef = schedule.trainSet?.train;
+ if (!builtTrainRef) {
+ throw new BadRequestException(
+ 'This schedule was not created from a built train — its consist cannot be adjusted here',
+ );
+ }
+ const loadedWagonIds = new Set(
+ (schedule.trainSet?.wagons ?? [])
+ .filter((slot) => slot.physicalWagonId && (slot.allocations?.length ?? 0) > 0)
+ .map((slot) => slot.physicalWagonId as string),
+ );
+ const limits = minLocomotiveLimits(this.locomotivesOfTrainSet(schedule.trainSet));
+ const pullCapTons = roundTons(
+ Number(limits?.maxPullWeightTons ?? 0) + (Number(limits?.overageToleranceTons) || 0),
+ );
+ const lengthCapMeters = roundTons(
+ Number(limits?.maxTrainLengthMeters ?? 0) + (Number(limits?.overageToleranceMeters) || 0),
+ );
+
+ await this.dataSource.transaction(async (manager) => {
+ const train = await manager.getRepository(Train).findOne({
+ where: { id: builtTrainRef.id },
+ lock: { mode: 'pessimistic_write' },
+ });
+ if (!train) throw new NotFoundException(`Train ${builtTrainRef.id} not found`);
+
+ const consist = await manager.getRepository(Wagon).find({
+ where: { trainId: train.id },
+ relations: { wagonType: true },
+ order: { sequenceNumber: 'ASC' },
+ });
+ const consistById = new Map(consist.map((w) => [w.id, w]));
+
+ // --- validate removals: must be coupled and free (no cargo, no pin) ---
+ const removed: Wagon[] = [];
+ for (const wagonId of removeWagonIds) {
+ const wagon = consistById.get(wagonId);
+ if (!wagon) {
+ throw new NotFoundException(`Wagon ${wagonId} is not coupled to train ${train.code}`);
+ }
+ if (loadedWagonIds.has(wagon.id) || wagon.currentTrainScheduleId != null) {
+ throw new ConflictException(
+ `Wagon ${wagon.wagonNumber} is loaded/pinned on a schedule and cannot be trimmed`,
+ );
+ }
+ removed.push(wagon);
+ }
+
+ // --- validate additions: AVAILABLE, loose, standing in the train's yard ---
+ const added: Wagon[] = [];
+ for (const wagonId of addWagonIds) {
+ const wagon = await manager.getRepository(Wagon).findOne({
+ where: { id: wagonId },
+ relations: { wagonType: true },
+ lock: { mode: 'pessimistic_write' },
+ });
+ if (!wagon) throw new NotFoundException(`Wagon ${wagonId} not found`);
+ if (wagon.trainId) {
+ throw new ConflictException(`Wagon ${wagon.wagonNumber} is already on a train`);
+ }
+ if (wagon.status !== WagonStatus.Available) {
+ throw new ConflictException(
+ `Wagon ${wagon.wagonNumber} is not available (${wagon.status})`,
+ );
+ }
+ if (wagon.currentYardId !== train.currentYardId) {
+ throw new BadRequestException(
+ `Wagon ${wagon.wagonNumber} is not in the train's yard — only wagons in the same yard can be coupled`,
+ );
+ }
+ added.push(wagon);
+ }
+
+ // --- headroom check (only additions can push the train over a cap) ---
+ const removedIds = new Set(removed.map((w) => w.id));
+ const finalConsist = [...consist.filter((w) => !removedIds.has(w.id)), ...added];
+ const tareOf = (w: Wagon) => Number(w.wagonType?.tareWeightTons ?? 0);
+ const lengthOf = (w: Wagon) => Number(w.wagonType?.lengthMeters ?? 0);
+ const finalTareTons = roundTons(finalConsist.reduce((s, w) => s + tareOf(w), 0));
+ const finalLengthMeters = roundTons(finalConsist.reduce((s, w) => s + lengthOf(w), 0));
+ const cargoTons = roundTons(Number(schedule.trainSet?.totalWeightTons ?? 0));
+ const finalGrossTons = roundTons(cargoTons + finalTareTons);
+ if (added.length && pullCapTons > 0 && finalGrossTons > pullCapTons) {
+ throw new BadRequestException(
+ `Adding these wagons puts gross weight at ${finalGrossTons}T (${cargoTons}T cargo + ${finalTareTons}T tare), over the locomotives' ${pullCapTons}T limit incl. tolerance`,
+ );
+ }
+ if (added.length && lengthCapMeters > 0 && finalLengthMeters > lengthCapMeters) {
+ throw new BadRequestException(
+ `Adding these wagons puts consist length at ${finalLengthMeters}m, over the locomotives' ${lengthCapMeters}m limit incl. tolerance`,
+ );
+ }
+
+ // --- apply: detach trims, couple additions, compact the sequence ---
+ for (const wagon of removed) {
+ await manager.getRepository(Wagon).update(wagon.id, {
+ trainId: null,
+ sequenceNumber: null,
+ status: WagonStatus.Available,
+ });
+ }
+ const remaining = consist.filter((w) => !removedIds.has(w.id));
+ for (let i = 0; i < remaining.length; i++) {
+ if (remaining[i].sequenceNumber !== i + 1) {
+ await manager.getRepository(Wagon).update(remaining[i].id, { sequenceNumber: i + 1 });
+ }
+ }
+ let sequence = remaining.length;
+ for (const wagon of added) {
+ sequence += 1;
+ await manager.getRepository(Wagon).update(wagon.id, {
+ trainId: train.id,
+ sequenceNumber: sequence,
+ status: WagonStatus.Assigned,
+ });
+ }
+
+ // The schedule is full when every consist wagon is allocated.
+ await manager
+ .getRepository(TrainSchedule)
+ .update(scheduleId, { maxWagons: finalConsist.length });
+
+ const logRepo = manager.getRepository(ScheduleWagonAdjustmentLog);
+ const now = new Date();
+ await logRepo.save(
+ [
+ ...removed.map((wagon) => ({ action: 'REMOVE' as const, wagon })),
+ ...added.map((wagon) => ({ action: 'ADD' as const, wagon })),
+ ].map(({ action, wagon }) =>
+ logRepo.create({
+ trainScheduleId: scheduleId,
+ trainId: train.id,
+ action,
+ wagonId: wagon.id,
+ wagonNumber: wagon.wagonNumber,
+ adjustedByUserId: userId ?? null,
+ occurredAt: now,
+ }),
+ ),
+ );
+ });
+
+ return this.getScheduleConsist(scheduleId);
+ }
+
/**
* Re-derive a built train's lifecycle status from its schedules after one of
* them changes: any DISPATCHED schedule → IN_SERVICE; any DRAFT/SCHEDULED →
diff --git a/apps/edr-freight-api/src/modules/trains/train-builder.service.ts b/apps/edr-freight-api/src/modules/trains/train-builder.service.ts
index b92ab21d6..16ff29d38 100644
--- a/apps/edr-freight-api/src/modules/trains/train-builder.service.ts
+++ b/apps/edr-freight-api/src/modules/trains/train-builder.service.ts
@@ -10,6 +10,7 @@ import { DataSource, EntityManager, ILike, In } from 'typeorm';
import { Locomotive } from '../locomotives/entities/locomotive.entity';
import { Yard } from '../rule-engine/entities/yard.entity';
import { minLocomotiveLimits } from '../train-scheduling/train-capacity.util';
+import { WagonType } from '../wagon-types/entities/wagon-type.entity';
import { WagonMovement } from '../wagons/entities/wagon-movement.entity';
import { Wagon } from '../wagons/entities/wagon.entity';
import { AssignTrainWagonsDto } from './dto/assign-train-wagons.dto';
@@ -511,9 +512,13 @@ export class TrainBuilderService {
startCount: number,
): Promise {
const uniqueIds = [...new Set(wagonIds)];
- let sequence = startCount;
+ const wagonRepo = manager.getRepository(Wagon);
+
+ // First pass: lock + validate every wagon so the length gate below sees
+ // the full incoming set before any row is written.
+ const toAttach: Wagon[] = [];
for (const wagonId of uniqueIds) {
- const wagon = await manager.getRepository(Wagon).findOne({
+ const wagon = await wagonRepo.findOne({
where: { id: wagonId },
lock: { mode: 'pessimistic_write' },
});
@@ -530,8 +535,16 @@ export class TrainBuilderService {
`Wagon ${wagon.wagonNumber} is not in the train's yard; only wagons in the same yard can be attached`,
);
}
+ toAttach.push(wagon);
+ }
+ if (!toAttach.length) return;
+
+ await this.assertConsistLengthWithinLimit(manager, train, toAttach);
+
+ let sequence = startCount;
+ for (const wagon of toAttach) {
sequence += 1;
- await manager.getRepository(Wagon).update(wagon.id, {
+ await wagonRepo.update(wagon.id, {
trainId: train.id,
sequenceNumber: sequence,
status: WagonStatus.Assigned,
@@ -539,6 +552,58 @@ export class TrainBuilderService {
}
}
+ /**
+ * The consist (already-attached wagons + the incoming ones) must fit the
+ * train's locomotive length limit — the weakest locomotive of the set caps
+ * the train, mirroring how scheduling derives capacity.
+ */
+ private async assertConsistLengthWithinLimit(
+ manager: EntityManager,
+ train: Train,
+ incoming: Wagon[],
+ ): Promise {
+ const links = await manager.getRepository(TrainLocomotive).find({
+ where: { trainId: train.id },
+ relations: { locomotive: true },
+ });
+ const limits = minLocomotiveLimits(
+ links
+ .map((link) => link.locomotive)
+ .filter((loco): loco is Locomotive => Boolean(loco)),
+ );
+ const maxLengthMeters = Number(limits?.maxTrainLengthMeters ?? 0);
+ if (!Number.isFinite(maxLengthMeters) || maxLengthMeters <= 0) return;
+
+ const existing = await manager.getRepository(Wagon).find({
+ where: { trainId: train.id },
+ relations: { wagonType: true },
+ });
+ const currentLength = existing.reduce(
+ (sum, w) => sum + (Number(w.wagonType?.lengthMeters) || 0),
+ 0,
+ );
+
+ const typeIds = [...new Set(incoming.map((w) => w.wagonTypeId).filter(Boolean))];
+ const types = typeIds.length
+ ? await manager.getRepository(WagonType).find({ where: { id: In(typeIds) } })
+ : [];
+ const lengthByType = new Map(types.map((t) => [t.id, Number(t.lengthMeters) || 0]));
+ const addedLength = incoming.reduce(
+ (sum, w) => sum + (lengthByType.get(w.wagonTypeId) ?? 0),
+ 0,
+ );
+
+ const totalLength = currentLength + addedLength;
+ if (totalLength > maxLengthMeters) {
+ throw new BadRequestException(
+ `Cannot attach wagons — train length would be ${round(totalLength)} m ` +
+ `(current ${round(currentLength)} m + ${round(addedLength)} m added), ` +
+ `over the locomotive limit of ${round(maxLengthMeters)} m. ` +
+ 'Remove wagons from the consist or use locomotives with a higher length limit.',
+ );
+ }
+ }
+
/** Compact wagon sequence numbers back to 1..n after a removal. */
private async resequenceWagons(manager: EntityManager, trainId: string): Promise {
const wagons = await manager.getRepository(Wagon).find({
diff --git a/apps/edr-freight-web/backoffice/src/components/trainScheduling/AdjustConsistModal.tsx b/apps/edr-freight-web/backoffice/src/components/trainScheduling/AdjustConsistModal.tsx
new file mode 100644
index 000000000..1ca91e01f
--- /dev/null
+++ b/apps/edr-freight-web/backoffice/src/components/trainScheduling/AdjustConsistModal.tsx
@@ -0,0 +1,396 @@
+import {
+ Alert,
+ Badge,
+ Button,
+ Checkbox,
+ Divider,
+ Grid,
+ Group,
+ Modal,
+ Progress,
+ ScrollArea,
+ Stack,
+ Text,
+} from "@mantine/core";
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { isAxiosError } from "axios";
+import { AlertTriangle, History, Minus, Plus } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+
+import { api } from "@/services/api";
+import type { ConsistWagonRef } from "@/services/trainBuilder.service";
+import { useToast } from "@/hooks/use-toast";
+
+const parseError = (error: unknown, fallback: string) => {
+ if (isAxiosError(error)) {
+ const message = error.response?.data?.message;
+ if (Array.isArray(message)) return message.join(", ");
+ if (typeof message === "string") return message;
+ }
+ return fallback;
+};
+
+const tareOf = (w: ConsistWagonRef) => w.wagonType?.tareWeightTons ?? 0;
+const lengthOf = (w: ConsistWagonRef) => w.wagonType?.lengthMeters ?? 0;
+const round2 = (v: number) => Math.round(v * 100) / 100;
+
+/**
+ * Adjust the built train's consist from a schedule: trim free wagons (their
+ * tare no longer rides — the fix when gross weight beats the pull limit) or
+ * couple extra yard wagons while weight/length headroom remains. Changes are
+ * permanent on the train and logged on the schedule.
+ */
+export default function AdjustConsistModal({
+ scheduleId,
+ opened,
+ onClose,
+}: AdjustConsistModalProps) {
+ const { toast } = useToast();
+ const [removeIds, setRemoveIds] = useState([]);
+ const [addIds, setAddIds] = useState([]);
+
+ const consistQuery = useQuery(
+ api.trainScheduling.scheduleConsist.queryOptions({
+ input: { scheduleId },
+ enabled: opened && Boolean(scheduleId),
+ }),
+ );
+ const adjust = useMutation(api.trainScheduling.adjustConsist.mutationOptions());
+ const data = consistQuery.data;
+
+ useEffect(() => {
+ if (opened) {
+ setRemoveIds([]);
+ setAddIds([]);
+ }
+ }, [opened]);
+
+ // Live projection: gross = cargo + tare of (consist − trims + adds).
+ const projection = useMemo(() => {
+ if (!data) return null;
+ const removed = new Set(removeIds);
+ const keptTare = data.wagons
+ .filter((w) => !removed.has(w.id))
+ .reduce((s, w) => s + tareOf(w), 0);
+ const keptLength = data.wagons
+ .filter((w) => !removed.has(w.id))
+ .reduce((s, w) => s + lengthOf(w), 0);
+ const addedWagons = data.addableWagons.filter((w) => addIds.includes(w.id));
+ const tare = keptTare + addedWagons.reduce((s, w) => s + tareOf(w), 0);
+ const length = keptLength + addedWagons.reduce((s, w) => s + lengthOf(w), 0);
+ const gross = round2(data.totals.cargoTons + tare);
+ return {
+ wagonCount: data.totals.wagonCount - removeIds.length + addIds.length,
+ tare: round2(tare),
+ gross,
+ length: round2(length),
+ grossPct: data.limits.pullCapTons
+ ? Math.round((gross / data.limits.pullCapTons) * 100)
+ : null,
+ lengthPct: data.limits.lengthCapMeters
+ ? Math.round((length / data.limits.lengthCapMeters) * 100)
+ : null,
+ overWeight: data.limits.pullCapTons > 0 && gross > data.limits.pullCapTons,
+ overLength:
+ data.limits.lengthCapMeters > 0 && length > data.limits.lengthCapMeters,
+ };
+ }, [data, removeIds, addIds]);
+
+ const toggle = (setter: typeof setRemoveIds) => (id: string, checked: boolean) =>
+ setter((prev) => (checked ? [...prev, id] : prev.filter((x) => x !== id)));
+
+ const handleSubmit = async () => {
+ if (!removeIds.length && !addIds.length) return;
+ try {
+ await adjust.mutateAsync({
+ scheduleId,
+ payload: {
+ ...(addIds.length ? { addWagonIds: addIds } : {}),
+ ...(removeIds.length ? { removeWagonIds: removeIds } : {}),
+ },
+ });
+ toast({
+ title: `Consist updated — ${removeIds.length ? `${removeIds.length} trimmed` : ""}${
+ removeIds.length && addIds.length ? ", " : ""
+ }${addIds.length ? `${addIds.length} added` : ""}`,
+ });
+ setRemoveIds([]);
+ setAddIds([]);
+ } catch (err) {
+ toast({
+ title: "Adjustment failed",
+ description: parseError(err, "Could not adjust the consist"),
+ variant: "destructive",
+ });
+ }
+ };
+
+ return (
+
+ Adjust consist{data ? ` — train ${data.train.code}` : ""}
+
+ }
+ radius="lg"
+ size={860}
+ centered
+ >
+ {consistQuery.isLoading || !data ? (
+
+ {consistQuery.isError
+ ? "This schedule has no built train to adjust."
+ : "Loading consist…"}
+
+ ) : (
+
+ {!data.editable ? (
+ }>
+ The consist is frozen once the train is dispatched.
+
+ ) : null}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Trim coupled wagons ({data.totals.wagonCount})
+
+
+
+ Only free (unloaded, unpinned) wagons can be detached. Detaching is
+ permanent — the wagon returns to the yard as available.
+
+
+
+ {data.wagons.map((wagon) => (
+
+ ))}
+
+
+
+
+
+
+
+
+
+ Couple yard wagons ({data.addableWagons.length} available)
+
+
+
+ AVAILABLE wagons standing in the train's yard. Blocked when they push
+ gross weight or length past the locomotive limits incl. tolerance.
+
+
+
+ {data.addableWagons.length ? (
+ data.addableWagons.map((wagon) => (
+
+ ))
+ ) : (
+
+ No available wagons in this yard
+
+ )}
+
+
+
+
+
+
+ {data.adjustments.length ? (
+ <>
+
+
+
+
+
+ Adjustment history
+
+
+
+
+ {data.adjustments.map((log) => (
+
+
+ {log.action === "ADD" ? "Added" : "Trimmed"}
+
+
+ {log.wagonNumber}
+
+
+ {new Date(log.occurredAt).toLocaleString()}
+
+
+ ))}
+
+
+
+ >
+ ) : null}
+
+
+
+ Projected consist: {projection?.wagonCount} wagons
+
+
+
+
+
+
+
+ )}
+
+ );
+}
+
+export interface AdjustConsistModalProps {
+ scheduleId: string;
+ opened: boolean;
+ onClose: () => void;
+}
+
+function LimitGauge({
+ label,
+ detail,
+ pct,
+ over,
+}: {
+ label: string;
+ detail: string;
+ pct: number | null;
+ over: boolean;
+}) {
+ return (
+
+
+
+ {label}
+
+
+ {pct != null ? `${pct}%` : "—"}
+
+
+
+ );
+}
+
+function WagonRow({
+ wagon,
+ checked,
+ disabled,
+ badge,
+ onToggle,
+}: {
+ wagon: ConsistWagonRef;
+ checked: boolean;
+ disabled: boolean;
+ badge: string | null;
+ onToggle: (id: string, checked: boolean) => void;
+}) {
+ return (
+
+ onToggle(wagon.id, e.currentTarget.checked)}
+ aria-label={`Select wagon ${wagon.wagonNumber}`}
+ />
+
+
+ {wagon.wagonNumber}
+
+
+ {wagon.wagonType
+ ? `${wagon.wagonType.code} · ${wagon.wagonType.tareWeightTons}T tare · ${wagon.wagonType.lengthMeters}m`
+ : "Unknown type"}
+
+
+ {badge ? (
+
+ {badge}
+
+ ) : null}
+
+ );
+}
diff --git a/apps/edr-freight-web/backoffice/src/pages/bookings/NewBookingPage.tsx b/apps/edr-freight-web/backoffice/src/pages/bookings/NewBookingPage.tsx
index 0344e99cb..07a6c72cd 100644
--- a/apps/edr-freight-web/backoffice/src/pages/bookings/NewBookingPage.tsx
+++ b/apps/edr-freight-web/backoffice/src/pages/bookings/NewBookingPage.tsx
@@ -1,5 +1,6 @@
import {
ActionIcon,
+ Alert,
Badge,
Box,
Button,
@@ -324,6 +325,21 @@ export default function NewBookingPage() {
const containerWeight = lines.reduce((s, l) => s + (l.quantity || 0) * (l.vgmPerUnitTons || 0), 0);
const cargoTotalWeightVgm = freightType === "CONTAINER" ? containerWeight : bulkWeight;
+ // 20ft containers ride two per wagon, so a booking must hold an even number
+ // of them — odd counts would leave half a wagon waiting on a co-loader
+ // (cross-booking consolidation is disabled for now).
+ const twentyFtCount = useMemo(() => {
+ const sizeById = new Map();
+ for (const group of refData?.containers ?? []) {
+ for (const type of group.types) sizeById.set(type.id, group.size);
+ }
+ return lines.reduce((sum, l) => {
+ const size = l.containerTypeId ? (sizeById.get(l.containerTypeId) ?? "") : "";
+ return String(size).includes("20") ? sum + (l.quantity || 0) : sum;
+ }, 0);
+ }, [refData?.containers, lines]);
+ const hasOdd20ft = freightType === "CONTAINER" && twentyFtCount % 2 === 1;
+
// ---- validation ----
const lineValid = (l: ContainerLine) =>
Boolean(l.containerTypeId) && l.quantity >= 1 && l.vgmPerUnitTons > 0;
@@ -344,7 +360,7 @@ export default function NewBookingPage() {
(isGovernment ? Boolean(govCompanyId && govProfileId) : Boolean(companyId)) &&
(freightType === "BULK"
? Boolean(cargoTypeId) && bulkWeight > 0
- : allLinesValid);
+ : allLinesValid && !hasOdd20ft);
const updateLine = (key: string, patch: Partial) =>
setLines((prev) => prev.map((l) => (l.key === key ? { ...l, ...patch } : l)));
@@ -842,6 +858,20 @@ export default function NewBookingPage() {
) : null}
+ {hasOdd20ft ? (
+ } radius="md" mt="md">
+
+ Odd number of 20ft containers ({twentyFtCount})
+
+
+ 20ft containers travel two per wagon, so they must be booked in
+ even numbers. Add one more 20ft container or remove one — e.g.
+ book {twentyFtCount + 1} or {twentyFtCount - 1} instead of{" "}
+ {twentyFtCount}.
+
+
+ ) : null}
+
+ {data.train && ["DRAFT", "SCHEDULED"].includes(data.status) ? (
+ }
+ onClick={() => setAdjustConsistOpen(true)}
+ >
+ Adjust consist
+
+ ) : null}
{data.windowPhase === "DOC_REVIEW" ? (
) : null}
+ {schedule.train && ["DRAFT", "SCHEDULED"].includes(schedule.status) ? (
+ }
+ onClick={() => setAdjustConsistOpen(true)}
+ >
+ Adjust consist
+
+ ) : null}
{gatepassApplies ? (
gatepassSecured ? (
) : null}
+ setAdjustConsistOpen(false)}
+ />
+
QUERY_KEYS.TRAIN_SCHEDULING.availableTrains(routeId),
),
+ scheduleConsist: endpoint<{ scheduleId: string }, ScheduleConsist>(
+ "train-scheduling",
+ "schedule-consist",
+ ({ scheduleId }) =>
+ trainBuilderService.scheduleConsist(scheduleId).then((r) => r.data),
+ ({ scheduleId }) => [
+ ...QUERY_KEYS.TRAIN_SCHEDULING.ROOT,
+ "consist",
+ scheduleId,
+ ],
+ ),
+
+ adjustConsist: endpoint<
+ { scheduleId: string; payload: AdjustConsistPayload },
+ ScheduleConsist
+ >(
+ "train-scheduling",
+ "adjust-consist",
+ ({ scheduleId, payload }) =>
+ trainBuilderService.adjustConsist(scheduleId, payload).then((r) => r.data),
+ undefined,
+ () => TRAIN_BUILDER_INVALIDATIONS,
+ ),
+
bookableSchedules: endpoint<
{ originYardId?: string | null; destinationYardId?: string | null },
BookableSchedule[]
diff --git a/apps/edr-freight-web/backoffice/src/services/trainBuilder.service.ts b/apps/edr-freight-web/backoffice/src/services/trainBuilder.service.ts
index e6c462992..d88cd3ed6 100644
--- a/apps/edr-freight-web/backoffice/src/services/trainBuilder.service.ts
+++ b/apps/edr-freight-web/backoffice/src/services/trainBuilder.service.ts
@@ -153,6 +153,64 @@ const toQuery = (filters: BuiltTrainListFilters = {}) => {
return qs ? `?${qs}` : "";
};
+// ---------------------------------------------------------------------------
+// Schedule consist adjustment (train-bound schedules)
+// ---------------------------------------------------------------------------
+
+export interface ConsistWagonRef {
+ id: string;
+ wagonNumber: string;
+ sequenceNumber: number | null;
+ wagonType: {
+ id: string;
+ code: string;
+ tareWeightTons: number;
+ capacityTons: number;
+ lengthMeters: number;
+ } | null;
+}
+
+export interface ScheduleConsist {
+ schedule: { id: string; reference: string | null; status: string };
+ train: {
+ id: string;
+ code: string;
+ trainName: string | null;
+ currentYardId: string | null;
+ };
+ limits: {
+ maxPullWeightTons: number;
+ overageToleranceTons: number;
+ pullCapTons: number;
+ maxTrainLengthMeters: number;
+ overageToleranceMeters: number;
+ lengthCapMeters: number;
+ };
+ totals: {
+ wagonCount: number;
+ cargoTons: number;
+ consistTareTons: number;
+ grossTons: number;
+ consistLengthMeters: number;
+ };
+ wagons: Array;
+ addableWagons: ConsistWagonRef[];
+ adjustments: Array<{
+ id: string;
+ action: "ADD" | "REMOVE";
+ wagonId: string;
+ wagonNumber: string;
+ adjustedByUserId: string | null;
+ occurredAt: string;
+ }>;
+ editable: boolean;
+}
+
+export interface AdjustConsistPayload {
+ addWagonIds?: string[];
+ removeWagonIds?: string[];
+}
+
export const trainBuilderService = {
list: (filters: BuiltTrainListFilters = {}) =>
apiClient.get(`${BASE}${toQuery(filters)}`),
@@ -175,4 +233,13 @@ export const trainBuilderService = {
apiClient.get(`/train-scheduling/available-trains`, {
params: { routeId },
}),
+ /** Consist snapshot for a train-bound schedule (adjust-consist UI). */
+ scheduleConsist: (scheduleId: string) =>
+ apiClient.get(`/train-scheduling/schedules/${scheduleId}/consist`),
+ /** Permanently trim/add wagons on the schedule's built train. */
+ adjustConsist: (scheduleId: string, payload: AdjustConsistPayload) =>
+ apiClient.post(
+ `/train-scheduling/schedules/${scheduleId}/adjust-consist`,
+ payload,
+ ),
};
diff --git a/apps/edr-freight-web/portal/src/pages/bookings/new-booking-form/step5-cargo-details.tsx b/apps/edr-freight-web/portal/src/pages/bookings/new-booking-form/step5-cargo-details.tsx
index b582468cf..b9cf743fa 100644
--- a/apps/edr-freight-web/portal/src/pages/bookings/new-booking-form/step5-cargo-details.tsx
+++ b/apps/edr-freight-web/portal/src/pages/bookings/new-booking-form/step5-cargo-details.tsx
@@ -787,13 +787,17 @@ export function Step5CargoDetails({
const result = calcWagons(containers ?? []);
if (result.hasOddUnit) {
return (
-
-
Unpaired 20ft Container
+
+
+ Odd number of 20ft containers ({result.ft20Wagons})
+
- One 20ft container occupies only half a wagon. The wagon will
- depart once a co-loader is found to fill the remaining slot,
- which may delay departure beyond the standard
- lead time.
+ 20ft containers travel two per wagon, so they must be booked in
+ even numbers. Please add one more 20ft container{" "}
+ or remove one (e.g. book{" "}
+ {result.ft20Wagons + 1} or {result.ft20Wagons - 1} instead of{" "}
+ {result.ft20Wagons}) — the booking cannot be submitted with an
+ unpaired 20ft container.
);
From b102a31fc1a658077e94ee141f6eed07073c6169 Mon Sep 17 00:00:00 2001
From: Marshal
Date: Tue, 14 Jul 2026 13:51:31 +0000
Subject: [PATCH 10/13] fix train builder and consolidation
---
.../new-booking-form/step8-review.tsx | 36 +++++++++++++++----
1 file changed, 30 insertions(+), 6 deletions(-)
diff --git a/apps/edr-freight-web/portal/src/pages/bookings/new-booking-form/step8-review.tsx b/apps/edr-freight-web/portal/src/pages/bookings/new-booking-form/step8-review.tsx
index a789943c2..501a04a5d 100644
--- a/apps/edr-freight-web/portal/src/pages/bookings/new-booking-form/step8-review.tsx
+++ b/apps/edr-freight-web/portal/src/pages/bookings/new-booking-form/step8-review.tsx
@@ -25,10 +25,11 @@ import {
} from "lucide-react";
import type { Freight } from "@/types";
import {
+ calcWagons,
type BookingFormInputValues,
type BookingFormValues,
} from "./schema";
-import { StepHeader } from "./shared";
+import { AlertBox, StepHeader } from "./shared";
export const REVIEW_STEP_TARGETS = {
contract: 1,
@@ -160,6 +161,12 @@ export function Step8Review({
.join(", ")
: "";
+ // 20ft containers must pair up (two per wagon) — an odd total blocks submit.
+ const { hasOddUnit: hasOdd20ft, ft20Wagons: twentyFtCount } =
+ values.cargoType === "container"
+ ? calcWagons(values.containers ?? [])
+ : { hasOddUnit: false, ft20Wagons: 0 };
+
const isGeneralContract = values.bookingType === "general_contract";
// Both one-time and general contracts take the bulk amount from the cargo step
// (cargoWeight); general contracts no longer collect a per-route quantity.
@@ -529,10 +536,27 @@ export function Step8Review({
-
- Ready to submit. You'll review the unit rates before final
- submission.
-
+ {hasOdd20ft ? (
+
+
+
+ Odd number of 20ft containers ({twentyFtCount})
+
+
+ 20ft containers travel two per wagon, so they must be booked
+ in even numbers. Go back to the cargo step and{" "}
+ add one more 20ft container or{" "}
+ remove one (e.g. {twentyFtCount + 1} or{" "}
+ {twentyFtCount - 1} instead of {twentyFtCount}).
+
+
+
+ ) : (
+
+ Ready to submit. You'll review the unit rates before final
+ submission.
+
+ )}
}
onClick={onSubmit}
loading={submitPending}
- disabled={submitPending}
+ disabled={submitPending || hasOdd20ft}
>
Submit
From 12ab3f33b109f4803f39fbbebba15138618cbbb3 Mon Sep 17 00:00:00 2001
From: Roba Boru
Date: Tue, 14 Jul 2026 16:54:24 +0300
Subject: [PATCH 11/13] Fix stop route
---
.../src/modules/bookings/bookings.service.ts | 52 ++++++++++++++++---
1 file changed, 46 insertions(+), 6 deletions(-)
diff --git a/apps/edr-passenger-api/src/modules/bookings/bookings.service.ts b/apps/edr-passenger-api/src/modules/bookings/bookings.service.ts
index 7f09ffa49..a4b3617c9 100644
--- a/apps/edr-passenger-api/src/modules/bookings/bookings.service.ts
+++ b/apps/edr-passenger-api/src/modules/bookings/bookings.service.ts
@@ -1728,13 +1728,40 @@ export class BookingsService {
);
}
+ // Resolves the passenger's actual boarding/alighting stations for one leg from
+ // originStationId/destinationStationId (set when the booking covers only part of a
+ // longer multi-stop schedule, e.g. train runs A→D but the passenger booked B→D) via
+ // the schedule's stopTimes, falling back to the schedule's own full-route endpoints
+ // when there's no segment override (older records, or a booking that covers the
+ // whole run). Mirrors notifications.service.ts's resolveSegmentStations — that's
+ // already applied to SMS/email; this brings the booking API (voucher, detail page,
+ // confirmation) to the same behavior instead of always showing the train's full route.
+ private resolveSegmentStations(
+ schedule: any,
+ originStationId: string | null | undefined,
+ destinationStationId: string | null | undefined,
+ ): { origin: any; destination: any } {
+ const stopTimes: any[] = schedule?.stopTimes ?? [];
+ const findStation = (stationId: string | null | undefined, fallback: any) => {
+ if (stationId && stopTimes.length > 0) {
+ const stop = stopTimes.find((st: any) => st.stationId === stationId);
+ if (stop?.station) return stop.station;
+ }
+ return fallback ?? null;
+ };
+ return {
+ origin: findStation(originStationId, schedule?.originStation),
+ destination: findStation(destinationStationId, schedule?.destinationStation),
+ };
+ }
+
async getByRef(bookingRefOrId: string) {
const isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(bookingRefOrId);
const booking = await this.prisma.booking.findUnique({
where: isUuid ? { id: bookingRefOrId } : { bookingRef: bookingRefOrId },
include: {
- schedule: { include: { originStation: true, destinationStation: true, train: true } },
- returnSchedule: { include: { originStation: true, destinationStation: true, train: true } },
+ schedule: { include: { originStation: true, destinationStation: true, train: true, stopTimes: { include: { station: true } } } },
+ returnSchedule: { include: { originStation: true, destinationStation: true, train: true, stopTimes: { include: { station: true } } } },
seats: { include: { seat: { include: { coach: { include: { coachType: { include: { seatClasses: true } } } } } } } },
paymentIntent: true, tickets: true,
priceTier: { select: { priceMinor: true } },
@@ -1803,6 +1830,19 @@ export class BookingsService {
};
}
+ const outboundSegment = this.resolveSegmentStations(
+ (booking as any).schedule,
+ (booking as any).originStationId,
+ (booking as any).destinationStationId,
+ );
+ const returnSegment = (booking as any).returnSchedule
+ ? this.resolveSegmentStations(
+ (booking as any).returnSchedule,
+ (booking as any).returnOriginStationId,
+ (booking as any).returnDestinationStationId,
+ )
+ : null;
+
return {
id: booking.id, bookingRef: booking.bookingRef, status: booking.status,
totalMinor: resolvePackageRoundTripTotal(booking, (booking as any).priceTier?.priceMinor, booking.adultCount, booking.childCount), currency: 'ETB',
@@ -1819,8 +1859,8 @@ export class BookingsService {
id: (booking as any).schedule.id,
trainNumber: (booking as any).schedule.train.number,
trainName: (booking as any).schedule.train.name,
- origin: { id: (booking as any).schedule.originStation.id, name: (booking as any).schedule.originStation.name, code: (booking as any).schedule.originStation.code, city: (booking as any).schedule.originStation.city },
- destination: { id: (booking as any).schedule.destinationStation.id, name: (booking as any).schedule.destinationStation.name, code: (booking as any).schedule.destinationStation.code, city: (booking as any).schedule.destinationStation.city },
+ origin: { id: outboundSegment.origin.id, name: outboundSegment.origin.name, code: outboundSegment.origin.code, city: outboundSegment.origin.city },
+ destination: { id: outboundSegment.destination.id, name: outboundSegment.destination.name, code: outboundSegment.destination.code, city: outboundSegment.destination.city },
departureAt: (booking as any).schedule.departureAt, arrivalAt: (booking as any).schedule.arrivalAt,
},
returnSchedule: (booking as any).returnSchedule
@@ -1828,8 +1868,8 @@ export class BookingsService {
id: (booking as any).returnSchedule.id,
trainNumber: (booking as any).returnSchedule.train.number,
trainName: (booking as any).returnSchedule.train.name,
- origin: { id: (booking as any).returnSchedule.originStation.id, name: (booking as any).returnSchedule.originStation.name, code: (booking as any).returnSchedule.originStation.code, city: (booking as any).returnSchedule.originStation.city },
- destination: { id: (booking as any).returnSchedule.destinationStation.id, name: (booking as any).returnSchedule.destinationStation.name, code: (booking as any).returnSchedule.destinationStation.code, city: (booking as any).returnSchedule.destinationStation.city },
+ origin: { id: returnSegment!.origin.id, name: returnSegment!.origin.name, code: returnSegment!.origin.code, city: returnSegment!.origin.city },
+ destination: { id: returnSegment!.destination.id, name: returnSegment!.destination.name, code: returnSegment!.destination.code, city: returnSegment!.destination.city },
departureAt: (booking as any).returnSchedule.departureAt, arrivalAt: (booking as any).returnSchedule.arrivalAt,
}
: null,
From fc684a0f65c139129434ac61558a3d000f77220e Mon Sep 17 00:00:00 2001
From: Abubeker Yasin
Date: Tue, 14 Jul 2026 20:04:42 +0300
Subject: [PATCH 12/13] feat: ( permissions ) add permssions for master data
---
.../src/modules/fleet/fleet.controller.ts | 15 ++-
.../modules/packages/packages.controller.ts | 24 ++--
.../modules/payments/payments.controller.ts | 15 ++-
.../modules/schedules/routes.controller.ts | 14 +--
.../modules/schedules/schedules.controller.ts | 29 ++---
.../seat-classes/seat-classes.controller.ts | 10 +-
.../src/modules/seats/seats.controller.ts | 15 +--
.../modules/stations/stations.controller.ts | 14 +--
.../src/seed/edr-passenger.seed.ts | 15 +++
.../seed/passenger-permissions.registry.ts | 107 ++++++++++++++++++
.../src/app/payment-methods/page.tsx | 9 +-
.../src/components/layout/Sidebar.tsx | 26 ++---
.../backoffice/src/lib/permissions.ts | 69 +++++++++--
13 files changed, 282 insertions(+), 80 deletions(-)
diff --git a/apps/edr-passenger-api/src/modules/fleet/fleet.controller.ts b/apps/edr-passenger-api/src/modules/fleet/fleet.controller.ts
index d3864e2b2..ee2a048f0 100644
--- a/apps/edr-passenger-api/src/modules/fleet/fleet.controller.ts
+++ b/apps/edr-passenger-api/src/modules/fleet/fleet.controller.ts
@@ -3,7 +3,8 @@ import { ApiTags, ApiOperation, ApiBearerAuth, ApiParam, ApiQuery, ApiBody, ApiR
import { FleetService } from './fleet.service';
import { CreateTrainDto, CreateCoachDto, UpdateCoachDto, AssignCoachDto, ListCoachesDto, CreateCoachTypeDto, UpdateCoachTypeDto, CreateClassDto, UpdateClassDto, GenerateSeatMapDto } from './fleet.dto';
import { JwtGuard } from '../../common/jwt.guard';
-import { PassengerAdmin } from '../../common/passenger-guards';
+import { PassengerAdmin, PassengerStaff } from '../../common/passenger-guards';
+import { PASSENGER_PERMS } from '../../seed/passenger-permissions.registry';
@ApiTags('Fleet')
@Controller('fleet')
@@ -21,6 +22,7 @@ export class FleetController {
}
@Post('coach-types')
+ @PassengerStaff([PASSENGER_PERMS.coaches.manage, PASSENGER_PERMS.admin])
@ApiOperation({ summary: 'Create a coach type' })
@ApiBody({ type: CreateCoachTypeDto })
@ApiResponse({ status: 201, description: 'Coach type created' })
@@ -29,6 +31,7 @@ export class FleetController {
}
@Patch('coach-types/:id')
+ @PassengerStaff([PASSENGER_PERMS.coaches.manage, PASSENGER_PERMS.admin])
@ApiOperation({ summary: 'Update a coach type' })
@ApiParam({ name: 'id', description: 'Coach Type UUID' })
@ApiBody({ type: UpdateCoachTypeDto })
@@ -59,6 +62,7 @@ export class FleetController {
}
@Post('classes')
+ @PassengerStaff([PASSENGER_PERMS.classes.manage, PASSENGER_PERMS.admin])
@ApiOperation({ summary: 'Create a class' })
@ApiBody({ type: CreateClassDto })
@ApiResponse({ status: 201, description: 'Class created' })
@@ -67,6 +71,7 @@ export class FleetController {
}
@Patch('classes/:id')
+ @PassengerStaff([PASSENGER_PERMS.classes.manage, PASSENGER_PERMS.admin])
@ApiOperation({ summary: 'Update a class' })
@ApiParam({ name: 'id', description: 'Class UUID' })
@ApiBody({ type: UpdateClassDto })
@@ -98,6 +103,7 @@ export class FleetController {
}
@Post('seat-classes')
+ @PassengerStaff([PASSENGER_PERMS.classes.manage, PASSENGER_PERMS.admin])
@ApiOperation({ summary: 'Create a class (DEPRECATED - use /fleet/classes)' })
@ApiBody({ type: CreateClassDto })
@ApiResponse({ status: 201, description: 'Class created' })
@@ -106,6 +112,7 @@ export class FleetController {
}
@Patch('seat-classes/:id')
+ @PassengerStaff([PASSENGER_PERMS.classes.manage, PASSENGER_PERMS.admin])
@ApiOperation({ summary: 'Update a class (DEPRECATED - use /fleet/classes)' })
@ApiParam({ name: 'id', description: 'Class UUID' })
@ApiBody({ type: UpdateClassDto })
@@ -136,6 +143,7 @@ export class FleetController {
}
@Post('trains')
+ @PassengerStaff([PASSENGER_PERMS.trains.manage, PASSENGER_PERMS.admin])
@ApiOperation({ summary: 'Create a train service' })
@ApiBody({ type: CreateTrainDto })
@ApiResponse({ status: 201, description: 'Train created' })
@@ -144,6 +152,7 @@ export class FleetController {
}
@Patch('trains/:id')
+ @PassengerStaff([PASSENGER_PERMS.trains.manage, PASSENGER_PERMS.admin])
@ApiOperation({ summary: 'Update a train service' })
@ApiParam({ name: 'id', description: 'Train UUID' })
@ApiBody({ type: CreateTrainDto })
@@ -166,6 +175,7 @@ export class FleetController {
}
@Patch('trains/:id/restore')
+ @PassengerStaff([PASSENGER_PERMS.trains.manage, PASSENGER_PERMS.admin])
@ApiOperation({ summary: 'Restore (reactivate) a deactivated train' })
@ApiParam({ name: 'id', description: 'Train UUID' })
@ApiResponse({ status: 200, description: 'Train restored' })
@@ -268,6 +278,7 @@ export class FleetController {
}
@Post('coaches')
+ @PassengerStaff([PASSENGER_PERMS.coaches.manage, PASSENGER_PERMS.admin])
@ApiOperation({ summary: 'Create a coach with auto-generated seat numbers' })
@ApiBody({ type: CreateCoachDto })
@ApiResponse({
@@ -293,6 +304,7 @@ export class FleetController {
}
@Patch('coaches/:id')
+ @PassengerStaff([PASSENGER_PERMS.coaches.manage, PASSENGER_PERMS.admin])
@ApiOperation({ summary: 'Update coach properties' })
@ApiParam({ name: 'id', description: 'Coach UUID' })
@ApiBody({ type: UpdateCoachDto })
@@ -331,6 +343,7 @@ export class FleetController {
}
@Post('assignments')
+ @PassengerStaff([PASSENGER_PERMS.coaches.manage, PASSENGER_PERMS.admin])
@ApiOperation({ summary: 'Assign a coach to a schedule' })
@ApiBody({ type: AssignCoachDto })
@ApiResponse({ status: 201, description: 'Coach assigned' })
diff --git a/apps/edr-passenger-api/src/modules/packages/packages.controller.ts b/apps/edr-passenger-api/src/modules/packages/packages.controller.ts
index 314f8aeb4..79f04f9d9 100644
--- a/apps/edr-passenger-api/src/modules/packages/packages.controller.ts
+++ b/apps/edr-passenger-api/src/modules/packages/packages.controller.ts
@@ -3,10 +3,10 @@ import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger'
import { IsPublic } from '@tria-plc/api-common/modules/auth/decorators/public.decorator';
import { PackagesService } from './packages.service';
import { CreatePackageDto, BookPackageDto, CreatePriceTierDto, UpdatePriceTierDto, CreateInquiryDto, UpdateInquiryStatusDto, PackageBookingContextDto } from './packages.dto';
-import { IamGuard } from '../../common/iam-adapter';
import { JwtGuard } from '../../common/jwt.guard';
import { OptionalJwtGuard } from '../verifayda/optional-jwt.guard';
-import { PassengerAdmin } from '../../common/passenger-guards';
+import { PassengerAdmin, PassengerStaff } from '../../common/passenger-guards';
+import { PASSENGER_PERMS } from '../../seed/passenger-permissions.registry';
@ApiTags('Packages')
@Controller('packages')
@@ -21,7 +21,7 @@ export class PackagesController {
}
@Get('inquiries')
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.inquiries.view, PASSENGER_PERMS.admin])
@ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'List all inquiries (backoffice)' })
listInquiries(
@@ -34,7 +34,7 @@ export class PackagesController {
}
@Patch('inquiries/:id/status')
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.inquiries.manage, PASSENGER_PERMS.admin])
@ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Update inquiry status (backoffice)' })
updateInquiryStatus(@Param('id') id: string, @Body() dto: UpdateInquiryStatusDto) {
@@ -57,7 +57,7 @@ export class PackagesController {
}
@Get('all')
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.packages.view, PASSENGER_PERMS.admin])
@ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'List all packages (backoffice)' })
listAll(@Query('page') page?: string, @Query('pageSize') pageSize?: string) {
@@ -65,7 +65,7 @@ export class PackagesController {
}
@Get('bookings')
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.packages.view, PASSENGER_PERMS.admin])
@ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'List all package bookings (backoffice)' })
listBookings(
@@ -124,7 +124,7 @@ export class PackagesController {
}
@Post()
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.packages.manage, PASSENGER_PERMS.admin])
@ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Create package (admin)' })
create(@Body() dto: CreatePackageDto) {
@@ -132,7 +132,7 @@ export class PackagesController {
}
@Patch(':id')
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.packages.manage, PASSENGER_PERMS.admin])
@ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Update package (admin)' })
update(@Param('id') id: string, @Body() dto: Partial) {
@@ -149,7 +149,7 @@ export class PackagesController {
}
@Patch(':id/activate')
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.packages.manage, PASSENGER_PERMS.admin])
@ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Activate package (admin)' })
activate(@Param('id') id: string) {
@@ -157,7 +157,7 @@ export class PackagesController {
}
@Patch(':id/deactivate')
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.packages.manage, PASSENGER_PERMS.admin])
@ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Deactivate package (admin)' })
deactivate(@Param('id') id: string) {
@@ -165,7 +165,7 @@ export class PackagesController {
}
@Post(':id/tiers')
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.packages.manage, PASSENGER_PERMS.admin])
@ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Add price tier to package (admin)' })
addTier(@Param('id') id: string, @Body() dto: CreatePriceTierDto) {
@@ -173,7 +173,7 @@ export class PackagesController {
}
@Patch('tiers/:tierId')
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.packages.manage, PASSENGER_PERMS.admin])
@ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Update price tier (admin)' })
updateTier(@Param('tierId') tierId: string, @Body() dto: UpdatePriceTierDto) {
diff --git a/apps/edr-passenger-api/src/modules/payments/payments.controller.ts b/apps/edr-passenger-api/src/modules/payments/payments.controller.ts
index 8917c75d3..f917a9590 100644
--- a/apps/edr-passenger-api/src/modules/payments/payments.controller.ts
+++ b/apps/edr-passenger-api/src/modules/payments/payments.controller.ts
@@ -55,7 +55,11 @@ export class PaymentsController {
}
@Get("all")
- @PassengerStaff([PASSENGER_PERMS.payments.viewAll, PASSENGER_PERMS.admin])
+ @PassengerStaff([
+ PASSENGER_PERMS.payments.view,
+ PASSENGER_PERMS.payments.viewAll,
+ PASSENGER_PERMS.admin,
+ ])
@ApiBearerAuth("IAM-auth")
@ApiOperation({ summary: "Get all payments with filters (staff/admin only)" })
@ApiQuery({ name: "search", required: false })
@@ -146,7 +150,11 @@ export class PaymentsController {
}
@Post("refund")
- @PassengerStaff([PASSENGER_PERMS.payments.refund, PASSENGER_PERMS.admin])
+ @PassengerStaff([
+ PASSENGER_PERMS.payments.manage,
+ PASSENGER_PERMS.payments.refund,
+ PASSENGER_PERMS.admin,
+ ])
@ApiBearerAuth("IAM-auth")
@ApiOperation({ summary: "Refund a confirmed booking (staff/agent only)" })
refund(@Body() dto: RefundDto) {
@@ -155,6 +163,7 @@ export class PaymentsController {
@Post(":bookingId/force-confirm")
@PassengerStaff([
+ PASSENGER_PERMS.payments.manage,
PASSENGER_PERMS.payments.manageMethods,
PASSENGER_PERMS.admin,
])
@@ -174,6 +183,7 @@ export class PaymentsController {
@Post("methods")
@PassengerStaff([
+ PASSENGER_PERMS.paymentMethods.manage,
PASSENGER_PERMS.payments.manageMethods,
PASSENGER_PERMS.admin,
])
@@ -187,6 +197,7 @@ export class PaymentsController {
@Patch("methods/:id")
@PassengerStaff([
+ PASSENGER_PERMS.paymentMethods.manage,
PASSENGER_PERMS.payments.manageMethods,
PASSENGER_PERMS.admin,
])
diff --git a/apps/edr-passenger-api/src/modules/schedules/routes.controller.ts b/apps/edr-passenger-api/src/modules/schedules/routes.controller.ts
index e751278ce..d468bba7c 100644
--- a/apps/edr-passenger-api/src/modules/schedules/routes.controller.ts
+++ b/apps/edr-passenger-api/src/modules/schedules/routes.controller.ts
@@ -1,9 +1,9 @@
-import { Body, Controller, Delete, Get, Param, Patch, Post, Put, Query, ParseIntPipe, UseGuards } from '@nestjs/common';
+import { Body, Controller, Delete, Get, Param, Patch, Post, Put, Query, ParseIntPipe } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiParam, ApiQuery, ApiResponse } from '@nestjs/swagger';
import { RoutesService } from './routes.service';
import { CreateRouteDto, AddRouteStopDto, UpdateRouteDto, SetRouteCoachTemplateDto } from './routes.dto';
-import { JwtGuard } from '../../common/jwt.guard';
-import { PassengerAdmin } from '../../common/passenger-guards';
+import { PassengerAdmin, PassengerStaff } from '../../common/passenger-guards';
+import { PASSENGER_PERMS } from '../../seed/passenger-permissions.registry';
@ApiTags('Routes')
@Controller('routes')
@@ -13,7 +13,7 @@ export class RoutesController {
// ── Routes ─────────────────────────────────────────────────────────────────
@Post()
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.routes.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({
summary: 'Create a reusable route with its ordered stops',
description: `Define the physical corridor once (e.g. ADD→ADM→AWS→DDW→AYS→DJI).
@@ -41,7 +41,7 @@ Route stops carry distanceKm for fare-by-distance calculations.`,
getRoute(@Param('id') id: string) { return this.service.getRoute(id); }
@Patch(':id')
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.routes.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Update route metadata (name, description, active flag, effectiveUntil)' })
@ApiParam({ name: 'id', description: 'Route UUID' })
@ApiResponse({ status: 200, description: 'Route updated' })
@@ -68,7 +68,7 @@ Route stops carry distanceKm for fare-by-distance calculations.`,
getStops(@Param('id') id: string) { return this.service.getStops(id); }
@Post(':id/stops')
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.routes.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Add a stop to an existing route' })
@ApiParam({ name: 'id', description: 'Route UUID' })
@ApiResponse({ status: 201, description: 'Stop added' })
@@ -108,7 +108,7 @@ Route stops carry distanceKm for fare-by-distance calculations.`,
getCoachTemplate(@Param('id') id: string) { return this.service.getRouteCoachTemplate(id); }
@Put(':id/coaches')
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.routes.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({
summary: 'Set the default coach lineup for this route',
description: 'Replaces the entire coach template. Coaches are auto-assigned in this order when a new schedule is created for this route.',
diff --git a/apps/edr-passenger-api/src/modules/schedules/schedules.controller.ts b/apps/edr-passenger-api/src/modules/schedules/schedules.controller.ts
index 9fc2ba851..a2d62d5aa 100644
--- a/apps/edr-passenger-api/src/modules/schedules/schedules.controller.ts
+++ b/apps/edr-passenger-api/src/modules/schedules/schedules.controller.ts
@@ -1,10 +1,10 @@
-import { Body, Controller, Delete, Get, Param, Patch, Post, Put, Query, ParseIntPipe, UseGuards } from '@nestjs/common';
+import { Body, Controller, Delete, Get, Param, Patch, Post, Put, Query, ParseIntPipe } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiParam, ApiQuery, ApiResponse } from '@nestjs/swagger';
import { IsPublic } from '@tria-plc/api-common/modules/auth/decorators/public.decorator';
import { SchedulesService } from './schedules.service';
import { CreateScheduleDto, UpdateScheduleDto, CreateFareRuleDto, UpdateScheduleStatusDto, UpdateStopTimeDto, ListSchedulesDto, BulkCreateSchedulesDto, BulkSchedulesResponseDto, TripStatus } from './schedules.dto';
-import { JwtGuard } from '../../common/jwt.guard';
-import { PassengerAdmin } from '../../common/passenger-guards';
+import { PassengerAdmin, PassengerStaff } from '../../common/passenger-guards';
+import { PASSENGER_PERMS } from '../../seed/passenger-permissions.registry';
@ApiTags('Schedule')
@Controller('schedules')
@@ -12,14 +12,14 @@ export class SchedulesController {
constructor(private service: SchedulesService) {}
@Post('bulk-generate')
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.schedules.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Bulk generate repetitive schedules' })
bulkGenerateSchedules(@Body() dto: BulkCreateSchedulesDto) {
return this.service.bulkGenerateSchedules(dto);
}
@Post()
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.schedules.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Create a train schedule from a route template' })
createSchedule(@Body() dto: CreateScheduleDto) { return this.service.createSchedule(dto); }
@@ -42,13 +42,13 @@ export class SchedulesController {
// ===== SPECIFIC ROUTES (must come BEFORE generic :id routes) =====
@Post('fares')
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.schedules.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Create a fare rule scoped to a schedule or route code' })
@ApiResponse({ status: 201, description: 'Fare rule created' })
createFareRule(@Body() dto: CreateFareRuleDto) { return this.service.createFareRule(dto); }
@Patch('fares/:id')
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.schedules.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Update a fare rule' })
@ApiParam({ name: 'id', description: 'FareRule UUID' })
@ApiResponse({ status: 200, description: 'Fare rule updated' })
@@ -65,7 +65,7 @@ export class SchedulesController {
deleteFareRule(@Param('id') id: string) { return this.service.deleteFareRule(id); }
@Post('segment-fares')
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.schedules.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Create a segment fare rule' })
createSegmentFareRule(@Body() dto: any) { return this.service.createSegmentFareRule(dto); }
@@ -76,7 +76,7 @@ export class SchedulesController {
getSegmentFares(@Param('routeId') routeId: string) { return this.service.getSegmentFares(routeId); }
@Patch('segment-fares/:id')
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.schedules.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Update a segment fare rule' })
@ApiParam({ name: 'id', description: 'SegmentFareRule UUID' })
updateSegmentFareRule(@Param('id') id: string, @Body() dto: any) { return this.service.updateSegmentFareRule(id, dto); }
@@ -97,7 +97,7 @@ export class SchedulesController {
getSchedule(@Param('id') id: string) { return this.service.getSchedule(id); }
@Patch(':id')
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.schedules.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Update a schedule (partial)' })
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
updateSchedule(@Param('id') id: string, @Body() dto: UpdateScheduleDto) {
@@ -105,7 +105,7 @@ export class SchedulesController {
}
@Patch(':id/status')
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.schedules.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Update schedule status' })
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
updateStatus(@Param('id') id: string, @Body() dto: UpdateScheduleStatusDto) {
@@ -127,7 +127,7 @@ export class SchedulesController {
getStops(@Param('id') id: string) { return this.service.getStops(id); }
@Patch(':id/stops/:sequence')
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.schedules.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Update a stop time' })
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
@ApiParam({ name: 'sequence', description: 'Stop sequence number' })
@@ -138,7 +138,7 @@ export class SchedulesController {
) { return this.service.updateStop(id, sequence, dto); }
@Put(':scheduleId/fares/:seatClassId')
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.schedules.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({
summary: 'Override fare for a specific seat class on a schedule',
description: 'Upserts a schedule-scoped FareRule. Expires any existing active rule for the same schedule+seatClass and creates a new one.',
@@ -186,12 +186,13 @@ export class SchedulesController {
}
@Post(':id/fares/sync')
+ @PassengerStaff([PASSENGER_PERMS.schedules.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Sync fares from fare engine' })
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
syncFares(@Param('id') id: string) { return this.service.syncFaresFromEngine(id); }
@Post(':id/coaches')
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.schedules.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Assign coaches to a schedule' })
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
assignCoaches(
diff --git a/apps/edr-passenger-api/src/modules/seat-classes/seat-classes.controller.ts b/apps/edr-passenger-api/src/modules/seat-classes/seat-classes.controller.ts
index 4eb6c212b..453256d7e 100644
--- a/apps/edr-passenger-api/src/modules/seat-classes/seat-classes.controller.ts
+++ b/apps/edr-passenger-api/src/modules/seat-classes/seat-classes.controller.ts
@@ -1,10 +1,10 @@
-import { Body, Controller, Delete, Get, Param, Patch, Post, UseGuards } from '@nestjs/common';
+import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiParam, ApiResponse, ApiBody } from '@nestjs/swagger';
import { IsPublic } from '@tria-plc/api-common/modules/auth/decorators/public.decorator';
import { SeatClassesService } from './seat-classes.service';
import { CreateSeatClassDto, UpdateSeatClassDto } from './seat-classes.dto';
-import { JwtGuard } from '../../common/jwt.guard';
-import { PassengerAdmin } from '../../common/passenger-guards';
+import { PassengerAdmin, PassengerStaff } from '../../common/passenger-guards';
+import { PASSENGER_PERMS } from '../../seed/passenger-permissions.registry';
@ApiTags('Seat Classes')
@Controller('seat-classes')
@@ -26,7 +26,7 @@ export class SeatClassesController {
getSeatClass(@Param('id') id: string) { return this.service.getSeatClass(id); }
@Post()
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.tariffRates.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Create a seat class' })
@ApiBody({ type: CreateSeatClassDto })
@ApiResponse({ status: 201, description: 'Seat class created' })
@@ -34,7 +34,7 @@ export class SeatClassesController {
createSeatClass(@Body() dto: CreateSeatClassDto) { return this.service.createSeatClass(dto); }
@Patch(':id')
- @UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.tariffRates.manage, PASSENGER_PERMS.admin]) @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Update a seat class' })
@ApiParam({ name: 'id', description: 'Seat class UUID' })
@ApiBody({ type: UpdateSeatClassDto })
diff --git a/apps/edr-passenger-api/src/modules/seats/seats.controller.ts b/apps/edr-passenger-api/src/modules/seats/seats.controller.ts
index fa233f45c..752b66390 100644
--- a/apps/edr-passenger-api/src/modules/seats/seats.controller.ts
+++ b/apps/edr-passenger-api/src/modules/seats/seats.controller.ts
@@ -21,7 +21,8 @@ import {
import { SeatsService } from "./seats.service";
import { HoldSeatsDto, ReleaseHoldDto } from "./seats.dto";
import { JwtGuard } from "../../common/jwt.guard";
-import { IamGuard } from "../../common/iam-adapter";
+import { PassengerStaff } from "../../common/passenger-guards";
+import { PASSENGER_PERMS } from "../../seed/passenger-permissions.registry";
@ApiTags("Seats")
@Controller("seats")
@@ -205,7 +206,7 @@ This makes it clear which segment of the route each seat is held for, enabling s
// ── Seat Block / Unblock ───────────────────────────────────────────────────
@Post(":seatId/block")
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.seats.manage, PASSENGER_PERMS.admin])
@ApiBearerAuth("IAM-auth")
@ApiOperation({ summary: "Block a seat (e.g., maintenance, damage)" })
@ApiParam({ name: "seatId", description: "Seat UUID" })
@@ -215,7 +216,7 @@ This makes it clear which segment of the route each seat is held for, enabling s
}
@Delete(":seatId/block")
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.seats.manage, PASSENGER_PERMS.admin])
@ApiBearerAuth("IAM-auth")
@ApiOperation({ summary: "Unblock a seat" })
@ApiParam({ name: "seatId", description: "Seat UUID" })
@@ -226,7 +227,7 @@ This makes it clear which segment of the route each seat is held for, enabling s
// ── Maintenance ───────────────────────────────────────────────────────────
@Post(":seatId/maintenance")
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.seats.manage, PASSENGER_PERMS.admin])
@ApiBearerAuth("IAM-auth")
@ApiOperation({ summary: "Set seat status to Under Maintenance" })
@ApiParam({ name: "seatId", description: "Seat UUID" })
@@ -236,7 +237,7 @@ This makes it clear which segment of the route each seat is held for, enabling s
}
@Delete(":seatId/maintenance")
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.seats.manage, PASSENGER_PERMS.admin])
@ApiBearerAuth("IAM-auth")
@ApiOperation({ summary: "Clear seat maintenance status" })
@ApiParam({ name: "seatId", description: "Seat UUID" })
@@ -247,7 +248,7 @@ This makes it clear which segment of the route each seat is held for, enabling s
// ── Remove Seat ────────────────────────────────────────────────────────────
@Patch(":seatId/remove")
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.seats.manage, PASSENGER_PERMS.admin])
@ApiBearerAuth("IAM-auth")
@ApiOperation({
summary: "Remove a seat by marking with negative seatNumber",
@@ -263,7 +264,7 @@ This makes it clear which segment of the route each seat is held for, enabling s
}
@Patch(":seatId/undo-remove")
- @UseGuards(IamGuard)
+ @PassengerStaff([PASSENGER_PERMS.seats.manage, PASSENGER_PERMS.admin])
@ApiBearerAuth("IAM-auth")
@ApiOperation({
summary: "Undo seat removal by restoring original seatNumber",
diff --git a/apps/edr-passenger-api/src/modules/stations/stations.controller.ts b/apps/edr-passenger-api/src/modules/stations/stations.controller.ts
index 0f367043b..5ddd64383 100644
--- a/apps/edr-passenger-api/src/modules/stations/stations.controller.ts
+++ b/apps/edr-passenger-api/src/modules/stations/stations.controller.ts
@@ -1,10 +1,10 @@
-import { Body, Controller, Get, Param, Post, Patch, Delete, UseGuards, Query } from '@nestjs/common';
+import { Body, Controller, Get, Param, Post, Patch, Delete, Query } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery, ApiResponse } from '@nestjs/swagger';
import { IsPublic } from '@tria-plc/api-common/modules/auth/decorators/public.decorator';
import { StationsService } from './stations.service';
import { CreateStationDto } from './stations.dto';
-import { JwtGuard } from '../../common/jwt.guard';
-import { PassengerAdmin } from '../../common/passenger-guards';
+import { PassengerAdmin, PassengerStaff } from '../../common/passenger-guards';
+import { PASSENGER_PERMS } from '../../seed/passenger-permissions.registry';
@ApiTags('Stations')
@Controller('stations')
@@ -79,8 +79,8 @@ export class StationsController {
findOne(@Param('id') id: string) { return this.service.findOne(id); }
@Post()
- @UseGuards(JwtGuard)
- @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.stations.manage, PASSENGER_PERMS.admin])
+ @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Create new station' })
@ApiResponse({
status: 201,
@@ -105,8 +105,8 @@ export class StationsController {
create(@Body() dto: CreateStationDto) { return this.service.create(dto); }
@Patch(':id')
- @UseGuards(JwtGuard)
- @ApiBearerAuth('JWT-auth')
+ @PassengerStaff([PASSENGER_PERMS.stations.manage, PASSENGER_PERMS.admin])
+ @ApiBearerAuth('IAM-auth')
@ApiOperation({ summary: 'Update station' })
@ApiResponse({
status: 200,
diff --git a/apps/edr-passenger-api/src/seed/edr-passenger.seed.ts b/apps/edr-passenger-api/src/seed/edr-passenger.seed.ts
index 578cf66ff..4313d5426 100644
--- a/apps/edr-passenger-api/src/seed/edr-passenger.seed.ts
+++ b/apps/edr-passenger-api/src/seed/edr-passenger.seed.ts
@@ -54,4 +54,19 @@ export const EDR_PASSENGER_ROLES: PassengerSeedRole[] = [
name: { en: 'EDR Passenger Finance' },
permissionKeys: [...ROLE_PERMISSION_PRESETS.finance],
},
+ {
+ key: 'edr_passenger_operations_manager',
+ name: { en: 'EDR Passenger Operations Manager' },
+ permissionKeys: [...ROLE_PERMISSION_PRESETS.operationsManager],
+ },
+ {
+ key: 'edr_passenger_marketing_manager',
+ name: { en: 'EDR Passenger Marketing Manager' },
+ permissionKeys: [...ROLE_PERMISSION_PRESETS.marketingManager],
+ },
+ {
+ key: 'edr_passenger_finance_manager',
+ name: { en: 'EDR Passenger Finance Manager' },
+ permissionKeys: [...ROLE_PERMISSION_PRESETS.financeManager],
+ },
];
diff --git a/apps/edr-passenger-api/src/seed/passenger-permissions.registry.ts b/apps/edr-passenger-api/src/seed/passenger-permissions.registry.ts
index bab7787b9..d62d5a261 100644
--- a/apps/edr-passenger-api/src/seed/passenger-permissions.registry.ts
+++ b/apps/edr-passenger-api/src/seed/passenger-permissions.registry.ts
@@ -34,6 +34,38 @@ export const PASSENGER_PERMISSIONS: PassengerPermissionSeed[] = [
perm('75b5ff62-a8e4-4331-b6e6-d53e1456d10e', 'edr_passenger_app:currencies:manage', 'Manage currencies'),
perm('4a47da9b-cf6e-4240-aff8-aadf01641c54', 'edr_passenger_app:notifications:send', 'Send notifications'),
perm('bfe3428f-8b85-4a36-87c6-33063b084bf3', 'edr_passenger_app:dashboard:view', 'View dashboard'),
+
+ // ── Master Data ────────────────────────────────────────────────────────────
+ perm('102969bc-13a2-4f4a-aa7f-ce4b2599ce82', 'edr_passenger_app:stations:view', 'View stations'),
+ perm('931cf6fc-8f41-46b6-82b8-b242f75d296e', 'edr_passenger_app:stations:manage', 'Manage stations'),
+ perm('82a801b3-2451-409b-99e8-9f4d3515d329', 'edr_passenger_app:trains:view', 'View trains'),
+ perm('e2a7f842-7691-4007-bd71-fd91c467044d', 'edr_passenger_app:trains:manage', 'Manage trains'),
+ perm('71de593c-ae4a-4d15-9f0a-b889eeb4910c', 'edr_passenger_app:coaches:view', 'View coaches'),
+ perm('39b3de2e-c779-4010-8ef3-d478f00a15c6', 'edr_passenger_app:coaches:manage', 'Manage coaches'),
+ perm('ba0fdd0b-6580-48a8-b31f-eb5ef76a2453', 'edr_passenger_app:seats:view', 'View seats'),
+ perm('6fb9affb-1885-446e-a8e4-962af9fae33f', 'edr_passenger_app:seats:manage', 'Manage seats'),
+ perm('b7b659d9-f453-41d3-a6db-72e671446214', 'edr_passenger_app:classes:view', 'View classes'),
+ perm('b2d06665-33f5-46d7-a895-785b5fb1896a', 'edr_passenger_app:classes:manage', 'Manage classes'),
+ perm('8731ee98-24c2-4f8b-9c06-cf3fa900a95a', 'edr_passenger_app:routes:view', 'View routes'),
+ perm('5851233c-78de-45b9-9d3f-63816d068622', 'edr_passenger_app:routes:manage', 'Manage routes'),
+ perm('c453bdf9-496a-4ac8-b733-8eb5dd5d591a', 'edr_passenger_app:schedules:view', 'View schedules'),
+ perm('d3f3cfd0-c7ce-47ab-be7f-bf3d6b40e488', 'edr_passenger_app:schedules:manage', 'Manage schedules'),
+
+ // ── Tourism ────────────────────────────────────────────────────────────────
+ perm('d78d810b-3003-4d81-92d5-41c437f3cc42', 'edr_passenger_app:packages:view', 'View packages'),
+ perm('dcfab0d9-1f80-4822-892a-e2851b549297', 'edr_passenger_app:packages:manage', 'Manage packages'),
+ perm('6d7ab68c-1b88-405d-9f92-b130055eece6', 'edr_passenger_app:inquiries:view', 'View package inquiries'),
+ perm('dbe5a07a-d12f-4a36-b191-0bb4f980054e', 'edr_passenger_app:inquiries:manage', 'Manage package inquiries'),
+
+ // ── Finance ────────────────────────────────────────────────────────────────
+ perm('4b6efd87-f230-4109-abe1-593e53cb0c10', 'edr_passenger_app:tariff_rates:view', 'View tariff rates'),
+ perm('94f17a59-397c-4c9c-a424-38a9c66c9e50', 'edr_passenger_app:tariff_rates:manage', 'Manage tariff rates'),
+ perm('2dc4eb75-5b28-4ead-a2d4-82ac95cd290c', 'edr_passenger_app:payments:view', 'View payments'),
+ perm('418b5f64-656b-4d44-a543-930ada9ec1a7', 'edr_passenger_app:payments:manage', 'Manage payments'),
+ perm('3f3d5479-af33-4883-867e-aae9e2aeeeca', 'edr_passenger_app:currencies:view', 'View currencies'),
+ perm('b4e63290-cc3a-4df8-9f2a-9ff726e86e36', 'edr_passenger_app:payment_methods:view', 'View payment methods'),
+ perm('f9fb6af2-e869-4e6e-938c-259643393315', 'edr_passenger_app:payment_methods:manage', 'Manage payment methods'),
+
perm('49fd28cd-5b58-4403-8e53-1df4b93cbbd2', 'edr_passenger_app:admin', 'Full admin access'),
];
@@ -54,10 +86,57 @@ export const PASSENGER_PERMS = {
manage: 'edr_passenger_app:tickets:manage',
},
payments: {
+ view: 'edr_passenger_app:payments:view',
+ manage: 'edr_passenger_app:payments:manage',
+ // legacy keys — retained as aliases for backward compatibility
viewAll: 'edr_passenger_app:payments:view_all',
refund: 'edr_passenger_app:payments:refund',
manageMethods: 'edr_passenger_app:payments:manage_methods',
},
+ paymentMethods: {
+ view: 'edr_passenger_app:payment_methods:view',
+ manage: 'edr_passenger_app:payment_methods:manage',
+ },
+ stations: {
+ view: 'edr_passenger_app:stations:view',
+ manage: 'edr_passenger_app:stations:manage',
+ },
+ trains: {
+ view: 'edr_passenger_app:trains:view',
+ manage: 'edr_passenger_app:trains:manage',
+ },
+ coaches: {
+ view: 'edr_passenger_app:coaches:view',
+ manage: 'edr_passenger_app:coaches:manage',
+ },
+ seats: {
+ view: 'edr_passenger_app:seats:view',
+ manage: 'edr_passenger_app:seats:manage',
+ },
+ classes: {
+ view: 'edr_passenger_app:classes:view',
+ manage: 'edr_passenger_app:classes:manage',
+ },
+ routes: {
+ view: 'edr_passenger_app:routes:view',
+ manage: 'edr_passenger_app:routes:manage',
+ },
+ schedules: {
+ view: 'edr_passenger_app:schedules:view',
+ manage: 'edr_passenger_app:schedules:manage',
+ },
+ packages: {
+ view: 'edr_passenger_app:packages:view',
+ manage: 'edr_passenger_app:packages:manage',
+ },
+ inquiries: {
+ view: 'edr_passenger_app:inquiries:view',
+ manage: 'edr_passenger_app:inquiries:manage',
+ },
+ tariffRates: {
+ view: 'edr_passenger_app:tariff_rates:view',
+ manage: 'edr_passenger_app:tariff_rates:manage',
+ },
reports: {
view: 'edr_passenger_app:reports:view',
},
@@ -73,6 +152,7 @@ export const PASSENGER_PERMS = {
manage: 'edr_passenger_app:agents:manage',
},
currencies: {
+ view: 'edr_passenger_app:currencies:view',
manage: 'edr_passenger_app:currencies:manage',
},
notifications: {
@@ -126,9 +206,36 @@ export const ROLE_PERMISSION_PRESETS = {
],
finance: [
+ PASSENGER_PERMS.payments.view,
PASSENGER_PERMS.payments.viewAll,
PASSENGER_PERMS.payments.refund,
PASSENGER_PERMS.reports.view,
PASSENGER_PERMS.dashboard.view,
],
+
+ operationsManager: [
+ PASSENGER_PERMS.stations.view, PASSENGER_PERMS.stations.manage,
+ PASSENGER_PERMS.trains.view, PASSENGER_PERMS.trains.manage,
+ PASSENGER_PERMS.coaches.view, PASSENGER_PERMS.coaches.manage,
+ PASSENGER_PERMS.seats.view, PASSENGER_PERMS.seats.manage,
+ PASSENGER_PERMS.classes.view, PASSENGER_PERMS.classes.manage,
+ PASSENGER_PERMS.routes.view, PASSENGER_PERMS.routes.manage,
+ PASSENGER_PERMS.schedules.view, PASSENGER_PERMS.schedules.manage,
+ PASSENGER_PERMS.dashboard.view,
+ ],
+
+ marketingManager: [
+ PASSENGER_PERMS.packages.view, PASSENGER_PERMS.packages.manage,
+ PASSENGER_PERMS.inquiries.view, PASSENGER_PERMS.inquiries.manage,
+ PASSENGER_PERMS.dashboard.view,
+ ],
+
+ financeManager: [
+ PASSENGER_PERMS.tariffRates.view, PASSENGER_PERMS.tariffRates.manage,
+ PASSENGER_PERMS.payments.view, PASSENGER_PERMS.payments.manage,
+ PASSENGER_PERMS.currencies.view, PASSENGER_PERMS.currencies.manage,
+ PASSENGER_PERMS.paymentMethods.view, PASSENGER_PERMS.paymentMethods.manage,
+ PASSENGER_PERMS.reports.view,
+ PASSENGER_PERMS.dashboard.view,
+ ],
} as const;
diff --git a/apps/edr-passenger-web/backoffice/src/app/payment-methods/page.tsx b/apps/edr-passenger-web/backoffice/src/app/payment-methods/page.tsx
index 8937497c6..4e6a71950 100644
--- a/apps/edr-passenger-web/backoffice/src/app/payment-methods/page.tsx
+++ b/apps/edr-passenger-web/backoffice/src/app/payment-methods/page.tsx
@@ -9,14 +9,13 @@ import ActionButton from '@/components/ui/ActionButton';
import Modal from '@/components/ui/Modal';
import ConfirmDialog from '@/components/ui/ConfirmDialog';
import { apiClient, paymentsApi } from '@/lib/api';
-import { PermissionGuard } from '@/components/layout/PermissionGuard';
import { usePermission } from '@/lib/use-permission';
import { PERMS } from '@/lib/permissions';
export default function PaymentMethodsPage() {
- const canManagePayments = usePermission(PERMS.payments.manage);
+ const canManageMethods = usePermission(PERMS.paymentMethods.manage);
const canManageAdmin = usePermission(PERMS.admin);
- const canManage = canManagePayments || canManageAdmin;
+ const canManage = canManageMethods || canManageAdmin;
const [createModalOpen, setCreateModalOpen] = useState(false);
const [editModalOpen, setEditModalOpen] = useState(false);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
@@ -228,11 +227,11 @@ export default function PaymentMethodsPage() {