mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 17:26:24 +00:00
fix(airports): use Bahrain time for Bahrain flights
Correct the airport data and repair affected flight endpoints and metadata during upgrade. Preserve stored local flight times and legacy metadata encoding. Closes #3294
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
// Build server/assets/airports.json from OurAirports (davidmegginson.github.io/ourairports-data).
|
||||
// License: Public Domain. Keeps large/medium airports with an IATA code, small ones only with scheduled service;
|
||||
// timezone derived from coords via tz-lookup.
|
||||
// Timezones come from coordinates via tz-lookup, with known country corrections.
|
||||
import fs from 'node:fs';
|
||||
import https from 'node:https';
|
||||
import path from 'node:path';
|
||||
@@ -11,6 +11,8 @@ import tzLookup from 'tz-lookup';
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const OUT = path.join(__dirname, '..', 'assets', 'airports.json');
|
||||
const SRC = 'https://davidmegginson.github.io/ourairports-data/airports.csv';
|
||||
// The coordinate lookup places Bahrain's airport in Iran. Bahrain has one zone.
|
||||
const COUNTRY_TIMEZONE_OVERRIDES = new Map([['BH', 'Asia/Bahrain']]);
|
||||
|
||||
function fetchText(url) {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -97,11 +99,12 @@ for (let i = 1; i < rows.length; i++) {
|
||||
if (r[TYPE] === 'small_airport' && r[SERVICE] !== 'yes') continue;
|
||||
const lat = Number(r[LAT]);
|
||||
const lng = Number(r[LNG]);
|
||||
const country = r[COUNTRY] || '';
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lng)) continue;
|
||||
|
||||
let tz = null;
|
||||
try {
|
||||
tz = tzLookup(lat, lng);
|
||||
tz = COUNTRY_TIMEZONE_OVERRIDES.get(country) ?? tzLookup(lat, lng);
|
||||
} catch {
|
||||
skippedNoTz++;
|
||||
continue;
|
||||
@@ -116,7 +119,7 @@ for (let i = 1; i < rows.length; i++) {
|
||||
icao: r[ICAO]?.trim().toUpperCase() || null,
|
||||
name: r[NAME],
|
||||
city: r[MUNICIPALITY] || '',
|
||||
country: r[COUNTRY] || '',
|
||||
country,
|
||||
lat: Math.round(lat * 1e6) / 1e6,
|
||||
lng: Math.round(lng * 1e6) / 1e6,
|
||||
tz,
|
||||
@@ -141,7 +144,7 @@ const previous = fs.existsSync(OUT) ? JSON.parse(fs.readFileSync(OUT, 'utf8')) :
|
||||
let kept = 0;
|
||||
for (const a of previous) {
|
||||
if (seen.has(a.iata)) continue;
|
||||
seen.set(a.iata, a);
|
||||
seen.set(a.iata, { ...a, tz: COUNTRY_TIMEZONE_OVERRIDES.get(a.country) ?? a.tz });
|
||||
kept++;
|
||||
}
|
||||
const unique = Array.from(seen.values()).sort((a, b) => a.iata.localeCompare(b.iata));
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { forEachInOrder } from '../../utils/for-each-in-order';
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
const WRONG_ZONE = 'Asia/Tehran';
|
||||
const BAHRAIN_ZONE = 'Asia/Bahrain';
|
||||
const BAHRAIN_CODES = ['BAH', 'OBBI'] as const;
|
||||
|
||||
function correctedMetadata(text: string): string | null {
|
||||
let value: unknown;
|
||||
let encodedAgain = false;
|
||||
try {
|
||||
value = JSON.parse(text);
|
||||
// Older bookings could store a JSON string containing the metadata JSON.
|
||||
if (typeof value === 'string') {
|
||||
encodedAgain = true;
|
||||
value = JSON.parse(value);
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
||||
|
||||
const metadata = value as Record<string, unknown>;
|
||||
let changed = false;
|
||||
for (const side of ['departure', 'arrival'] as const) {
|
||||
const airport = metadata[`${side}_airport`];
|
||||
const timezone = `${side}_timezone`;
|
||||
if (
|
||||
typeof airport === 'string' &&
|
||||
BAHRAIN_CODES.some((code) => code === airport.trim().toUpperCase()) &&
|
||||
metadata[timezone] === WRONG_ZONE
|
||||
) {
|
||||
metadata[timezone] = BAHRAIN_ZONE;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (!changed) return null;
|
||||
const json = JSON.stringify(metadata);
|
||||
return encodedAgain ? JSON.stringify(json) : json;
|
||||
}
|
||||
|
||||
/**
|
||||
* The airport dataset used the wrong zone for Bahrain. Repair its exact persisted
|
||||
* airport/zone pair in flight endpoints and metadata, including legacy metadata-only
|
||||
* bookings. The stored wall-clock times are already local and need no rewrite.
|
||||
*/
|
||||
export class Migration20200101046640_bahrain_flights_keep_bahrain_time extends Migration {
|
||||
override name = 'Migration20200101046640_bahrain_flights_keep_bahrain_time';
|
||||
|
||||
override async up(): Promise<void> {
|
||||
await this.execute(
|
||||
`UPDATE reservation_endpoints SET timezone = ?
|
||||
WHERE timezone = ? AND UPPER(TRIM(code)) IN (?, ?)
|
||||
AND reservation_id IN (SELECT id FROM reservations WHERE type = 'flight')`,
|
||||
[BAHRAIN_ZONE, WRONG_ZONE, ...BAHRAIN_CODES],
|
||||
);
|
||||
const rows = (await this.execute(
|
||||
"SELECT id, metadata FROM reservations WHERE type = 'flight' AND metadata LIKE ?",
|
||||
[`%${WRONG_ZONE}%`],
|
||||
)) as { id: number; metadata: string }[];
|
||||
|
||||
await forEachInOrder(rows, async ({ id, metadata }) => {
|
||||
const corrected = correctedMetadata(metadata);
|
||||
if (corrected !== null) {
|
||||
await this.execute('UPDATE reservations SET metadata = ? WHERE id = ?', [corrected, id]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -7,17 +7,20 @@ import { BudgetItems } from '../../src/db/entities/BudgetItems.entity';
|
||||
import { DayAccommodations } from '../../src/db/entities/DayAccommodations.entity';
|
||||
import { Days } from '../../src/db/entities/Days.entity';
|
||||
import { ReservationDayPositions } from '../../src/db/entities/ReservationDayPositions.entity';
|
||||
import { ReservationEndpoints } from '../../src/db/entities/ReservationEndpoints.entity';
|
||||
import { Reservations } from '../../src/db/entities/Reservations.entity';
|
||||
import { Migration20200101046640_bahrain_flights_keep_bahrain_time } from '../../src/db/migrations/Migration20200101046640_bahrain_flights_keep_bahrain_time';
|
||||
import { authCookie } from '../helpers/auth';
|
||||
import { makeDayAssignment } from '../helpers/factories/itinerary';
|
||||
import { makePlace } from '../helpers/factories/places';
|
||||
import { makeReservation } from '../helpers/factories/reservations';
|
||||
import { makeReservation, makeReservationEndpoint } from '../helpers/factories/reservations';
|
||||
import { findRow, findRows, updateRows } from '../helpers/factories/rows';
|
||||
import { makeDay, makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { resetDatabase } from '../helpers/reset-database';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { AbstractSqlDriver } from '@mikro-orm/sql';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
|
||||
import type { Application } from 'express';
|
||||
@@ -49,6 +52,60 @@ afterAll(async () => {
|
||||
await nestApp.close();
|
||||
});
|
||||
|
||||
it('repairs only the wrong Bahrain timezone on existing flight bookings (#3294)', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id);
|
||||
const timezone = 'Asia/Tehran';
|
||||
const correctZone = 'Asia/Bahrain';
|
||||
const reservationTime = '2026-12-18T18:30';
|
||||
const metadata = {
|
||||
departure_airport: 'BAH',
|
||||
departure_timezone: timezone,
|
||||
arrival_airport: 'IKA',
|
||||
arrival_timezone: timezone,
|
||||
airline: 'Gulf Air',
|
||||
};
|
||||
const flight = await makeReservation(orm, trip.id, {
|
||||
reservation_time: reservationTime,
|
||||
metadata: JSON.stringify(metadata),
|
||||
});
|
||||
const legacy = await makeReservation(orm, trip.id, {
|
||||
metadata: JSON.stringify({ arrival_airport: ' bah ', arrival_timezone: timezone }),
|
||||
});
|
||||
const doubleEncoded = await makeReservation(orm, trip.id, { metadata: JSON.stringify(JSON.stringify(metadata)) });
|
||||
const train = await makeReservation(orm, trip.id, { type: 'train', metadata: JSON.stringify(metadata) });
|
||||
const malformed = await makeReservation(orm, trip.id, { metadata: '{"arrival_timezone":"Asia/Tehran"' });
|
||||
|
||||
const local = { local_date: '2026-12-18', local_time: '18:30' };
|
||||
const from = await makeReservationEndpoint(orm, flight.id, { code: 'BAH', timezone, ...local });
|
||||
const stop = await makeReservationEndpoint(orm, flight.id, { role: 'stop', code: 'obbi', timezone });
|
||||
const iran = await makeReservationEndpoint(orm, flight.id, { role: 'to', code: 'IKA', timezone });
|
||||
const alreadyCorrect = await makeReservationEndpoint(orm, flight.id, { code: 'BAH', timezone: correctZone });
|
||||
const station = await makeReservationEndpoint(orm, train.id, { code: 'BAH', timezone });
|
||||
|
||||
const driver = orm.em.getDriver();
|
||||
if (!(driver instanceof AbstractSqlDriver)) throw new Error('Expected a SQL driver');
|
||||
await new Migration20200101046640_bahrain_flights_keep_bahrain_time(driver, orm.config).up();
|
||||
|
||||
expect(await findRow(orm, Reservations, { id: flight.id })).toMatchObject({
|
||||
reservation_time: reservationTime,
|
||||
metadata: JSON.stringify({ ...metadata, departure_timezone: correctZone }),
|
||||
});
|
||||
expect((await findRow(orm, Reservations, { id: legacy.id }))?.metadata).toBe(
|
||||
JSON.stringify({ arrival_airport: ' bah ', arrival_timezone: correctZone }),
|
||||
);
|
||||
expect((await findRow(orm, Reservations, { id: doubleEncoded.id }))?.metadata).toBe(
|
||||
JSON.stringify(JSON.stringify({ ...metadata, departure_timezone: correctZone })),
|
||||
);
|
||||
expect((await findRow(orm, Reservations, { id: train.id }))?.metadata).toBe(train.metadata);
|
||||
expect((await findRow(orm, Reservations, { id: malformed.id }))?.metadata).toBe(malformed.metadata);
|
||||
expect(await findRow(orm, ReservationEndpoints, { id: from.id })).toMatchObject({ timezone: correctZone, ...local });
|
||||
expect((await findRow(orm, ReservationEndpoints, { id: stop.id }))?.timezone).toBe(correctZone);
|
||||
expect((await findRow(orm, ReservationEndpoints, { id: iran.id }))?.timezone).toBe(timezone);
|
||||
expect((await findRow(orm, ReservationEndpoints, { id: station.id }))?.timezone).toBe(timezone);
|
||||
expect((await findRow(orm, ReservationEndpoints, { id: alreadyCorrect.id }))?.timezone).toBe(correctZone);
|
||||
});
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Create reservation
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -129,6 +129,7 @@ const UNNUMBERED = [
|
||||
'Migration20200101046610_a_vote_remembers_when_it_last_changed',
|
||||
'Migration20200101046620_a_journey_link_can_ask_for_a_password_and_run_out',
|
||||
'Migration20200101046630_a_journey_gathers_comments_and_followers',
|
||||
'Migration20200101046640_bahrain_flights_keep_bahrain_time',
|
||||
];
|
||||
// The last step the positional runner ever had; planLegacyBaseline refuses a
|
||||
// schema_version past it.
|
||||
|
||||
@@ -25,4 +25,9 @@ describe('bundled airport dataset', () => {
|
||||
expect(findByIata('RJL')).toMatchObject({ icao: 'LERJ', city: 'Logroño', country: 'ES', tz: 'Europe/Madrid' });
|
||||
expect(findByIata('DXN')?.country).toBe('IN');
|
||||
});
|
||||
|
||||
it('AIRPORT-ASSET-004: gives Bahrain International Airport its local timezone (#3294)', () => {
|
||||
expect(findByIata('BAH')).toMatchObject({ icao: 'OBBI', country: 'BH', tz: 'Asia/Bahrain' });
|
||||
expect(findByIata('IKA')?.tz).toBe('Asia/Tehran');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user