From 3fe4ea72acafe7421472fd65b0c23fa7bf74513d Mon Sep 17 00:00:00 2001 From: Marshal Date: Mon, 13 Jul 2026 11:47:27 +0000 Subject: [PATCH] update train scheduling logic to clear trainScheduleId when unassigning bookings --- .../src/modules/bookings/bookings.repository.ts | 7 ++++++- .../train-scheduling/train-scheduling.service.ts | 14 ++++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/apps/edr-freight-api/src/modules/bookings/bookings.repository.ts b/apps/edr-freight-api/src/modules/bookings/bookings.repository.ts index 39bb7ef78..6a04014a7 100644 --- a/apps/edr-freight-api/src/modules/bookings/bookings.repository.ts +++ b/apps/edr-freight-api/src/modules/bookings/bookings.repository.ts @@ -1269,7 +1269,12 @@ export class BookingsRepository extends BaseRepository { fields: Partial< Pick< Booking, - 'schedulingStatus' | 'wagonsRequired' | 'scheduledAt' | 'holdStartedAt' | 'holdExpiresAt' + | 'schedulingStatus' + | 'wagonsRequired' + | 'scheduledAt' + | 'holdStartedAt' + | 'holdExpiresAt' + | 'trainScheduleId' > >, manager?: EntityManager, 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 f5d335efa..c0aa14bd9 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 @@ -1387,9 +1387,13 @@ export class TrainSchedulingService { const booking = await this.bookingsRepository.findById(bookingId); const schedulingStatus = this.resolvePostUnassignStatus(booking); + // Clear the schedule pointer too: unassign fully detaches the booking from + // this train. Leaving trainScheduleId set glued the booking to a schedule + // that may then be dispatched/cancelled/deleted, orphaning it — the + // assign-bookings parity guard would reject it from every OTHER schedule. await this.bookingsRepository.updateSchedulingFields( bookingId, - { schedulingStatus, wagonsRequired: null }, + { schedulingStatus, wagonsRequired: null, trainScheduleId: null }, manager, ); @@ -3043,9 +3047,15 @@ export class TrainSchedulingService { } for (const sb of schedule.scheduleBookings ?? []) { const booking = await this.bookingsRepository.findById(sb.bookingId); + // Detach from the cancelled schedule — clear the pointer so the freed + // booking can be assigned to another train. Leaving it set orphans the + // booking against a schedule that is about to be gone. await this.bookingsRepository.updateSchedulingFields( sb.bookingId, - { schedulingStatus: this.resolvePostUnassignStatus(booking) }, + { + schedulingStatus: this.resolvePostUnassignStatus(booking), + trainScheduleId: null, + }, manager, ); }