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 e72308a4d..22dec2a37 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 @@ -1059,32 +1059,34 @@ export class TrainSchedulingService { } private async runWarehouseArrivalAutomation(scheduleId: string) { - const [schedule]: Array<{ - originCountry: string | null; - destinationCountry: string | null; - destinationCode: string | null; - destinationName: string | null; - }> = await this.dataSource.query( - `SELECT oy.country AS "originCountry", - dy.country AS "destinationCountry", - dy.code AS "destinationCode", - dy.name AS "destinationName" - 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 - WHERE ts.id = $1 AND ts.deleted_at IS NULL - LIMIT 1`, - [scheduleId], - ); - - if (!schedule) return { status: 'SKIPPED', reason: 'Train schedule not found' }; - - const direction = deriveTradeDirection( - { country: schedule.originCountry }, - { country: schedule.destinationCountry }, - ); - + // Runs after the arrival transaction has committed — must never throw, or a + // successfully arrived train reports a 500 and looks stuck to the operator. + let direction: string | undefined; try { + const [schedule]: Array<{ + originCountry: string | null; + destinationCountry: string | null; + destinationCode: string | null; + destinationName: string | null; + }> = await this.dataSource.query( + `SELECT oy.country AS "originCountry", + dy.country AS "destinationCountry", + dy.code AS "destinationCode", + dy.label AS "destinationName" + 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 + WHERE ts.id = $1 AND ts.deleted_at IS NULL + LIMIT 1`, + [scheduleId], + ); + + if (!schedule) return { status: 'SKIPPED', reason: 'Train schedule not found' }; + + direction = deriveTradeDirection( + { country: schedule.originCountry }, + { country: schedule.destinationCountry }, + ); if (direction === 'IMPORT') { return { direction,