diff --git a/server/src/index.ts b/server/src/index.ts index 117a75510..d8d1a3249 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -11,6 +11,7 @@ import type { INestApplication } from '@nestjs/common'; import { buildApp } from './bootstrap'; import { BackupService } from './nest/backup/backup.service'; import { PlacePhotoCacheService } from './nest/place-photos/place-photo-cache.service'; +import { AirtrailSyncService } from './nest/integrations/airtrail-sync.service'; // Create upload and data directories on startup. // Every uploads subdir the app writes to must be listed here (#1762): a dir @@ -97,6 +98,10 @@ const onListen = () => { // The container singleton, not a fresh instance: the in-flight dedup and the // known-on-disk set only work if the whole process shares one. placePhotos: nestApp.get(PlacePhotoCacheService), + // The last lazy require() in the cron path. It used to fail inside the tick, + // logged as "AirTrail sync tick failed", where a boot-time wiring mistake + // belongs at boot. + airtrail: nestApp.get(AirtrailSyncService), }); scheduler.start(); scheduler.startTripReminders(); diff --git a/server/src/nest/integrations/airtrail-import.controller.ts b/server/src/nest/integrations/airtrail-import.controller.ts index 764b7d2fe..282972918 100644 --- a/server/src/nest/integrations/airtrail-import.controller.ts +++ b/server/src/nest/integrations/airtrail-import.controller.ts @@ -9,7 +9,7 @@ import { AirtrailImportDto } from './airtrail.dto'; import type { AirtrailImportResult } from '@trek/shared'; import { PermissionsService } from '../permissions/permissions.service'; import { DatabaseService } from '../database/database.service'; -import { importAirtrailFlights } from '../../services/airtrail/airtrailImport'; +import { AirtrailImportService } from './airtrail-import.service'; /** * POST /api/trips/:tripId/reservations/import/airtrail — turn selected AirTrail @@ -23,6 +23,7 @@ export class AirtrailImportController { constructor( private readonly permissions: PermissionsService, private readonly db: DatabaseService, + private readonly imports: AirtrailImportService, ) {} private requireEdit(tripId: string, user: User): void { @@ -42,7 +43,7 @@ export class AirtrailImportController { ): Promise { this.requireEdit(tripId, user); try { - return await importAirtrailFlights(tripId, user.id, body.flightIds, socketId, body.connections ?? []); + return await this.imports.importAirtrailFlights(tripId, user.id, body.flightIds, socketId, body.connections ?? []); } catch (err: any) { throw new HttpException({ error: err?.message || 'AirTrail import failed' }, err?.status === 400 ? 400 : 502); } diff --git a/server/src/nest/integrations/airtrail-import.service.ts b/server/src/nest/integrations/airtrail-import.service.ts new file mode 100644 index 000000000..280f86b0d --- /dev/null +++ b/server/src/nest/integrations/airtrail-import.service.ts @@ -0,0 +1,307 @@ +import { Injectable } from '@nestjs/common'; +import type { AirtrailImportResult } from '@trek/shared'; +import { DatabaseService } from '../database/database.service'; +import { RealtimeService } from '../realtime/realtime.service'; +import { ReservationsService } from '../reservations/reservations.service'; +import { AirtrailRequestError, type AirtrailFlightRaw } from './airtrail.client'; +import { AirtrailClient } from './airtrail.client'; +import { AirtrailService } from './airtrail.service'; +import { canonicalHash, mapFlightToReservation, mapFlightsToMultiLegReservation, normalizeFlight } from './airtrail.mapper'; + +interface ExistingFlightRow { + id: number; + reservation_time: string | null; + metadata: string | null; +} + +interface EndpointRow { + reservation_id: number; + code: string | null; + local_date: string | null; + sequence: number; +} + +function depDate(t: string | null): string | null { + return t && /^\d{4}-\d{2}-\d{2}/.test(t) ? t.slice(0, 10) : null; +} + +/** A loose "same physical flight" key: flight number + date, else route + date. */ +function softSignature( + date: string | null, + flightNumber: string | null, + fromCode: string | null, + toCode: string | null, +): string | null { + if (!date) return null; + if (flightNumber) return `fn:${flightNumber.toUpperCase()}@${date}`; + if (fromCode && toCode) return `rt:${fromCode.toUpperCase()}-${toCode.toUpperCase()}@${date}`; + return null; +} + +/** The signature a single AirTrail flight would get as its own reservation. */ +function flightSignature(flight: AirtrailFlightRaw): string | null { + const mapped = mapFlightToReservation(flight); + return softSignature( + depDate(mapped.reservation_time), + (mapped.metadata.flight_number as string) ?? null, + mapped.endpoints.find(e => e.role === 'from')?.code ?? null, + mapped.endpoints.find(e => e.role === 'to')?.code ?? null, + ); +} + +/** + * Order a requested join group by departure and verify it forms a real + * connection chain: each flight leaves the airport the previous one arrived at, + * onward in time and within 24 h — the same window the booking import applies + * to same-PNR legs. A leg landing back at the chain's origin is a return + * flight, never a connection. Flights without usable instants can't prove any + * of this, so they don't chain. Returns the ordered chain, or null when the + * flights don't chain; the members then import individually, exactly as if no + * join had been requested. + */ +function orderConnectionChain(group: AirtrailFlightRaw[]): AirtrailFlightRaw[] | null { + if (group.length < 2) return null; + const norm = group.map(raw => ({ raw, n: normalizeFlight(raw) })); + const depMs = (n: (typeof norm)[number]['n']): number => (n.departure ? Date.parse(n.departure) : NaN); + if (norm.some(x => Number.isNaN(depMs(x.n)))) return null; + norm.sort((a, b) => depMs(a.n) - depMs(b.n)); + const origin = norm[0].n.fromCode; + for (let i = 1; i < norm.length; i++) { + const prev = norm[i - 1].n; + const next = norm[i].n; + if (!prev.toCode || !next.fromCode || prev.toCode.toUpperCase() !== next.fromCode.toUpperCase()) return null; + if (origin && next.toCode && next.toCode.toUpperCase() === origin.toUpperCase()) return null; + const arrMs = prev.arrival ? Date.parse(prev.arrival) : NaN; + if (Number.isNaN(arrMs)) return null; + const gap = depMs(next) - arrMs; + if (gap < 0 || gap > 24 * 3600 * 1000) return null; + } + return norm.map(x => x.raw); +} + +/** + * Import the given AirTrail flights into a trip as reservations (type:'flight'), + * recording the AirTrail linkage for two-way sync and broadcasting each one live. + * + * `connections` names chains of selected flights to import as ONE multi-leg + * reservation each, with the connection airports as layover stops (#1535). A + * joined booking is created detached from live sync (sync_enabled = 0): AirTrail + * has no multi-leg flight entity it could round-trip to, and a pull would + * flatten the layover again. All member ids are kept in metadata.airtrail_ids + * so none of the legs is offered for re-import. + * + * Dedup: a flight already linked to this trip is skipped ('already-imported'); a + * flight that looks like one already in the trip — e.g. the same flight another + * member already imported from their own AirTrail — is skipped ('already-in-trip'). + * The server re-fetches the flights by id with the caller's own key, so the client + * cannot inject arbitrary flight data. + */ + +/** + * Importing selected AirTrail flights into a trip. + * + * Folded out of services/airtrail/airtrailImport.ts. The dedupe pipeline, the + * connection-chain detection and the day matching are unchanged; the db + * singleton, the raw websocket broadcast and the reservations bridge are + * injected now. + */ +@Injectable() +export class AirtrailImportService { + constructor( + private readonly db: DatabaseService, + private readonly realtime: RealtimeService, + private readonly reservations: ReservationsService, + private readonly client: AirtrailClient, + private readonly airtrail: AirtrailService, + ) {} + + async importAirtrailFlights( + tripId: string | number, + userId: number, + flightIds: string[], + socketId: string | undefined, + connections: string[][] = [], + ): Promise { + const creds = this.airtrail.getAirtrailCredentials(userId); + if (!creds) throw new AirtrailRequestError('AirTrail is not connected', 400); + + const wanted = new Set(flightIds.map(String)); + const selected = (await this.client.listFlights(creds)).filter(f => wanted.has(String(f.id))); + const byId = new Map(selected.map(f => [String(f.id), f])); + + const result: AirtrailImportResult = { imported: [], skipped: [] }; + + // Every AirTrail id already linked to this trip: the external_id column plus + // the metadata.airtrail_ids of joined multi-leg imports. + const linkedIds = new Set(); + const linkedRows = this.db.connection + .prepare("SELECT external_id, metadata FROM reservations WHERE trip_id = ? AND external_source = 'airtrail'") + .all(tripId) as { external_id: string | null; metadata: string | null }[]; + for (const row of linkedRows) { + if (row.external_id) linkedIds.add(row.external_id); + try { + const ids = row.metadata ? JSON.parse(row.metadata).airtrail_ids : null; + if (Array.isArray(ids)) for (const id of ids) linkedIds.add(String(id)); + } catch { + /* malformed metadata — ignore */ + } + } + + const existing = this.db.connection + .prepare("SELECT r.id, r.reservation_time, r.metadata FROM reservations r WHERE r.trip_id = ? AND r.type = 'flight'") + .all(tripId) as ExistingFlightRow[]; + const endpointsByReservation = new Map(); + const endpointRows = this.db.connection + .prepare( + `SELECT e.reservation_id, e.code, e.local_date, e.sequence + FROM reservation_endpoints e JOIN reservations r ON r.id = e.reservation_id + WHERE r.trip_id = ? AND r.type = 'flight' ORDER BY e.sequence`, + ) + .all(tripId) as EndpointRow[]; + for (const ep of endpointRows) { + const list = endpointsByReservation.get(ep.reservation_id); + if (list) list.push(ep); + else endpointsByReservation.set(ep.reservation_id, [ep]); + } + + const days = this.db.prepare('SELECT id, date FROM days WHERE trip_id = ?').all(tripId) as { id: number; date: string | null }[]; + const dayIdByDate = new Map(); + const dayDateById = new Map(); + for (const day of days) { + if (!day.date) continue; + if (!dayIdByDate.has(day.date)) dayIdByDate.set(day.date, day.id); + dayDateById.set(day.id, day.date); + } + const resolveDayId = (date: string | null): number | null => (date ? (dayIdByDate.get(date) ?? null) : null); + + const existingSigs = new Set(); + for (const row of existing) { + let meta: Record = {}; + try { + meta = row.metadata ? JSON.parse(row.metadata) : {}; + } catch { + /* malformed metadata — ignore */ + } + const eps = endpointsByReservation.get(row.id) ?? []; + const legs: any[] | null = Array.isArray(meta.legs) ? meta.legs : null; + if (legs && legs.length > 1) { + // One signature per leg. The leg's departure date comes from its own + // dep_day_id when set; the positional endpoint fallback is only sound + // while no endpoint was dropped (e.g. for missing coordinates) — a + // misaligned date would produce a WRONG signature, worse than none. + const aligned = eps.length === legs.length + 1; + legs.forEach((leg, i) => { + const legDate = (typeof leg?.dep_day_id === 'number' ? dayDateById.get(leg.dep_day_id) : null) + ?? (aligned ? eps[i]?.local_date : null) + ?? null; + const sig = softSignature(legDate, leg?.flight_number ?? null, leg?.from ?? null, leg?.to ?? null); + if (sig) existingSigs.add(sig); + }); + } else { + const from = eps[0]?.code ?? null; + const to = eps.length > 1 ? eps[eps.length - 1].code : null; + const sig = softSignature(depDate(row.reservation_time), meta.flight_number ?? null, from, to); + if (sig) existingSigs.add(sig); + } + } + + // Resolve the requested joins into validated chains. A group that doesn't + // chain, overlaps another, or contains an already-linked/duplicate flight + // degrades to individual imports rather than failing the whole request. + const groupedIds = new Set(); + const chains: AirtrailFlightRaw[][] = []; + for (const ids of connections) { + const unique = [...new Set(ids.map(String))]; + const members = unique.map(id => byId.get(id)).filter((f): f is AirtrailFlightRaw => !!f); + const chain = members.length === unique.length && !unique.some(id => groupedIds.has(id)) + ? orderConnectionChain(members) + : null; + if (!chain) { + console.warn('[airtrail-import] join group is not a connection chain — importing flights individually'); + continue; + } + if (unique.some(id => linkedIds.has(id)) || chain.some(f => { + const sig = flightSignature(f); + return !!sig && existingSigs.has(sig); + })) { + continue; // a member already exists in the trip — let the single path sort it out + } + chains.push(chain); + for (const id of unique) groupedIds.add(id); + } + + for (const chain of chains) { + const ids = chain.map(f => String(f.id)); + try { + const mapped = mapFlightsToMultiLegReservation(chain, resolveDayId); + const { reservation } = this.reservations.create(tripId, mapped as any); + const now = new Date().toISOString(); + this.db.prepare( + `UPDATE reservations SET external_source = 'airtrail', external_id = ?, external_owner_user_id = ?, + sync_enabled = 0, external_synced_at = ? WHERE id = ?`, + ).run(ids[0], userId, now, reservation.id); + + reservation.external_source = 'airtrail'; + reservation.external_id = ids[0]; + reservation.external_owner_user_id = userId; + reservation.sync_enabled = 0; + reservation.external_synced_at = now; + + this.realtime.broadcast(String(tripId), 'reservation:created', { reservation } as never, socketId); + for (const f of chain) { + const sig = flightSignature(f); + if (sig) existingSigs.add(sig); + } + ids.forEach(id => linkedIds.add(id)); + result.imported.push(...ids); + } catch (err) { + console.error('[airtrail-import] failed to import connection', ids.join('+'), err instanceof Error ? err.message : err); + for (const id of ids) { + result.skipped.push({ flightId: id, reason: 'invalid', detail: err instanceof Error ? err.message : undefined }); + } + } + } + + for (const flight of selected) { + const fid = String(flight.id); + if (groupedIds.has(fid)) continue; + if (linkedIds.has(fid)) { + result.skipped.push({ flightId: fid, reason: 'already-imported' }); + continue; + } + + const mapped = mapFlightToReservation(flight); + const sig = flightSignature(flight); + if (sig && existingSigs.has(sig)) { + result.skipped.push({ flightId: fid, reason: 'already-in-trip', detail: mapped.title }); + continue; + } + + try { + const { reservation } = this.reservations.create(tripId, mapped as any); + const now = new Date().toISOString(); + this.db.prepare( + `UPDATE reservations SET external_source = 'airtrail', external_id = ?, external_owner_user_id = ?, + sync_enabled = 1, external_hash = ?, external_synced_at = ? WHERE id = ?`, + ).run(fid, userId, canonicalHash(flight), now, reservation.id); + + // Carry the linkage on the broadcast payload so members see the badge live. + reservation.external_source = 'airtrail'; + reservation.external_id = fid; + reservation.external_owner_user_id = userId; + reservation.sync_enabled = 1; + reservation.external_synced_at = now; + + this.realtime.broadcast(String(tripId), 'reservation:created', { reservation } as never, socketId); + if (sig) existingSigs.add(sig); + linkedIds.add(fid); + result.imported.push(fid); + } catch (err) { + console.error('[airtrail-import] failed to import flight', fid, err instanceof Error ? err.message : err); + result.skipped.push({ flightId: fid, reason: 'invalid', detail: err instanceof Error ? err.message : undefined }); + } + } + + return result; + } +} diff --git a/server/src/nest/integrations/airtrail-sync.helpers.ts b/server/src/nest/integrations/airtrail-sync.helpers.ts new file mode 100644 index 000000000..50e1220bc --- /dev/null +++ b/server/src/nest/integrations/airtrail-sync.helpers.ts @@ -0,0 +1,102 @@ +import { entityCode } from './airtrail.mapper'; +import type { AirtrailFlightRaw, AirtrailSavePayload } from './airtrail.client'; + +/** + * The pure half of the AirTrail push: turning a TREK reservation plus the flight + * as AirTrail currently has it into a save body. + * + * Free functions rather than methods, and in their own file, because + * buildSavePayload is the part with the real rules and its unit test drives it + * directly with fixture objects — no database, no HTTP, no container. + */ +function splitLocal(dt: string | null | undefined): { date: string | null; time: string | null } { + if (!dt) return { date: null, time: null }; + const date = dt.slice(0, 10); + const m = dt.slice(10).match(/(\d{2}:\d{2})/); + return { date: /^\d{4}-\d{2}-\d{2}$/.test(date) ? date : null, time: m ? m[1] : null }; +} + +/** + * Build the POST /flight/save body. AirTrail's save fully overwrites the flight, + * so we start from the flight as AirTrail currently has it (`existing`, the raw + * GET object) and overwrite ONLY the fields TREK manages. Everything else — + * terminal, gate, scheduled/actual times, customFields, track, and any field + * AirTrail may add later — passes through untouched. We deliberately do NOT model + * those fields; spreading the raw object keeps us decoupled from AirTrail's schema + * (#1240). + */ +export function buildSavePayload(reservation: any, existing: AirtrailFlightRaw): AirtrailSavePayload | null { + let meta: Record; + try { + meta = reservation.metadata ? JSON.parse(reservation.metadata) : {}; + } catch { + meta = {}; + } + const endpoints: any[] = reservation.endpoints || []; + const fromEp = endpoints.find((e) => e.role === 'from'); + const toEp = endpoints.find((e) => e.role === 'to'); + const fromCode = fromEp?.code || existing.from?.iata || existing.from?.icao || null; + const toCode = toEp?.code || existing.to?.iata || existing.to?.icao || null; + if (!fromCode || !toCode) return null; + + const dep = splitLocal(reservation.reservation_time); + const arr = splitLocal(reservation.reservation_end_time); + if (!dep.date) return null; + + // Preserve the existing seat manifest (an update replaces all seats); fall back + // to the key-owner placeholder so AirTrail attributes it to the connecting user. + const seats = (existing.seats ?? []).map((s) => ({ + userId: s.userId, + guestName: s.guestName, + seat: s.seat, + seatNumber: s.seatNumber, + seatClass: s.seatClass, + })); + if (seats.length === 0) { + seats.push({ userId: '', guestName: null, seat: null, seatNumber: null, seatClass: null }); + } + + // Push the seat the user set in TREK onto their own AirTrail seat (the one with + // a userId), leaving any co-passenger seats untouched. + const seatNumber = typeof meta.seat === 'string' && meta.seat.trim() ? meta.seat.trim() : null; + if (seatNumber) { + const ownSeat = seats.find((s) => s.userId) ?? seats[0]; + if (ownSeat) ownSeat.seatNumber = seatNumber; + } + + // Spread the existing flight first to preserve every AirTrail-owned field, then + // overwrite only what TREK manages. `from`/`to`/`airline`/`aircraft` come back + // from GET as objects but the save shape wants codes — those are exactly the + // keys we override, so the spread never ships an object where a code is wanted. + return { + // Cast so the spread carries through the AirTrail-owned keys we deliberately + // don't model (terminal, gate, scheduled/actual times, customFields, track, …). + ...(existing as unknown as Record), + id: Number(reservation.external_id), + from: fromCode, + to: toCode, + departure: dep.date, + departureTime: dep.time, + arrival: arr.date, + arrivalTime: arr.time, + // Import reads the SCHEDULED time, so a TREK edit must write back there too — + // otherwise the next pull (scheduled-wins) would revert it. AirTrail rebuilds the + // instant from a full-ISO date carrier + the HH:MM time, so pass a date carrier. + departureScheduled: dep.date ? `${dep.date}T00:00:00.000Z` : null, + departureScheduledTime: dep.time, + arrivalScheduled: arr.date ? `${arr.date}T00:00:00.000Z` : null, + arrivalScheduledTime: arr.time, + // These are AirTrail-owned details TREK doesn't surface in its edit UI — a TREK + // edit can leave them out of `metadata`. Preserve AirTrail's current value when + // TREK has none rather than nulling it out (#1240). Use airline_code (not the + // display name in metadata.airline, #1334); both it and entityCode mirror the + // import/hash code-selection so a writeback stays a no-op for the hash. + airline: meta.airline_code ?? entityCode(existing.airline) ?? null, + flightNumber: meta.flight_number ?? existing.flightNumber ?? null, + aircraft: meta.aircraft ?? entityCode(existing.aircraft) ?? null, + aircraftReg: meta.aircraft_reg ?? existing.aircraftReg ?? null, + flightReason: meta.flight_reason ?? existing.flightReason ?? null, + note: reservation.notes ?? existing.note ?? null, + seats, + } as AirtrailSavePayload; +} diff --git a/server/src/nest/integrations/airtrail-sync.service.ts b/server/src/nest/integrations/airtrail-sync.service.ts new file mode 100644 index 000000000..ea6b30ea5 --- /dev/null +++ b/server/src/nest/integrations/airtrail-sync.service.ts @@ -0,0 +1,258 @@ +import { Injectable } from '@nestjs/common'; +import { ADDON_IDS } from '../../addons'; +import { DatabaseService } from '../database/database.service'; +import { RealtimeService } from '../realtime/realtime.service'; +import { AddonsService } from '../addons/addons.service'; +import { ReservationsService } from '../reservations/reservations.service'; +import { logError, logInfo } from '../audit/audit-log.logger'; +import { AirtrailAuthError, type AirtrailCreds, type AirtrailFlightRaw } from './airtrail.client'; +import { AirtrailClient } from './airtrail.client'; +import { AirtrailService } from './airtrail.service'; +import { canonicalHash, mapFlightToReservation } from './airtrail.mapper'; +import { buildSavePayload } from './airtrail-sync.helpers'; + +export { buildSavePayload } from './airtrail-sync.helpers'; + +/** + * Two-way AirTrail sync: the background pull that reconciles linked reservations + * against the owner's current flights, and the push that writes a local edit + * back. + * + * Folded out of services/airtrail/airtrailSync.ts. Every rule is unchanged — the + * snapshot-hash change detection, the detach-instead-of-delete policy, the + * multi-leg guard (#1535), the write opt-in (#1240) and the self-write + * suppression. What moved is the wiring: the db singleton, the raw websocket + * broadcast and three bridges (addons, reservations) were module imports and are + * injected now. + */ +@Injectable() +export class AirtrailSyncService { + constructor( + private readonly db: DatabaseService, + private readonly realtime: RealtimeService, + private readonly addons: AddonsService, + private readonly reservations: ReservationsService, + private readonly client: AirtrailClient, + private readonly airtrail: AirtrailService, + ) {} + + /** Guards the background poll against overlapping ticks. Instance state rather + * than a module-level flag, because the service is a container singleton. */ + private running = false; + + /** Global on/off: the addon must be enabled and sync not explicitly turned off. */ + syncGloballyEnabled(): boolean { + if (!this.addons.isAddonEnabled(ADDON_IDS.AIRTRAIL)) return false; + const row = this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'airtrail_sync_enabled'"); + return row?.value !== 'false'; + } + + private broadcastUpdated(tripId: number, reservationId: number): void { + try { + const reservation = this.reservations.getReservationWithJoins(reservationId); + if (reservation) this.realtime.broadcast(String(tripId), 'reservation:updated', { reservation } as never, undefined); + } catch { + /* broadcast failure is non-fatal */ + } + } + + private detach(tripId: number, reservationId: number): void { + this.db.run('UPDATE reservations SET sync_enabled = 0 WHERE id = ?', reservationId); + this.broadcastUpdated(tripId, reservationId); + } + + /** + * True when the reservation has grown into a multi-leg booking locally (extra + * stops / metadata.legs) — a shape the single AirTrail flight it is linked to + * cannot represent. Syncing such a row in either direction would corrupt one + * side: a pull flattens the layover chain back to from→to, a push rewrites the + * AirTrail flight to span the whole route (#1535). + */ + private hasLocalMultiLegShape(reservationId: number, metadataJson: string | null | undefined): boolean { + try { + const meta = metadataJson ? JSON.parse(metadataJson) : {}; + if (Array.isArray(meta?.legs) && meta.legs.length > 1) return true; + } catch { + /* malformed metadata — fall through to the endpoint count */ + } + const row = this.db.get<{ n: number }>( + 'SELECT COUNT(*) AS n FROM reservation_endpoints WHERE reservation_id = ?', + reservationId, + ) as { n: number }; + return row.n > 2; + } + + // ── AirTrail → TREK (poll) ─────────────────────────────────────────────────── + + /** + * Reconcile one owner's linked reservations against their current AirTrail + * flights: apply field changes (detected by snapshot hash, since AirTrail has no + * updated_at) and, when a flight is gone from AirTrail, keep the TREK row but + * stop syncing it. Only already-imported flights are touched — new AirTrail + * flights are never auto-added to a trip. Returns how many rows changed. + */ + private async syncOwner(uid: number): Promise { + const creds = this.airtrail.getAirtrailCredentials(uid); + if (!creds) return 0; // owner disconnected — leave their linked rows as-is + + let flights: AirtrailFlightRaw[]; + try { + flights = await this.client.listFlights(creds); + } catch (err) { + if (err instanceof AirtrailAuthError) logError(`AirTrail sync: invalid API key for user ${uid}`); + return 0; + } + const byId = new Map(flights.map((f) => [String(f.id), f])); + + const linked = this.db.all<{ id: number; trip_id: number; external_id: string; external_hash: string | null }>( + "SELECT id, trip_id, external_id, external_hash FROM reservations WHERE external_source = 'airtrail' AND sync_enabled = 1 AND external_owner_user_id = ?", + uid, + ); + + let changed = 0; + for (const row of linked) { + const flight = byId.get(String(row.external_id)); + if (!flight) { + this.detach(row.trip_id, row.id); // deleted in AirTrail → keep row, stop syncing + changed++; + continue; + } + + const hash = canonicalHash(flight); + if (hash === row.external_hash) continue; + + const current = this.reservations.getReservation(row.id, row.trip_id); + if (!current) continue; + if (this.hasLocalMultiLegShape(row.id, (current as any).metadata)) { + // The user connected this flight into a multi-leg booking; applying the + // remote single-flight shape would flatten it. Stop syncing instead. + this.detach(row.trip_id, row.id); + changed++; + continue; + } + try { + this.reservations.update(row.id, row.trip_id, mapFlightToReservation(flight) as any, current as any); + this.db.run( + 'UPDATE reservations SET external_hash = ?, external_synced_at = ? WHERE id = ?', + hash, + new Date().toISOString(), + row.id, + ); + this.broadcastUpdated(row.trip_id, row.id); + changed++; + } catch (err) { + logError(`AirTrail sync: failed to update reservation ${row.id}: ${err instanceof Error ? err.message : err}`); + } + } + return changed; + } + + /** Background poll across every connected owner (scheduler). */ + async runAirtrailSync(): Promise { + if (this.running) return; + if (!this.syncGloballyEnabled()) return; + this.running = true; + let changed = 0; + try { + const owners = this.db.all<{ uid: number }>( + "SELECT DISTINCT external_owner_user_id AS uid FROM reservations WHERE external_source = 'airtrail' AND sync_enabled = 1 AND external_owner_user_id IS NOT NULL", + ); + for (const { uid } of owners) changed += await this.syncOwner(uid); + if (changed > 0) logInfo(`AirTrail sync: applied ${changed} change(s)`); + } catch (err) { + logError(`AirTrail sync failed: ${err instanceof Error ? err.message : err}`); + } finally { + this.running = false; + } + } + + /** + * On-demand sync of just this user's linked flights — called when the user opens + * a trip so AirTrail-side edits show up immediately instead of waiting for the + * background poll. + */ + async runAirtrailSyncForUser(userId: number): Promise<{ changed: number }> { + if (!this.syncGloballyEnabled()) return { changed: 0 }; + try { + return { changed: await this.syncOwner(userId) }; + } catch (err) { + logError(`AirTrail sync (user ${userId}) failed: ${err instanceof Error ? err.message : err}`); + return { changed: 0 }; + } + } + + // ── TREK → AirTrail (push) ─────────────────────────────────────────────────── + + /** + * Push a locally-edited linked reservation back to AirTrail using the importer's + * (owner's) credentials — even if a different member made the edit. If the owner + * is gone or the flight no longer exists in AirTrail, the link is detached so the + * next pull's AirTrail-wins policy can't silently revert the local edit. + */ + async pushReservationToAirtrail(reservationId: number, tripId: number): Promise { + if (!this.syncGloballyEnabled()) return; + + const row = this.db.get<{ + id: number; trip_id: number; external_id: string; external_owner_user_id: number | null; sync_enabled: number; + }>( + "SELECT id, trip_id, external_id, external_owner_user_id, sync_enabled FROM reservations WHERE id = ? AND external_source = 'airtrail'", + reservationId, + ); + if (!row || !row.sync_enabled) return; + + // An edit that turned this linked flight into a multi-leg booking severs the + // 1:1 mapping to the AirTrail flight: pushing would rewrite that flight to the + // full span, and the next pull would flatten the layover again. Detach — the + // merge is a deliberate local restructuring, like a joined import (#1535). + const reservation = this.reservations.getReservationWithJoins(row.id); + if (!reservation) return; + if (this.hasLocalMultiLegShape(row.id, (reservation as { metadata?: string | null }).metadata)) { + this.detach(tripId, row.id); + return; + } + + // AirTrail is read-only by default (#1240). Only push when the flight's owner has + // explicitly opted in. A no-op skip (not a detach): the link stays active so the + // inbound, AirTrail-wins pull keeps the reservation up to date. + if (!row.external_owner_user_id || !this.airtrail.isAirtrailWriteEnabled(row.external_owner_user_id)) return; + + const creds: AirtrailCreds | null = this.airtrail.getAirtrailCredentials(row.external_owner_user_id); + if (!creds) { + this.detach(tripId, row.id); // owner disconnected — cannot push, so stop syncing + return; + } + + let existing: AirtrailFlightRaw | null; + try { + existing = await this.client.getFlight(creds, Number(row.external_id)); + } catch (err) { + if (err instanceof AirtrailAuthError) this.detach(tripId, row.id); + else logError(`AirTrail push: get failed for reservation ${row.id}: ${err instanceof Error ? err.message : err}`); + return; + } + if (!existing) { + this.detach(tripId, row.id); // gone in AirTrail → treat like a remote delete + return; + } + + const payload = buildSavePayload(reservation, existing); + if (!payload) return; + + try { + await this.client.saveFlight(creds, payload); + // Self-write suppression: re-read the saved flight and store its hash so the + // next poll doesn't treat our own write as an inbound change. + const saved = await this.client.getFlight(creds, Number(row.external_id)); + if (saved) { + this.db.run( + 'UPDATE reservations SET external_hash = ?, external_synced_at = ? WHERE id = ?', + canonicalHash(saved), + new Date().toISOString(), + row.id, + ); + } + } catch (err) { + logError(`AirTrail push failed for reservation ${row.id}: ${err instanceof Error ? err.message : err}`); + } + } +} diff --git a/server/src/nest/integrations/airtrail.bridge.ts b/server/src/nest/integrations/airtrail.bridge.ts new file mode 100644 index 000000000..ffebb9d31 --- /dev/null +++ b/server/src/nest/integrations/airtrail.bridge.ts @@ -0,0 +1,54 @@ +import { db } from '../../db/database'; +import { DatabaseService } from '../database/database.service'; +import { RealtimeService } from '../realtime/realtime.service'; +import { PermissionsService } from '../permissions/permissions.service'; +import { AddonsService } from '../addons/addons.service'; +import { AuditService } from '../audit/audit.service'; +import { BudgetService } from '../budget/budget.service'; +import { ExchangeRatesService } from '../budget/exchange-rates.service'; +import { ReservationsService } from '../reservations/reservations.service'; +import { AirtrailClient } from './airtrail.client'; +import { AirtrailService } from './airtrail.service'; +import { AirtrailSyncService } from './airtrail-sync.service'; + +/** + * The ONE airtrail edge that cannot be an injection, and why. + * + * `AirtrailSyncService` needs `ReservationsService`: the pull applies remote + * changes through the real reservation update path, endpoint restamping and all, + * and reimplementing that against raw SQL would be strictly worse than the + * coupling. So `AirtrailModule` imports `ReservationsModule`. + * + * The write-back trigger runs in the other direction — `reservations.controller` + * fires it after a local edit — and injecting `AirtrailSyncService` there would + * close `ReservationsModule -> AirtrailModule -> ReservationsModule`. A + * `forwardRef` would compile and is exactly the shape this migration has been + * removing, so it stays a seam instead, documented rather than accidental. + * + * Module-level construction is safe: `db` is the reinitialize-proof Proxy onto + * the shared better-sqlite3 singleton, the same pattern the other bridges use. + */ +const dbs = () => new DatabaseService(db); +const realtime = new RealtimeService(); +const permissions = new PermissionsService(dbs()); +const client = new AirtrailClient(); +const airtrail = new AirtrailService(dbs(), new AuditService(dbs()), client); +const reservations = new ReservationsService( + dbs(), + permissions, + new BudgetService(dbs(), permissions, new ExchangeRatesService(), realtime), + realtime, +); +const sync = new AirtrailSyncService( + dbs(), + realtime, + new AddonsService(dbs()), + reservations, + client, + airtrail, +); + +/** Fire-and-forget write-back after a local edit to a linked flight (#1240). */ +export function pushReservationToAirtrail(reservationId: number, tripId: number): Promise { + return sync.pushReservationToAirtrail(reservationId, tripId); +} diff --git a/server/src/services/airtrail/airtrailClient.ts b/server/src/nest/integrations/airtrail.client.ts similarity index 71% rename from server/src/services/airtrail/airtrailClient.ts rename to server/src/nest/integrations/airtrail.client.ts index f8ad41509..10930af53 100644 --- a/server/src/services/airtrail/airtrailClient.ts +++ b/server/src/nest/integrations/airtrail.client.ts @@ -1,3 +1,4 @@ +import { Injectable } from '@nestjs/common'; import { safeFetch } from '../../utils/ssrfGuard'; /** @@ -166,38 +167,50 @@ async function request(creds: AirtrailCreds, path: string, init: RequestInit): P return resp; } -export async function listFlights(creds: AirtrailCreds): Promise { - const resp = await request(creds, '/flight/list', { method: 'GET' }); - if (!resp.ok) throw new AirtrailRequestError(`AirTrail list failed (HTTP ${resp.status})`, resp.status); - const data = await parseJson<{ flights?: AirtrailFlightRaw[] }>(resp); - return data.flights ?? []; -} -export async function getFlight(creds: AirtrailCreds, id: number): Promise { - const resp = await request(creds, `/flight/get/${id}`, { method: 'GET' }); - if (resp.status === 404) return null; - if (!resp.ok) throw new AirtrailRequestError(`AirTrail get failed (HTTP ${resp.status})`, resp.status); - const data = await parseJson<{ flight?: AirtrailFlightRaw }>(resp); - return data.flight ?? null; -} - -export async function saveFlight(creds: AirtrailCreds, payload: AirtrailSavePayload): Promise<{ id?: number }> { - const resp = await request(creds, '/flight/save', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(payload), - }); - if (!resp.ok) { - let msg = `AirTrail save failed (HTTP ${resp.status})`; - try { - const body = (await resp.json()) as { message?: string; errors?: unknown }; - if (body?.message) msg = body.message; - else if (body?.errors) msg = JSON.stringify(body.errors); - } catch { - /* keep the generic message */ - } - throw new AirtrailRequestError(msg, resp.status); +/** + * The AirTrail HTTP surface, as a provider. + * + * It has no constructor dependencies: `safeFetch` is the SSRF guard, a plain + * util that fifteen other nest services import directly. The error classes stay + * exported classes rather than becoming anything injectable, because four call + * sites branch on `instanceof` and on `err.status === 400`. + */ +@Injectable() +export class AirtrailClient { + async listFlights(creds: AirtrailCreds): Promise { + const resp = await request(creds, '/flight/list', { method: 'GET' }); + if (!resp.ok) throw new AirtrailRequestError(`AirTrail list failed (HTTP ${resp.status})`, resp.status); + const data = await parseJson<{ flights?: AirtrailFlightRaw[] }>(resp); + return data.flights ?? []; + } + + async getFlight(creds: AirtrailCreds, id: number): Promise { + const resp = await request(creds, `/flight/get/${id}`, { method: 'GET' }); + if (resp.status === 404) return null; + if (!resp.ok) throw new AirtrailRequestError(`AirTrail get failed (HTTP ${resp.status})`, resp.status); + const data = await parseJson<{ flight?: AirtrailFlightRaw }>(resp); + return data.flight ?? null; + } + + async saveFlight(creds: AirtrailCreds, payload: AirtrailSavePayload): Promise<{ id?: number }> { + const resp = await request(creds, '/flight/save', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + }); + if (!resp.ok) { + let msg = `AirTrail save failed (HTTP ${resp.status})`; + try { + const body = (await resp.json()) as { message?: string; errors?: unknown }; + if (body?.message) msg = body.message; + else if (body?.errors) msg = JSON.stringify(body.errors); + } catch { + /* keep the generic message */ + } + throw new AirtrailRequestError(msg, resp.status); + } + const data = await parseJson<{ id?: number }>(resp); + return { id: data.id }; } - const data = await parseJson<{ id?: number }>(resp); - return { id: data.id }; } diff --git a/server/src/nest/integrations/airtrail.controller.ts b/server/src/nest/integrations/airtrail.controller.ts index a85e0de2b..6fd5d08ce 100644 --- a/server/src/nest/integrations/airtrail.controller.ts +++ b/server/src/nest/integrations/airtrail.controller.ts @@ -8,14 +8,8 @@ import { RequireAddon } from '../addons/require-addon.decorator'; import { ADDON_IDS } from '../../addons'; import { AirtrailSettingsDto } from './airtrail.dto'; import { getClientIp } from '../audit/client-ip'; -import { - getConnectionSettings, - getConnectionStatus, - getFlightsForPicker, - saveSettings, - testConnection, -} from '../../services/airtrail/airtrailService'; -import { runAirtrailSyncForUser } from '../../services/airtrail/airtrailSync'; +import { AirtrailService } from './airtrail.service'; +import { AirtrailSyncService } from './airtrail-sync.service'; /** * /api/integrations/airtrail — per-user AirTrail connection (#214). @@ -29,9 +23,14 @@ import { runAirtrailSyncForUser } from '../../services/airtrail/airtrailSync'; @UseGuards(AddonGuard, JwtAuthGuard) @RequireAddon(ADDON_IDS.AIRTRAIL, 'AirTrail') export class AirtrailController { + constructor( + private readonly airtrail: AirtrailService, + private readonly syncService: AirtrailSyncService, + ) {} + @Get('settings') getSettings(@CurrentUser() user: User) { - return getConnectionSettings(user.id); + return this.airtrail.getConnectionSettings(user.id); } @Put('settings') @@ -40,7 +39,7 @@ export class AirtrailController { @Body() body: AirtrailSettingsDto, @Req() req: Request, ) { - const result = await saveSettings( + const result = await this.airtrail.saveSettings( user.id, body.url, body.apiKey, @@ -56,13 +55,13 @@ export class AirtrailController { @Get('status') getStatus(@CurrentUser() user: User) { - return getConnectionStatus(user.id); + return this.airtrail.getConnectionStatus(user.id); } @Get('flights') async flights(@CurrentUser() user: User) { try { - return { flights: await getFlightsForPicker(user.id) }; + return { flights: await this.airtrail.getFlightsForPicker(user.id) }; } catch (err: any) { throw new HttpException({ error: err?.message || 'Could not load AirTrail flights' }, err?.status === 400 ? 400 : 502); } @@ -72,7 +71,7 @@ export class AirtrailController { @Post('sync') @HttpCode(200) sync(@CurrentUser() user: User) { - return runAirtrailSyncForUser(user.id); + return this.syncService.runAirtrailSyncForUser(user.id); } @Post('test') @@ -81,6 +80,6 @@ export class AirtrailController { @CurrentUser() user: User, @Body() body: AirtrailSettingsDto, ) { - return testConnection(user.id, body.url, body.apiKey, !!body.allowInsecureTls); + return this.airtrail.testConnection(user.id, body.url, body.apiKey, !!body.allowInsecureTls); } } diff --git a/server/src/services/airtrail/airtrailMapper.ts b/server/src/nest/integrations/airtrail.mapper.ts similarity index 99% rename from server/src/services/airtrail/airtrailMapper.ts rename to server/src/nest/integrations/airtrail.mapper.ts index 4a9c32df2..122002be5 100644 --- a/server/src/services/airtrail/airtrailMapper.ts +++ b/server/src/nest/integrations/airtrail.mapper.ts @@ -1,5 +1,5 @@ -import { localParts } from '../../nest/common/timezoneService'; -import type { AirtrailAirport, AirtrailFlightRaw, AirtrailNamedCode } from './airtrailClient'; +import { localParts } from '../common/timezoneService'; +import type { AirtrailAirport, AirtrailFlightRaw, AirtrailNamedCode } from './airtrail.client'; import type { AirtrailFlight } from '@trek/shared'; import * as crypto from 'node:crypto'; diff --git a/server/src/nest/integrations/airtrail.module.ts b/server/src/nest/integrations/airtrail.module.ts index ec8999c5c..a7ce781e4 100644 --- a/server/src/nest/integrations/airtrail.module.ts +++ b/server/src/nest/integrations/airtrail.module.ts @@ -1,17 +1,33 @@ import { Module } from '@nestjs/common'; import { AirtrailController } from './airtrail.controller'; import { AirtrailImportController } from './airtrail-import.controller'; +import { AirtrailClient } from './airtrail.client'; +import { AirtrailService } from './airtrail.service'; +import { AirtrailSyncService } from './airtrail-sync.service'; +import { AirtrailImportService } from './airtrail-import.service'; import { PermissionsModule } from '../permissions/permissions.module'; import { AddonsModule } from '../addons/addons.module'; +import { AuditModule } from '../audit/audit.module'; +import { ReservationsModule } from '../reservations/reservations.module'; /** * AirTrail integration domain. The connection lives under * /api/integrations/airtrail; the flight import is trip-scoped under - * /api/trips/:tripId/reservations/import/airtrail. Business logic lives in - * services/airtrail/* (plain functions over better-sqlite3). + * /api/trips/:tripId/reservations/import/airtrail. + * + * The logic used to be plain functions over the better-sqlite3 singleton in + * services/airtrail/*, the last thing left in that directory. It is four + * providers now: the HTTP client, the credential/settings service, the two-way + * sync and the importer. + * + * It imports ReservationsModule because the pull applies remote changes through + * the real reservation update path. The trigger in the other direction stays a + * seam on purpose - see airtrail.bridge.ts. */ @Module({ - imports: [PermissionsModule, AddonsModule], + imports: [PermissionsModule, AddonsModule, AuditModule, ReservationsModule], controllers: [AirtrailController, AirtrailImportController], + providers: [AirtrailClient, AirtrailService, AirtrailSyncService, AirtrailImportService], + exports: [AirtrailSyncService], }) export class AirtrailModule {} diff --git a/server/src/nest/integrations/airtrail.service.ts b/server/src/nest/integrations/airtrail.service.ts new file mode 100644 index 000000000..253084b49 --- /dev/null +++ b/server/src/nest/integrations/airtrail.service.ts @@ -0,0 +1,192 @@ +import { Injectable } from '@nestjs/common'; +import type { AirtrailFlight } from '@trek/shared'; +import { DatabaseService } from '../database/database.service'; +import { AuditService } from '../audit/audit.service'; +import { maybe_encrypt_api_key, decrypt_api_key } from '../common/crypto/apiKeyCrypto'; +import { checkSsrf } from '../../utils/ssrfGuard'; +import { AirtrailAuthError, AirtrailRequestError, type AirtrailCreds } from './airtrail.client'; +import { AirtrailClient } from './airtrail.client'; +import { normalizeFlight } from './airtrail.mapper'; + +const KEY_MASK = '••••••••'; + +interface UserConnRow { + airtrail_url?: string | null; + airtrail_api_key?: string | null; + airtrail_allow_insecure_tls?: number | null; + airtrail_write_enabled?: number | null; +} + +/** + * AirTrail credentials, connection settings and the connection probe. + * + * Folded out of services/airtrail/airtrailService.ts: the SQL, the SSRF + * handling, the audit entry and the error mapping are unchanged. What moved is + * where the collaborators come from — the db singleton and the audit bridge were + * module-level imports and are injected now. + * + * The credentials stay in the users columns (airtrail_url, airtrail_api_key, + * airtrail_allow_insecure_tls, airtrail_write_enabled). That was a deliberate + * decision, not an omission: an integrations table would have needed a migration + * and bought nothing while AirTrail is the only integration of this shape. + */ +@Injectable() +export class AirtrailService { + constructor( + private readonly db: DatabaseService, + private readonly audit: AuditService, + private readonly client: AirtrailClient, + ) {} + + private readRow(userId: number): UserConnRow | undefined { + return this.db.get( + 'SELECT airtrail_url, airtrail_api_key, airtrail_allow_insecure_tls, airtrail_write_enabled FROM users WHERE id = ?', + userId, + ); + } + + /** Has this user opted in to TREK writing their flight edits back to AirTrail? (#1240) */ + isAirtrailWriteEnabled(userId: number): boolean { + const row = this.db.get<{ airtrail_write_enabled?: number | null }>( + 'SELECT airtrail_write_enabled FROM users WHERE id = ?', + userId, + ); + return !!row?.airtrail_write_enabled; + } + + /** Decrypted creds for outbound calls, or null when the user has no connection. */ + getAirtrailCredentials(userId: number): AirtrailCreds | null { + const row = this.readRow(userId); + if (!row?.airtrail_url || !row?.airtrail_api_key) return null; + const apiKey = decrypt_api_key(row.airtrail_api_key); + if (!apiKey) return null; + return { + baseUrl: row.airtrail_url, + apiKey, + allowInsecureTls: !!row.airtrail_allow_insecure_tls, + }; + } + + /** Settings as shown in the UI — the key is never echoed, only masked. */ + getConnectionSettings(userId: number) { + const row = this.readRow(userId); + return { + url: row?.airtrail_url || '', + apiKeyMasked: row?.airtrail_api_key ? KEY_MASK : '', + allowInsecureTls: !!row?.airtrail_allow_insecure_tls, + writeEnabled: !!row?.airtrail_write_enabled, + connected: !!(row?.airtrail_url && row?.airtrail_api_key), + }; + } + + async saveSettings( + userId: number, + url: string | undefined, + apiKey: string | undefined, + allowInsecureTls: boolean, + writeEnabled: boolean, + clientIp: string | null, + ): Promise<{ success: boolean; warning?: string; error?: string }> { + const trimmedUrl = (url || '').trim(); + let warning: string | undefined; + + if (trimmedUrl) { + const ssrf = await checkSsrf(trimmedUrl); + // Reject only genuinely unusable URLs (malformed, unresolvable, non-http, + // loopback). Private/LAN instances are the common self-hosted case, so we + // persist them with a warning rather than blocking — the outbound calls + // still need ALLOW_INTERNAL_NETWORK=true to actually reach them. + if (!ssrf.allowed && !ssrf.isPrivate) { + return { success: false, error: ssrf.error ?? 'Invalid AirTrail URL' }; + } + if (ssrf.isPrivate) { + this.audit.writeAudit({ + userId, + action: 'airtrail.private_ip_configured', + ip: clientIp, + details: { airtrail_url: trimmedUrl, resolved_ip: ssrf.resolvedIp }, + }); + warning = `AirTrail URL resolves to a private IP (${ssrf.resolvedIp}). Make sure this is intentional — the server may need ALLOW_INTERNAL_NETWORK=true to reach it.`; + } + } + + // Only overwrite the stored key when a genuinely new value is supplied; + // a blank field or the mask means "keep the existing key". + const provided = (apiKey || '').trim(); + const newKey = provided && provided !== KEY_MASK ? maybe_encrypt_api_key(provided) : undefined; + + if (newKey !== undefined) { + this.db.run( + 'UPDATE users SET airtrail_url = ?, airtrail_api_key = ?, airtrail_allow_insecure_tls = ?, airtrail_write_enabled = ? WHERE id = ?', + trimmedUrl || null, newKey, allowInsecureTls ? 1 : 0, writeEnabled ? 1 : 0, userId, + ); + } else { + this.db.run( + 'UPDATE users SET airtrail_url = ?, airtrail_allow_insecure_tls = ?, airtrail_write_enabled = ? WHERE id = ?', + trimmedUrl || null, allowInsecureTls ? 1 : 0, writeEnabled ? 1 : 0, userId, + ); + // Clearing the URL with no key left makes the connection meaningless — drop the key too. + if (!trimmedUrl) { + this.db.run('UPDATE users SET airtrail_api_key = NULL WHERE id = ?', userId); + } + } + + return { success: true, warning }; + } + + private async probe(creds: AirtrailCreds): Promise<{ connected: boolean; flightCount?: number; error?: string }> { + try { + const flights = await this.client.listFlights(creds); + return { connected: true, flightCount: flights.length }; + } catch (err: unknown) { + if (err instanceof AirtrailAuthError) return { connected: false, error: 'Invalid API key' }; + return { connected: false, error: err instanceof Error ? err.message : 'Connection failed' }; + } + } + + /** Live check using the stored connection. */ + async getConnectionStatus( + userId: number, + ): Promise<{ connected: boolean; flightCount?: number; error?: string }> { + const creds = this.getAirtrailCredentials(userId); + if (!creds) return { connected: false, error: 'Not configured' }; + return this.probe(creds); + } + + /** + * "Test connection" from the settings form. Uses the typed URL/key when given; + * falls back to the stored key when the key field still shows the mask. + */ + async testConnection( + userId: number, + url: string | undefined, + apiKey: string | undefined, + allowInsecureTls: boolean, + ): Promise<{ connected: boolean; flightCount?: number; error?: string }> { + const trimmedUrl = (url || '').trim(); + const provided = (apiKey || '').trim(); + + const stored = this.getAirtrailCredentials(userId); + const effectiveUrl = trimmedUrl || stored?.baseUrl; + const effectiveKey = provided && provided !== KEY_MASK ? provided : stored?.apiKey; + + if (!effectiveUrl || !effectiveKey) { + return { connected: false, error: 'URL and API key required' }; + } + + const ssrf = await checkSsrf(effectiveUrl); + if (!ssrf.allowed && !ssrf.isPrivate) { + return { connected: false, error: ssrf.error ?? 'Invalid AirTrail URL' }; + } + + return this.probe({ baseUrl: effectiveUrl, apiKey: effectiveKey, allowInsecureTls }); + } + + /** The user's AirTrail flights, normalized for the import picker. */ + async getFlightsForPicker(userId: number): Promise { + const creds = this.getAirtrailCredentials(userId); + if (!creds) throw new AirtrailRequestError('AirTrail is not connected', 400); + const raw = await this.client.listFlights(creds); + return raw.map(normalizeFlight); + } +} diff --git a/server/src/nest/reservations/reservations.controller.ts b/server/src/nest/reservations/reservations.controller.ts index a2f5348c8..40c8cd053 100644 --- a/server/src/nest/reservations/reservations.controller.ts +++ b/server/src/nest/reservations/reservations.controller.ts @@ -15,7 +15,7 @@ import { ReservationsService } from './reservations.service'; import { JwtAuthGuard } from '../auth/jwt-auth.guard'; import { CurrentUser } from '../auth/current-user.decorator'; import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard'; -import { pushReservationToAirtrail } from '../../services/airtrail/airtrailSync'; +import { pushReservationToAirtrail } from '../integrations/airtrail.bridge'; import { ReservationCreateDto, ReservationUpdateDto, diff --git a/server/src/scheduler.ts b/server/src/scheduler.ts index a757f052e..51c6902db 100644 --- a/server/src/scheduler.ts +++ b/server/src/scheduler.ts @@ -74,6 +74,7 @@ function saveSettings(settings: BackupSettings): void { export interface SchedulerDeps { backups: { createBackup(prefix?: 'backup' | 'auto-backup'): Promise<{ filename: string }> }; placePhotos: { sweepOrphans(): number }; + airtrail: { runAirtrailSync(): Promise }; } let deps: SchedulerDeps | undefined; @@ -434,8 +435,11 @@ function startAirTrailSync(): void { airtrailSyncTask = cron.schedule(`*/${minutes} * * * *`, async () => { try { - const { runAirtrailSync } = require('./services/airtrail/airtrailSync'); - await runAirtrailSync(); + if (!deps) { + logError('AirTrail sync: skipped, the scheduler was started without its container dependencies'); + return; + } + await deps.airtrail.runAirtrailSync(); } catch (err: unknown) { logError(`AirTrail sync tick failed: ${err instanceof Error ? err.message : err}`); } diff --git a/server/src/services/airtrail/airtrailImport.ts b/server/src/services/airtrail/airtrailImport.ts deleted file mode 100644 index 7dc6bfe2e..000000000 --- a/server/src/services/airtrail/airtrailImport.ts +++ /dev/null @@ -1,286 +0,0 @@ -import type { AirtrailImportResult } from '@trek/shared'; -import { db } from '../../db/database'; -import { broadcast } from '../../websocket'; -import { createReservation } from '../../nest/reservations/reservations.bridge'; -import { getAirtrailCredentials } from './airtrailService'; -import { AirtrailRequestError, listFlights } from './airtrailClient'; -import type { AirtrailFlightRaw } from './airtrailClient'; -import { canonicalHash, mapFlightToReservation, mapFlightsToMultiLegReservation, normalizeFlight } from './airtrailMapper'; - -interface ExistingFlightRow { - id: number; - reservation_time: string | null; - metadata: string | null; -} - -interface EndpointRow { - reservation_id: number; - code: string | null; - local_date: string | null; - sequence: number; -} - -function depDate(t: string | null): string | null { - return t && /^\d{4}-\d{2}-\d{2}/.test(t) ? t.slice(0, 10) : null; -} - -/** A loose "same physical flight" key: flight number + date, else route + date. */ -function softSignature( - date: string | null, - flightNumber: string | null, - fromCode: string | null, - toCode: string | null, -): string | null { - if (!date) return null; - if (flightNumber) return `fn:${flightNumber.toUpperCase()}@${date}`; - if (fromCode && toCode) return `rt:${fromCode.toUpperCase()}-${toCode.toUpperCase()}@${date}`; - return null; -} - -/** The signature a single AirTrail flight would get as its own reservation. */ -function flightSignature(flight: AirtrailFlightRaw): string | null { - const mapped = mapFlightToReservation(flight); - return softSignature( - depDate(mapped.reservation_time), - (mapped.metadata.flight_number as string) ?? null, - mapped.endpoints.find(e => e.role === 'from')?.code ?? null, - mapped.endpoints.find(e => e.role === 'to')?.code ?? null, - ); -} - -/** - * Order a requested join group by departure and verify it forms a real - * connection chain: each flight leaves the airport the previous one arrived at, - * onward in time and within 24 h — the same window the booking import applies - * to same-PNR legs. A leg landing back at the chain's origin is a return - * flight, never a connection. Flights without usable instants can't prove any - * of this, so they don't chain. Returns the ordered chain, or null when the - * flights don't chain; the members then import individually, exactly as if no - * join had been requested. - */ -function orderConnectionChain(group: AirtrailFlightRaw[]): AirtrailFlightRaw[] | null { - if (group.length < 2) return null; - const norm = group.map(raw => ({ raw, n: normalizeFlight(raw) })); - const depMs = (n: (typeof norm)[number]['n']): number => (n.departure ? Date.parse(n.departure) : NaN); - if (norm.some(x => Number.isNaN(depMs(x.n)))) return null; - norm.sort((a, b) => depMs(a.n) - depMs(b.n)); - const origin = norm[0].n.fromCode; - for (let i = 1; i < norm.length; i++) { - const prev = norm[i - 1].n; - const next = norm[i].n; - if (!prev.toCode || !next.fromCode || prev.toCode.toUpperCase() !== next.fromCode.toUpperCase()) return null; - if (origin && next.toCode && next.toCode.toUpperCase() === origin.toUpperCase()) return null; - const arrMs = prev.arrival ? Date.parse(prev.arrival) : NaN; - if (Number.isNaN(arrMs)) return null; - const gap = depMs(next) - arrMs; - if (gap < 0 || gap > 24 * 3600 * 1000) return null; - } - return norm.map(x => x.raw); -} - -/** - * Import the given AirTrail flights into a trip as reservations (type:'flight'), - * recording the AirTrail linkage for two-way sync and broadcasting each one live. - * - * `connections` names chains of selected flights to import as ONE multi-leg - * reservation each, with the connection airports as layover stops (#1535). A - * joined booking is created detached from live sync (sync_enabled = 0): AirTrail - * has no multi-leg flight entity it could round-trip to, and a pull would - * flatten the layover again. All member ids are kept in metadata.airtrail_ids - * so none of the legs is offered for re-import. - * - * Dedup: a flight already linked to this trip is skipped ('already-imported'); a - * flight that looks like one already in the trip — e.g. the same flight another - * member already imported from their own AirTrail — is skipped ('already-in-trip'). - * The server re-fetches the flights by id with the caller's own key, so the client - * cannot inject arbitrary flight data. - */ -export async function importAirtrailFlights( - tripId: string | number, - userId: number, - flightIds: string[], - socketId: string | undefined, - connections: string[][] = [], -): Promise { - const creds = getAirtrailCredentials(userId); - if (!creds) throw new AirtrailRequestError('AirTrail is not connected', 400); - - const wanted = new Set(flightIds.map(String)); - const selected = (await listFlights(creds)).filter(f => wanted.has(String(f.id))); - const byId = new Map(selected.map(f => [String(f.id), f])); - - const result: AirtrailImportResult = { imported: [], skipped: [] }; - - // Every AirTrail id already linked to this trip: the external_id column plus - // the metadata.airtrail_ids of joined multi-leg imports. - const linkedIds = new Set(); - const linkedRows = db - .prepare("SELECT external_id, metadata FROM reservations WHERE trip_id = ? AND external_source = 'airtrail'") - .all(tripId) as { external_id: string | null; metadata: string | null }[]; - for (const row of linkedRows) { - if (row.external_id) linkedIds.add(row.external_id); - try { - const ids = row.metadata ? JSON.parse(row.metadata).airtrail_ids : null; - if (Array.isArray(ids)) for (const id of ids) linkedIds.add(String(id)); - } catch { - /* malformed metadata — ignore */ - } - } - - const existing = db - .prepare("SELECT r.id, r.reservation_time, r.metadata FROM reservations r WHERE r.trip_id = ? AND r.type = 'flight'") - .all(tripId) as ExistingFlightRow[]; - const endpointsByReservation = new Map(); - const endpointRows = db - .prepare( - `SELECT e.reservation_id, e.code, e.local_date, e.sequence - FROM reservation_endpoints e JOIN reservations r ON r.id = e.reservation_id - WHERE r.trip_id = ? AND r.type = 'flight' ORDER BY e.sequence`, - ) - .all(tripId) as EndpointRow[]; - for (const ep of endpointRows) { - const list = endpointsByReservation.get(ep.reservation_id); - if (list) list.push(ep); - else endpointsByReservation.set(ep.reservation_id, [ep]); - } - - const days = db.prepare('SELECT id, date FROM days WHERE trip_id = ?').all(tripId) as { id: number; date: string | null }[]; - const dayIdByDate = new Map(); - const dayDateById = new Map(); - for (const day of days) { - if (!day.date) continue; - if (!dayIdByDate.has(day.date)) dayIdByDate.set(day.date, day.id); - dayDateById.set(day.id, day.date); - } - const resolveDayId = (date: string | null): number | null => (date ? (dayIdByDate.get(date) ?? null) : null); - - const existingSigs = new Set(); - for (const row of existing) { - let meta: Record = {}; - try { - meta = row.metadata ? JSON.parse(row.metadata) : {}; - } catch { - /* malformed metadata — ignore */ - } - const eps = endpointsByReservation.get(row.id) ?? []; - const legs: any[] | null = Array.isArray(meta.legs) ? meta.legs : null; - if (legs && legs.length > 1) { - // One signature per leg. The leg's departure date comes from its own - // dep_day_id when set; the positional endpoint fallback is only sound - // while no endpoint was dropped (e.g. for missing coordinates) — a - // misaligned date would produce a WRONG signature, worse than none. - const aligned = eps.length === legs.length + 1; - legs.forEach((leg, i) => { - const legDate = (typeof leg?.dep_day_id === 'number' ? dayDateById.get(leg.dep_day_id) : null) - ?? (aligned ? eps[i]?.local_date : null) - ?? null; - const sig = softSignature(legDate, leg?.flight_number ?? null, leg?.from ?? null, leg?.to ?? null); - if (sig) existingSigs.add(sig); - }); - } else { - const from = eps[0]?.code ?? null; - const to = eps.length > 1 ? eps[eps.length - 1].code : null; - const sig = softSignature(depDate(row.reservation_time), meta.flight_number ?? null, from, to); - if (sig) existingSigs.add(sig); - } - } - - // Resolve the requested joins into validated chains. A group that doesn't - // chain, overlaps another, or contains an already-linked/duplicate flight - // degrades to individual imports rather than failing the whole request. - const groupedIds = new Set(); - const chains: AirtrailFlightRaw[][] = []; - for (const ids of connections) { - const unique = [...new Set(ids.map(String))]; - const members = unique.map(id => byId.get(id)).filter((f): f is AirtrailFlightRaw => !!f); - const chain = members.length === unique.length && !unique.some(id => groupedIds.has(id)) - ? orderConnectionChain(members) - : null; - if (!chain) { - console.warn('[airtrail-import] join group is not a connection chain — importing flights individually'); - continue; - } - if (unique.some(id => linkedIds.has(id)) || chain.some(f => { - const sig = flightSignature(f); - return !!sig && existingSigs.has(sig); - })) { - continue; // a member already exists in the trip — let the single path sort it out - } - chains.push(chain); - for (const id of unique) groupedIds.add(id); - } - - for (const chain of chains) { - const ids = chain.map(f => String(f.id)); - try { - const mapped = mapFlightsToMultiLegReservation(chain, resolveDayId); - const { reservation } = createReservation(tripId, mapped as any); - const now = new Date().toISOString(); - db.prepare( - `UPDATE reservations SET external_source = 'airtrail', external_id = ?, external_owner_user_id = ?, - sync_enabled = 0, external_synced_at = ? WHERE id = ?`, - ).run(ids[0], userId, now, reservation.id); - - reservation.external_source = 'airtrail'; - reservation.external_id = ids[0]; - reservation.external_owner_user_id = userId; - reservation.sync_enabled = 0; - reservation.external_synced_at = now; - - broadcast(tripId, 'reservation:created', { reservation }, socketId); - for (const f of chain) { - const sig = flightSignature(f); - if (sig) existingSigs.add(sig); - } - ids.forEach(id => linkedIds.add(id)); - result.imported.push(...ids); - } catch (err) { - console.error('[airtrail-import] failed to import connection', ids.join('+'), err instanceof Error ? err.message : err); - for (const id of ids) { - result.skipped.push({ flightId: id, reason: 'invalid', detail: err instanceof Error ? err.message : undefined }); - } - } - } - - for (const flight of selected) { - const fid = String(flight.id); - if (groupedIds.has(fid)) continue; - if (linkedIds.has(fid)) { - result.skipped.push({ flightId: fid, reason: 'already-imported' }); - continue; - } - - const mapped = mapFlightToReservation(flight); - const sig = flightSignature(flight); - if (sig && existingSigs.has(sig)) { - result.skipped.push({ flightId: fid, reason: 'already-in-trip', detail: mapped.title }); - continue; - } - - try { - const { reservation } = createReservation(tripId, mapped as any); - const now = new Date().toISOString(); - db.prepare( - `UPDATE reservations SET external_source = 'airtrail', external_id = ?, external_owner_user_id = ?, - sync_enabled = 1, external_hash = ?, external_synced_at = ? WHERE id = ?`, - ).run(fid, userId, canonicalHash(flight), now, reservation.id); - - // Carry the linkage on the broadcast payload so members see the badge live. - reservation.external_source = 'airtrail'; - reservation.external_id = fid; - reservation.external_owner_user_id = userId; - reservation.sync_enabled = 1; - reservation.external_synced_at = now; - - broadcast(tripId, 'reservation:created', { reservation }, socketId); - if (sig) existingSigs.add(sig); - linkedIds.add(fid); - result.imported.push(fid); - } catch (err) { - console.error('[airtrail-import] failed to import flight', fid, err instanceof Error ? err.message : err); - result.skipped.push({ flightId: fid, reason: 'invalid', detail: err instanceof Error ? err.message : undefined }); - } - } - - return result; -} diff --git a/server/src/services/airtrail/airtrailService.ts b/server/src/services/airtrail/airtrailService.ts deleted file mode 100644 index 4f5ab4194..000000000 --- a/server/src/services/airtrail/airtrailService.ts +++ /dev/null @@ -1,166 +0,0 @@ -import type { AirtrailFlight } from '@trek/shared'; -import { db } from '../../db/database'; -import { maybe_encrypt_api_key, decrypt_api_key } from '../../nest/common/crypto/apiKeyCrypto'; -import { checkSsrf } from '../../utils/ssrfGuard'; -import { writeAudit } from '../../nest/audit/audit.bridge'; -import { AirtrailAuthError, AirtrailCreds, AirtrailRequestError, listFlights } from './airtrailClient'; -import { normalizeFlight } from './airtrailMapper'; - -const KEY_MASK = '••••••••'; - -interface UserConnRow { - airtrail_url?: string | null; - airtrail_api_key?: string | null; - airtrail_allow_insecure_tls?: number | null; - airtrail_write_enabled?: number | null; -} - -function readRow(userId: number): UserConnRow | undefined { - return db - .prepare( - 'SELECT airtrail_url, airtrail_api_key, airtrail_allow_insecure_tls, airtrail_write_enabled FROM users WHERE id = ?', - ) - .get(userId) as UserConnRow | undefined; -} - -/** Has this user opted in to TREK writing their flight edits back to AirTrail? (#1240) */ -export function isAirtrailWriteEnabled(userId: number): boolean { - const row = db.prepare('SELECT airtrail_write_enabled FROM users WHERE id = ?').get(userId) as - | { airtrail_write_enabled?: number | null } - | undefined; - return !!row?.airtrail_write_enabled; -} - -/** Decrypted creds for outbound calls, or null when the user has no connection. */ -export function getAirtrailCredentials(userId: number): AirtrailCreds | null { - const row = readRow(userId); - if (!row?.airtrail_url || !row?.airtrail_api_key) return null; - const apiKey = decrypt_api_key(row.airtrail_api_key); - if (!apiKey) return null; - return { - baseUrl: row.airtrail_url, - apiKey, - allowInsecureTls: !!row.airtrail_allow_insecure_tls, - }; -} - -/** Settings as shown in the UI — the key is never echoed, only masked. */ -export function getConnectionSettings(userId: number) { - const row = readRow(userId); - return { - url: row?.airtrail_url || '', - apiKeyMasked: row?.airtrail_api_key ? KEY_MASK : '', - allowInsecureTls: !!row?.airtrail_allow_insecure_tls, - writeEnabled: !!row?.airtrail_write_enabled, - connected: !!(row?.airtrail_url && row?.airtrail_api_key), - }; -} - -export async function saveSettings( - userId: number, - url: string | undefined, - apiKey: string | undefined, - allowInsecureTls: boolean, - writeEnabled: boolean, - clientIp: string | null, -): Promise<{ success: boolean; warning?: string; error?: string }> { - const trimmedUrl = (url || '').trim(); - let warning: string | undefined; - - if (trimmedUrl) { - const ssrf = await checkSsrf(trimmedUrl); - // Reject only genuinely unusable URLs (malformed, unresolvable, non-http, - // loopback). Private/LAN instances are the common self-hosted case, so we - // persist them with a warning rather than blocking — the outbound calls - // still need ALLOW_INTERNAL_NETWORK=true to actually reach them. - if (!ssrf.allowed && !ssrf.isPrivate) { - return { success: false, error: ssrf.error ?? 'Invalid AirTrail URL' }; - } - if (ssrf.isPrivate) { - writeAudit({ - userId, - action: 'airtrail.private_ip_configured', - ip: clientIp, - details: { airtrail_url: trimmedUrl, resolved_ip: ssrf.resolvedIp }, - }); - warning = `AirTrail URL resolves to a private IP (${ssrf.resolvedIp}). Make sure this is intentional — the server may need ALLOW_INTERNAL_NETWORK=true to reach it.`; - } - } - - // Only overwrite the stored key when a genuinely new value is supplied; - // a blank field or the mask means "keep the existing key". - const provided = (apiKey || '').trim(); - const newKey = provided && provided !== KEY_MASK ? maybe_encrypt_api_key(provided) : undefined; - - if (newKey !== undefined) { - db.prepare( - 'UPDATE users SET airtrail_url = ?, airtrail_api_key = ?, airtrail_allow_insecure_tls = ?, airtrail_write_enabled = ? WHERE id = ?', - ).run(trimmedUrl || null, newKey, allowInsecureTls ? 1 : 0, writeEnabled ? 1 : 0, userId); - } else { - db.prepare( - 'UPDATE users SET airtrail_url = ?, airtrail_allow_insecure_tls = ?, airtrail_write_enabled = ? WHERE id = ?', - ).run(trimmedUrl || null, allowInsecureTls ? 1 : 0, writeEnabled ? 1 : 0, userId); - // Clearing the URL with no key left makes the connection meaningless — drop the key too. - if (!trimmedUrl) { - db.prepare('UPDATE users SET airtrail_api_key = NULL WHERE id = ?').run(userId); - } - } - - return { success: true, warning }; -} - -async function probe(creds: AirtrailCreds): Promise<{ connected: boolean; flightCount?: number; error?: string }> { - try { - const flights = await listFlights(creds); - return { connected: true, flightCount: flights.length }; - } catch (err: unknown) { - if (err instanceof AirtrailAuthError) return { connected: false, error: 'Invalid API key' }; - return { connected: false, error: err instanceof Error ? err.message : 'Connection failed' }; - } -} - -/** Live check using the stored connection. */ -export async function getConnectionStatus( - userId: number, -): Promise<{ connected: boolean; flightCount?: number; error?: string }> { - const creds = getAirtrailCredentials(userId); - if (!creds) return { connected: false, error: 'Not configured' }; - return probe(creds); -} - -/** - * "Test connection" from the settings form. Uses the typed URL/key when given; - * falls back to the stored key when the key field still shows the mask. - */ -export async function testConnection( - userId: number, - url: string | undefined, - apiKey: string | undefined, - allowInsecureTls: boolean, -): Promise<{ connected: boolean; flightCount?: number; error?: string }> { - const trimmedUrl = (url || '').trim(); - const provided = (apiKey || '').trim(); - - const stored = getAirtrailCredentials(userId); - const effectiveUrl = trimmedUrl || stored?.baseUrl; - const effectiveKey = provided && provided !== KEY_MASK ? provided : stored?.apiKey; - - if (!effectiveUrl || !effectiveKey) { - return { connected: false, error: 'URL and API key required' }; - } - - const ssrf = await checkSsrf(effectiveUrl); - if (!ssrf.allowed && !ssrf.isPrivate) { - return { connected: false, error: ssrf.error ?? 'Invalid AirTrail URL' }; - } - - return probe({ baseUrl: effectiveUrl, apiKey: effectiveKey, allowInsecureTls }); -} - -/** The user's AirTrail flights, normalized for the import picker. */ -export async function getFlightsForPicker(userId: number): Promise { - const creds = getAirtrailCredentials(userId); - if (!creds) throw new AirtrailRequestError('AirTrail is not connected', 400); - const raw = await listFlights(creds); - return raw.map(normalizeFlight); -} diff --git a/server/src/services/airtrail/airtrailSync.ts b/server/src/services/airtrail/airtrailSync.ts deleted file mode 100644 index 1861b6160..000000000 --- a/server/src/services/airtrail/airtrailSync.ts +++ /dev/null @@ -1,330 +0,0 @@ -import { ADDON_IDS } from '../../addons'; -import { db } from '../../db/database'; -import { broadcast } from '../../websocket'; -import { isAddonEnabled } from '../../nest/addons/addons.bridge'; -import { logError, logInfo } from '../../nest/audit/audit-log.logger'; -import { getReservation, getReservationWithJoins, updateReservation } from '../../nest/reservations/reservations.bridge'; -import { - AirtrailAuthError, - AirtrailCreds, - AirtrailFlightRaw, - AirtrailSavePayload, - getFlight, - listFlights, - saveFlight, -} from './airtrailClient'; -import { canonicalHash, entityCode, mapFlightToReservation } from './airtrailMapper'; -import { getAirtrailCredentials, isAirtrailWriteEnabled } from './airtrailService'; - -/** Global on/off: the addon must be enabled and sync not explicitly turned off. */ -export function syncGloballyEnabled(): boolean { - if (!isAddonEnabled(ADDON_IDS.AIRTRAIL)) return false; - const row = db.prepare("SELECT value FROM app_settings WHERE key = 'airtrail_sync_enabled'").get() as - | { value: string } - | undefined; - return row?.value !== 'false'; -} - -function broadcastUpdated(tripId: number, reservationId: number): void { - try { - const reservation = getReservationWithJoins(reservationId); - if (reservation) broadcast(tripId, 'reservation:updated', { reservation }); - } catch { - /* broadcast failure is non-fatal */ - } -} - -function detach(tripId: number, reservationId: number): void { - db.prepare('UPDATE reservations SET sync_enabled = 0 WHERE id = ?').run(reservationId); - broadcastUpdated(tripId, reservationId); -} - -/** - * True when the reservation has grown into a multi-leg booking locally (extra - * stops / metadata.legs) — a shape the single AirTrail flight it is linked to - * cannot represent. Syncing such a row in either direction would corrupt one - * side: a pull flattens the layover chain back to from→to, a push rewrites the - * AirTrail flight to span the whole route (#1535). - */ -function hasLocalMultiLegShape(reservationId: number, metadataJson: string | null | undefined): boolean { - try { - const meta = metadataJson ? JSON.parse(metadataJson) : {}; - if (Array.isArray(meta?.legs) && meta.legs.length > 1) return true; - } catch { - /* malformed metadata — fall through to the endpoint count */ - } - const row = db.prepare('SELECT COUNT(*) AS n FROM reservation_endpoints WHERE reservation_id = ?').get(reservationId) as { - n: number; - }; - return row.n > 2; -} - -// ── AirTrail → TREK (poll) ─────────────────────────────────────────────────── - -/** - * Reconcile one owner's linked reservations against their current AirTrail - * flights: apply field changes (detected by snapshot hash, since AirTrail has no - * updated_at) and, when a flight is gone from AirTrail, keep the TREK row but - * stop syncing it. Only already-imported flights are touched — new AirTrail - * flights are never auto-added to a trip. Returns how many rows changed. - */ -async function syncOwner(uid: number): Promise { - const creds = getAirtrailCredentials(uid); - if (!creds) return 0; // owner disconnected — leave their linked rows as-is - - let flights: AirtrailFlightRaw[]; - try { - flights = await listFlights(creds); - } catch (err) { - if (err instanceof AirtrailAuthError) logError(`AirTrail sync: invalid API key for user ${uid}`); - return 0; - } - const byId = new Map(flights.map((f) => [String(f.id), f])); - - const linked = db - .prepare( - "SELECT id, trip_id, external_id, external_hash FROM reservations WHERE external_source = 'airtrail' AND sync_enabled = 1 AND external_owner_user_id = ?", - ) - .all(uid) as { id: number; trip_id: number; external_id: string; external_hash: string | null }[]; - - let changed = 0; - for (const row of linked) { - const flight = byId.get(String(row.external_id)); - if (!flight) { - detach(row.trip_id, row.id); // deleted in AirTrail → keep row, stop syncing - changed++; - continue; - } - - const hash = canonicalHash(flight); - if (hash === row.external_hash) continue; - - const current = getReservation(row.id, row.trip_id); - if (!current) continue; - if (hasLocalMultiLegShape(row.id, (current as any).metadata)) { - // The user connected this flight into a multi-leg booking; applying the - // remote single-flight shape would flatten it. Stop syncing instead. - detach(row.trip_id, row.id); - changed++; - continue; - } - try { - updateReservation(row.id, row.trip_id, mapFlightToReservation(flight) as any, current as any); - db.prepare('UPDATE reservations SET external_hash = ?, external_synced_at = ? WHERE id = ?').run( - hash, - new Date().toISOString(), - row.id, - ); - broadcastUpdated(row.trip_id, row.id); - changed++; - } catch (err) { - logError(`AirTrail sync: failed to update reservation ${row.id}: ${err instanceof Error ? err.message : err}`); - } - } - return changed; -} - -let running = false; - -/** Background poll across every connected owner (scheduler). */ -export async function runAirtrailSync(): Promise { - if (running) return; - if (!syncGloballyEnabled()) return; - running = true; - let changed = 0; - try { - const owners = db - .prepare( - "SELECT DISTINCT external_owner_user_id AS uid FROM reservations WHERE external_source = 'airtrail' AND sync_enabled = 1 AND external_owner_user_id IS NOT NULL", - ) - .all() as { uid: number }[]; - for (const { uid } of owners) changed += await syncOwner(uid); - if (changed > 0) logInfo(`AirTrail sync: applied ${changed} change(s)`); - } catch (err) { - logError(`AirTrail sync failed: ${err instanceof Error ? err.message : err}`); - } finally { - running = false; - } -} - -/** - * On-demand sync of just this user's linked flights — called when the user opens - * a trip so AirTrail-side edits show up immediately instead of waiting for the - * background poll. - */ -export async function runAirtrailSyncForUser(userId: number): Promise<{ changed: number }> { - if (!syncGloballyEnabled()) return { changed: 0 }; - try { - return { changed: await syncOwner(userId) }; - } catch (err) { - logError(`AirTrail sync (user ${userId}) failed: ${err instanceof Error ? err.message : err}`); - return { changed: 0 }; - } -} - -// ── TREK → AirTrail (push) ─────────────────────────────────────────────────── - -function splitLocal(dt: string | null | undefined): { date: string | null; time: string | null } { - if (!dt) return { date: null, time: null }; - const date = dt.slice(0, 10); - const m = dt.slice(10).match(/(\d{2}:\d{2})/); - return { date: /^\d{4}-\d{2}-\d{2}$/.test(date) ? date : null, time: m ? m[1] : null }; -} - -/** - * Build the POST /flight/save body. AirTrail's save fully overwrites the flight, - * so we start from the flight as AirTrail currently has it (`existing`, the raw - * GET object) and overwrite ONLY the fields TREK manages. Everything else — - * terminal, gate, scheduled/actual times, customFields, track, and any field - * AirTrail may add later — passes through untouched. We deliberately do NOT model - * those fields; spreading the raw object keeps us decoupled from AirTrail's schema - * (#1240). - */ -export function buildSavePayload(reservation: any, existing: AirtrailFlightRaw): AirtrailSavePayload | null { - let meta: Record; - try { - meta = reservation.metadata ? JSON.parse(reservation.metadata) : {}; - } catch { - meta = {}; - } - const endpoints: any[] = reservation.endpoints || []; - const fromEp = endpoints.find((e) => e.role === 'from'); - const toEp = endpoints.find((e) => e.role === 'to'); - const fromCode = fromEp?.code || existing.from?.iata || existing.from?.icao || null; - const toCode = toEp?.code || existing.to?.iata || existing.to?.icao || null; - if (!fromCode || !toCode) return null; - - const dep = splitLocal(reservation.reservation_time); - const arr = splitLocal(reservation.reservation_end_time); - if (!dep.date) return null; - - // Preserve the existing seat manifest (an update replaces all seats); fall back - // to the key-owner placeholder so AirTrail attributes it to the connecting user. - const seats = (existing.seats ?? []).map((s) => ({ - userId: s.userId, - guestName: s.guestName, - seat: s.seat, - seatNumber: s.seatNumber, - seatClass: s.seatClass, - })); - if (seats.length === 0) { - seats.push({ userId: '', guestName: null, seat: null, seatNumber: null, seatClass: null }); - } - - // Push the seat the user set in TREK onto their own AirTrail seat (the one with - // a userId), leaving any co-passenger seats untouched. - const seatNumber = typeof meta.seat === 'string' && meta.seat.trim() ? meta.seat.trim() : null; - if (seatNumber) { - const ownSeat = seats.find((s) => s.userId) ?? seats[0]; - if (ownSeat) ownSeat.seatNumber = seatNumber; - } - - // Spread the existing flight first to preserve every AirTrail-owned field, then - // overwrite only what TREK manages. `from`/`to`/`airline`/`aircraft` come back - // from GET as objects but the save shape wants codes — those are exactly the - // keys we override, so the spread never ships an object where a code is wanted. - return { - // Cast so the spread carries through the AirTrail-owned keys we deliberately - // don't model (terminal, gate, scheduled/actual times, customFields, track, …). - ...(existing as unknown as Record), - id: Number(reservation.external_id), - from: fromCode, - to: toCode, - departure: dep.date, - departureTime: dep.time, - arrival: arr.date, - arrivalTime: arr.time, - // Import reads the SCHEDULED time, so a TREK edit must write back there too — - // otherwise the next pull (scheduled-wins) would revert it. AirTrail rebuilds the - // instant from a full-ISO date carrier + the HH:MM time, so pass a date carrier. - departureScheduled: dep.date ? `${dep.date}T00:00:00.000Z` : null, - departureScheduledTime: dep.time, - arrivalScheduled: arr.date ? `${arr.date}T00:00:00.000Z` : null, - arrivalScheduledTime: arr.time, - // These are AirTrail-owned details TREK doesn't surface in its edit UI — a TREK - // edit can leave them out of `metadata`. Preserve AirTrail's current value when - // TREK has none rather than nulling it out (#1240). Use airline_code (not the - // display name in metadata.airline, #1334); both it and entityCode mirror the - // import/hash code-selection so a writeback stays a no-op for the hash. - airline: meta.airline_code ?? entityCode(existing.airline) ?? null, - flightNumber: meta.flight_number ?? existing.flightNumber ?? null, - aircraft: meta.aircraft ?? entityCode(existing.aircraft) ?? null, - aircraftReg: meta.aircraft_reg ?? existing.aircraftReg ?? null, - flightReason: meta.flight_reason ?? existing.flightReason ?? null, - note: reservation.notes ?? existing.note ?? null, - seats, - } as AirtrailSavePayload; -} - -/** - * Push a locally-edited linked reservation back to AirTrail using the importer's - * (owner's) credentials — even if a different member made the edit. If the owner - * is gone or the flight no longer exists in AirTrail, the link is detached so the - * next pull's AirTrail-wins policy can't silently revert the local edit. - */ -export async function pushReservationToAirtrail(reservationId: number, tripId: number): Promise { - if (!syncGloballyEnabled()) return; - - const row = db - .prepare( - "SELECT id, trip_id, external_id, external_owner_user_id, sync_enabled FROM reservations WHERE id = ? AND external_source = 'airtrail'", - ) - .get(reservationId) as - | { id: number; trip_id: number; external_id: string; external_owner_user_id: number | null; sync_enabled: number } - | undefined; - if (!row || !row.sync_enabled) return; - - // An edit that turned this linked flight into a multi-leg booking severs the - // 1:1 mapping to the AirTrail flight: pushing would rewrite that flight to the - // full span, and the next pull would flatten the layover again. Detach — the - // merge is a deliberate local restructuring, like a joined import (#1535). - const reservation = getReservationWithJoins(row.id); - if (!reservation) return; - if (hasLocalMultiLegShape(row.id, reservation.metadata)) { - detach(tripId, row.id); - return; - } - - // AirTrail is read-only by default (#1240). Only push when the flight's owner has - // explicitly opted in. A no-op skip (not a detach): the link stays active so the - // inbound, AirTrail-wins pull keeps the reservation up to date. - if (!row.external_owner_user_id || !isAirtrailWriteEnabled(row.external_owner_user_id)) return; - - const creds: AirtrailCreds | null = getAirtrailCredentials(row.external_owner_user_id); - if (!creds) { - detach(tripId, row.id); // owner disconnected — cannot push, so stop syncing - return; - } - - let existing: AirtrailFlightRaw | null; - try { - existing = await getFlight(creds, Number(row.external_id)); - } catch (err) { - if (err instanceof AirtrailAuthError) detach(tripId, row.id); - else logError(`AirTrail push: get failed for reservation ${row.id}: ${err instanceof Error ? err.message : err}`); - return; - } - if (!existing) { - detach(tripId, row.id); // gone in AirTrail → treat like a remote delete - return; - } - - const payload = buildSavePayload(reservation, existing); - if (!payload) return; - - try { - await saveFlight(creds, payload); - // Self-write suppression: re-read the saved flight and store its hash so the - // next poll doesn't treat our own write as an inbound change. - const saved = await getFlight(creds, Number(row.external_id)); - if (saved) { - db.prepare('UPDATE reservations SET external_hash = ?, external_synced_at = ? WHERE id = ?').run( - canonicalHash(saved), - new Date().toISOString(), - row.id, - ); - } - } catch (err) { - logError(`AirTrail push failed for reservation ${row.id}: ${err instanceof Error ? err.message : err}`); - } -} diff --git a/server/tests/unit/services/airtrailImport.test.ts b/server/tests/unit/services/airtrailImport.test.ts index beaa9fbe5..10878f691 100644 --- a/server/tests/unit/services/airtrailImport.test.ts +++ b/server/tests/unit/services/airtrailImport.test.ts @@ -8,20 +8,48 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; * doesn't actually chain. */ -vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() })); -vi.mock('../../../src/services/airtrail/airtrailService', () => ({ - getAirtrailCredentials: vi.fn(() => ({ baseUrl: 'https://at.example', apiKey: 'k', allowInsecureTls: false })), -})); -vi.mock('../../../src/services/airtrail/airtrailClient', async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, listFlights: vi.fn() }; -}); - import { db } from '../../../src/db/database'; import { createUser, createTrip } from '../../helpers/factories'; -import { listFlights } from '../../../src/services/airtrail/airtrailClient'; -import type { AirtrailAirport, AirtrailFlightRaw } from '../../../src/services/airtrail/airtrailClient'; -import { importAirtrailFlights } from '../../../src/services/airtrail/airtrailImport'; +import type { AirtrailAirport, AirtrailFlightRaw } from '../../../src/nest/integrations/airtrail.client'; +import { AirtrailImportService } from '../../../src/nest/integrations/airtrail-import.service'; +import { DatabaseService } from '../../../src/nest/database/database.service'; +import { PermissionsService } from '../../../src/nest/permissions/permissions.service'; +import { RealtimeService } from '../../../src/nest/realtime/realtime.service'; +import { BudgetService } from '../../../src/nest/budget/budget.service'; +import { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.service'; +import { ReservationsService } from '../../../src/nest/reservations/reservations.service'; +import type { AirtrailClient } from '../../../src/nest/integrations/airtrail.client'; +import type { AirtrailService } from '../../../src/nest/integrations/airtrail.service'; + +// The client and the per-user credentials are the only stubs; the reservation +// writes go through the real service against the real test DB, as before. They +// were module mocks until the fold made them injected collaborators. +const listFlights = vi.fn(); +const broadcast = vi.fn(); + +function makeImportService(): AirtrailImportService { + const dbs = () => new DatabaseService(db); + const permissions = new PermissionsService(dbs()); + const realtime = { broadcast } as unknown as RealtimeService; + return new AirtrailImportService( + dbs(), + realtime, + new ReservationsService( + dbs(), + permissions, + new BudgetService(dbs(), permissions, new ExchangeRatesService(), realtime), + realtime, + ), + { listFlights } as unknown as AirtrailClient, + { + getAirtrailCredentials: () => ({ baseUrl: 'https://at.example', apiKey: 'k', allowInsecureTls: false }), + } as unknown as AirtrailService, + ); +} + +const importAirtrailFlights = ( + ...args: Parameters +) => makeImportService().importAirtrailFlights(...args); const BRU: AirtrailAirport = { id: 1, icao: 'EBBR', iata: 'BRU', name: 'Brussels', lat: 50.9014, lon: 4.4844, tz: 'Europe/Brussels', country: 'BE' }; const HEL: AirtrailAirport = { id: 2, icao: 'EFHK', iata: 'HEL', name: 'Helsinki-Vantaa', lat: 60.3172, lon: 24.9633, tz: 'Europe/Helsinki', country: 'FI' }; @@ -93,7 +121,7 @@ beforeEach(() => { describe('importAirtrailFlights connection joining (#1535)', () => { it('imports a connection chain as ONE multi-leg reservation, detached from live sync', async () => { - (listFlights as any).mockResolvedValue([legBruHel(), legHelJfk()]); + listFlights.mockResolvedValue([legBruHel(), legHelJfk()]); // Deliberately unordered — the server orders the chain by departure itself. const result = await importAirtrailFlights(tripId, userId, ['101', '102'], undefined, [['102', '101']]); @@ -131,7 +159,7 @@ describe('importAirtrailFlights connection joining (#1535)', () => { departure: '2026-08-02T07:00:00.000+00:00', arrival: '2026-08-02T15:00:00.000+00:00', }; - (listFlights as any).mockResolvedValue([legBruHel(), overnightLeg2]); + listFlights.mockResolvedValue([legBruHel(), overnightLeg2]); await importAirtrailFlights(tripId, userId, ['101', '102'], undefined, [['101', '102']]); const [r] = tripReservations(tripId); @@ -152,7 +180,7 @@ describe('importAirtrailFlights connection joining (#1535)', () => { arrival: '2026-08-01T21:30:00.000+00:00', flightNumber: 'AY1503', }; - (listFlights as any).mockResolvedValue([legBruHel(), returnFlight]); + listFlights.mockResolvedValue([legBruHel(), returnFlight]); const result = await importAirtrailFlights(tripId, userId, ['101', '104'], undefined, [['101', '104']]); expect([...result.imported].sort()).toEqual(['101', '104']); @@ -160,7 +188,7 @@ describe('importAirtrailFlights connection joining (#1535)', () => { }); it('skips every member of a joined booking on a later import attempt', async () => { - (listFlights as any).mockResolvedValue([legBruHel(), legHelJfk()]); + listFlights.mockResolvedValue([legBruHel(), legHelJfk()]); await importAirtrailFlights(tripId, userId, ['101', '102'], undefined, [['101', '102']]); // Only leg 2 carries no external_id of its own — it must still be recognized @@ -172,13 +200,13 @@ describe('importAirtrailFlights connection joining (#1535)', () => { }); it('recognizes a joined leg imported by another member via its per-leg signature', async () => { - (listFlights as any).mockResolvedValue([legBruHel(), legHelJfk()]); + listFlights.mockResolvedValue([legBruHel(), legHelJfk()]); await importAirtrailFlights(tripId, userId, ['101', '102'], undefined, [['101', '102']]); // The same physical HEL→JFK flight from another member's AirTrail carries a // different id there — the flight-number@date signature must catch it. const { user: other } = createUser(db); - (listFlights as any).mockResolvedValue([{ ...legHelJfk(), id: 999 }]); + listFlights.mockResolvedValue([{ ...legHelJfk(), id: 999 }]); const result = await importAirtrailFlights(tripId, other.id, ['999'], undefined); expect(result.imported).toEqual([]); expect(result.skipped).toEqual([{ flightId: '999', reason: 'already-in-trip', detail: expect.any(String) }]); @@ -186,7 +214,7 @@ describe('importAirtrailFlights connection joining (#1535)', () => { }); it('falls back to individual imports when the requested join does not chain', async () => { - (listFlights as any).mockResolvedValue([legBruHel(), legLhrJfk()]); + listFlights.mockResolvedValue([legBruHel(), legLhrJfk()]); const result = await importAirtrailFlights(tripId, userId, ['101', '103'], undefined, [['101', '103']]); expect([...result.imported].sort()).toEqual(['101', '103']); @@ -201,7 +229,7 @@ describe('importAirtrailFlights connection joining (#1535)', () => { it('falls back to individual imports when the layover exceeds 24 h', async () => { const lateLeg2 = { ...legHelJfk(), departure: '2026-08-03T11:00:00.000+00:00', arrival: '2026-08-03T19:00:00.000+00:00', date: '2026-08-03' }; - (listFlights as any).mockResolvedValue([legBruHel(), lateLeg2]); + listFlights.mockResolvedValue([legBruHel(), lateLeg2]); const result = await importAirtrailFlights(tripId, userId, ['101', '102'], undefined, [['101', '102']]); expect([...result.imported].sort()).toEqual(['101', '102']); @@ -209,7 +237,7 @@ describe('importAirtrailFlights connection joining (#1535)', () => { }); it('imports singles exactly as before when no join is requested', async () => { - (listFlights as any).mockResolvedValue([legBruHel()]); + listFlights.mockResolvedValue([legBruHel()]); const result = await importAirtrailFlights(tripId, userId, ['101'], undefined); expect(result.imported).toEqual(['101']); diff --git a/server/tests/unit/services/airtrailMapper.test.ts b/server/tests/unit/services/airtrailMapper.test.ts index dfb9c1489..4501c5918 100644 --- a/server/tests/unit/services/airtrailMapper.test.ts +++ b/server/tests/unit/services/airtrailMapper.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; -import { canonicalHash, mapFlightToReservation, mapFlightsToMultiLegReservation, normalizeFlight } from '../../../src/services/airtrail/airtrailMapper'; -import type { AirtrailFlightRaw } from '../../../src/services/airtrail/airtrailClient'; +import { canonicalHash, mapFlightToReservation, mapFlightsToMultiLegReservation, normalizeFlight } from '../../../src/nest/integrations/airtrail.mapper'; +import type { AirtrailFlightRaw } from '../../../src/nest/integrations/airtrail.client'; function airport(over: Partial = {}): NonNullable { return { diff --git a/server/tests/unit/services/airtrailSync.test.ts b/server/tests/unit/services/airtrailSync.test.ts index e60b73891..ec4dbf52a 100644 --- a/server/tests/unit/services/airtrailSync.test.ts +++ b/server/tests/unit/services/airtrailSync.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; -import { buildSavePayload } from '../../../src/services/airtrail/airtrailSync'; -import type { AirtrailAirport, AirtrailFlightRaw } from '../../../src/services/airtrail/airtrailClient'; +import { buildSavePayload } from '../../../src/nest/integrations/airtrail-sync.service'; +import type { AirtrailAirport, AirtrailFlightRaw } from '../../../src/nest/integrations/airtrail.client'; function airport(over: Partial = {}): AirtrailAirport { return { diff --git a/server/tests/unit/services/airtrailWriteGate.test.ts b/server/tests/unit/services/airtrailWriteGate.test.ts index 5311573f8..8961fd9b6 100644 --- a/server/tests/unit/services/airtrailWriteGate.test.ts +++ b/server/tests/unit/services/airtrailWriteGate.test.ts @@ -2,66 +2,85 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; /** * The #1240 write gate: pushReservationToAirtrail must NOT write to AirTrail unless - * the flight's owner has opted in (airtrail_write_enabled). Collaborators are mocked + * the flight's owner has opted in (airtrail_write_enabled). Collaborators are stubbed * so the test exercises just the gate + payload wiring. + * + * They used to be module mocks over free functions. The fold made them injected + * services, so the stubs go through the constructor now — which is the point: + * the collaborators are visible in the signature instead of resolved by path. + * Only the mapper stays a module mock, because it stayed free functions. */ - -vi.mock('../../../src/db/database', () => ({ db: { prepare: vi.fn() } })); -vi.mock('../../../src/nest/addons/addons.bridge', () => ({ isAddonEnabled: vi.fn(() => true) })); -vi.mock('../../../src/nest/audit/audit-log.logger', () => ({ logError: vi.fn(), logInfo: vi.fn() })); -vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() })); -vi.mock('../../../src/nest/reservations/reservations.bridge', () => ({ - getReservation: vi.fn(), - getReservationWithJoins: vi.fn(), - updateReservation: vi.fn(), -})); -vi.mock('../../../src/services/airtrail/airtrailClient', () => ({ - AirtrailAuthError: class AirtrailAuthError extends Error {}, - getFlight: vi.fn(), - listFlights: vi.fn(), - saveFlight: vi.fn(), -})); -vi.mock('../../../src/services/airtrail/airtrailMapper', () => ({ +vi.mock('../../../src/nest/integrations/airtrail.mapper', () => ({ canonicalHash: vi.fn(() => 'hash'), mapFlightToReservation: vi.fn(() => ({})), entityCode: (e: any) => e?.icao || e?.iata || null, })); -vi.mock('../../../src/services/airtrail/airtrailService', () => ({ - isAirtrailWriteEnabled: vi.fn(), - getAirtrailCredentials: vi.fn(), -})); -import { pushReservationToAirtrail, runAirtrailSyncForUser } from '../../../src/services/airtrail/airtrailSync'; -import { db } from '../../../src/db/database'; -import { getReservation, getReservationWithJoins, updateReservation } from '../../../src/nest/reservations/reservations.bridge'; -import { getFlight, listFlights, saveFlight } from '../../../src/services/airtrail/airtrailClient'; -import { isAirtrailWriteEnabled, getAirtrailCredentials } from '../../../src/services/airtrail/airtrailService'; +import { AirtrailSyncService } from '../../../src/nest/integrations/airtrail-sync.service'; +import { AirtrailAuthError } from '../../../src/nest/integrations/airtrail.client'; +import type { DatabaseService } from '../../../src/nest/database/database.service'; +import type { RealtimeService } from '../../../src/nest/realtime/realtime.service'; +import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { ReservationsService } from '../../../src/nest/reservations/reservations.service'; +import type { AirtrailClient } from '../../../src/nest/integrations/airtrail.client'; +import type { AirtrailService } from '../../../src/nest/integrations/airtrail.service'; const linkedRow = { id: 5, trip_id: 9, external_id: '42', external_owner_user_id: 7, sync_enabled: 1 }; -const runSpy = vi.fn(); -beforeEach(() => { - vi.clearAllMocks(); - // Route db reads: global sync setting, the linked reservation row and the - // endpoint count the multi-leg guard checks (#1535) — two = plain from/to. - (db.prepare as any).mockImplementation((sql: string) => ({ - get: () => { - if (sql.includes('app_settings')) return { value: 'true' }; - if (sql.includes('FROM reservation_endpoints')) return { n: 2 }; - if (sql.includes('FROM reservations')) return { ...linkedRow }; - return undefined; - }, - run: (...args: any[]) => { +const runSpy = vi.fn(); +const getFlight = vi.fn(); +const listFlights = vi.fn(); +const saveFlight = vi.fn(); +const getReservation = vi.fn(); +const getReservationWithJoins = vi.fn(); +const updateReservation = vi.fn(); +const isAirtrailWriteEnabled = vi.fn(); +const getAirtrailCredentials = vi.fn(); + +/** Routes reads by SQL, exactly as the old db.prepare stub did. */ +let dbGet: (sql: string) => unknown; +let dbAll: (sql: string) => unknown[]; + +function makeService(): AirtrailSyncService { + const db = { + get: (sql: string) => dbGet(sql), + all: (sql: string) => dbAll(sql), + run: (sql: string, ...args: unknown[]) => { runSpy(sql, args); return {}; }, - all: () => [], - })); - (getAirtrailCredentials as any).mockReturnValue({ baseUrl: 'https://at.example', apiKey: 'k', allowInsecureTls: false }); + } as unknown as DatabaseService; + + return new AirtrailSyncService( + db, + { broadcast: vi.fn() } as unknown as RealtimeService, + { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + { getReservation, getReservationWithJoins, update: updateReservation } as unknown as ReservationsService, + { getFlight, listFlights, saveFlight } as unknown as AirtrailClient, + { isAirtrailWriteEnabled, getAirtrailCredentials } as unknown as AirtrailService, + ); +} + +let svc: AirtrailSyncService; + +beforeEach(() => { + vi.clearAllMocks(); + // Global sync setting, the linked reservation row and the endpoint count the + // multi-leg guard checks (#1535) — two = plain from/to. + dbGet = (sql: string) => { + if (sql.includes('app_settings')) return { value: 'true' }; + if (sql.includes('FROM reservation_endpoints')) return { n: 2 }; + if (sql.includes('FROM reservations')) return { ...linkedRow }; + return undefined; + }; + dbAll = () => []; + svc = makeService(); + + getAirtrailCredentials.mockReturnValue({ baseUrl: 'https://at.example', apiKey: 'k', allowInsecureTls: false }); // GET returns AirTrail-owned detail TREK doesn't model — must survive the writeback. - (getFlight as any).mockResolvedValue({ id: 42, from: { iata: 'JFK' }, to: { iata: 'LHR' }, seats: [], departureTerminal: '7' }); - (saveFlight as any).mockResolvedValue({ id: 42 }); - (getReservationWithJoins as any).mockReturnValue({ + getFlight.mockResolvedValue({ id: 42, from: { iata: 'JFK' }, to: { iata: 'LHR' }, seats: [], departureTerminal: '7' }); + saveFlight.mockResolvedValue({ id: 42 }); + getReservationWithJoins.mockReturnValue({ external_id: '42', reservation_time: '2021-09-01T19:00', reservation_end_time: '2021-09-02T08:00', @@ -76,101 +95,117 @@ beforeEach(() => { describe('pushReservationToAirtrail write gate (#1240)', () => { it('does nothing — and does not detach — when the owner has not opted in', async () => { - (isAirtrailWriteEnabled as any).mockReturnValue(false); - await pushReservationToAirtrail(5, 9); + isAirtrailWriteEnabled.mockReturnValue(false); + await svc.pushReservationToAirtrail(5, 9); expect(getFlight).not.toHaveBeenCalled(); expect(saveFlight).not.toHaveBeenCalled(); expect(runSpy).not.toHaveBeenCalled(); // no detach, no hash write — pure no-op }); it('writes back, preserving AirTrail-owned fields, when the owner has opted in', async () => { - (isAirtrailWriteEnabled as any).mockReturnValue(true); - await pushReservationToAirtrail(5, 9); + isAirtrailWriteEnabled.mockReturnValue(true); + await svc.pushReservationToAirtrail(5, 9); expect(saveFlight).toHaveBeenCalledTimes(1); - const payload = (saveFlight as any).mock.calls[0][1]; + const payload = saveFlight.mock.calls[0][1] as Record; expect(payload.departureTerminal).toBe('7'); // spread preserved the unmanaged field expect(payload.from).toBe('JFK'); // TREK-managed field still applied as a code }); it('#1535 detaches instead of pushing when the reservation grew extra stops', async () => { - (isAirtrailWriteEnabled as any).mockReturnValue(true); - (db.prepare as any).mockImplementation((sql: string) => ({ - get: () => { - if (sql.includes('app_settings')) return { value: 'true' }; - if (sql.includes('FROM reservation_endpoints')) return { n: 3 }; // from + stop + to - if (sql.includes('FROM reservations')) return { ...linkedRow }; - return undefined; - }, - run: (...args: any[]) => { - runSpy(sql, args); - return {}; - }, - all: () => [], - })); - await pushReservationToAirtrail(5, 9); + isAirtrailWriteEnabled.mockReturnValue(true); + dbGet = (sql: string) => { + if (sql.includes('app_settings')) return { value: 'true' }; + if (sql.includes('FROM reservation_endpoints')) return { n: 3 }; // from + stop + to + if (sql.includes('FROM reservations')) return { ...linkedRow }; + return undefined; + }; + await svc.pushReservationToAirtrail(5, 9); // Pushing would rewrite the single AirTrail flight to span the whole route. expect(saveFlight).not.toHaveBeenCalled(); expect(runSpy).toHaveBeenCalledWith(expect.stringContaining('sync_enabled = 0'), [5]); }); it('#1535 detaches on metadata.legs even when the endpoint count is not available', async () => { - (isAirtrailWriteEnabled as any).mockReturnValue(true); - (getReservationWithJoins as any).mockReturnValue({ + isAirtrailWriteEnabled.mockReturnValue(true); + getReservationWithJoins.mockReturnValue({ external_id: '42', reservation_time: '2021-09-01T19:00', metadata: JSON.stringify({ legs: [{ from: 'BRU', to: 'HEL' }, { from: 'HEL', to: 'JFK' }] }), endpoints: [], }); - await pushReservationToAirtrail(5, 9); + await svc.pushReservationToAirtrail(5, 9); + expect(saveFlight).not.toHaveBeenCalled(); + expect(runSpy).toHaveBeenCalledWith(expect.stringContaining('sync_enabled = 0'), [5]); + }); + + it('detaches when the owner key stopped working, rather than retrying forever', async () => { + isAirtrailWriteEnabled.mockReturnValue(true); + getFlight.mockRejectedValue(new AirtrailAuthError('invalid key')); + await svc.pushReservationToAirtrail(5, 9); + expect(saveFlight).not.toHaveBeenCalled(); + expect(runSpy).toHaveBeenCalledWith(expect.stringContaining('sync_enabled = 0'), [5]); + }); + + it('detaches when the flight is gone from AirTrail — the same as a remote delete', async () => { + isAirtrailWriteEnabled.mockReturnValue(true); + getFlight.mockResolvedValue(null); + await svc.pushReservationToAirtrail(5, 9); expect(saveFlight).not.toHaveBeenCalled(); expect(runSpy).toHaveBeenCalledWith(expect.stringContaining('sync_enabled = 0'), [5]); }); }); describe('inbound sync multi-leg guard (#1535)', () => { + function withLinkedRow(endpointCount: number) { + dbGet = (sql: string) => { + if (sql.includes('app_settings')) return { value: 'true' }; + if (sql.includes('FROM reservation_endpoints')) return { n: endpointCount }; + return undefined; + }; + dbAll = (sql: string) => + sql.includes('sync_enabled = 1') ? [{ id: 5, trip_id: 9, external_id: '42', external_hash: 'stale' }] : []; + svc = makeService(); + } + it('detaches instead of flattening when a linked reservation grew extra stops locally', async () => { // A remote change is pending (stored hash differs from canonicalHash's // 'hash'), but the local reservation has become multi-leg — applying the // single-flight shape would flatten the layover chain. - (db.prepare as any).mockImplementation((sql: string) => ({ - get: () => { - if (sql.includes('app_settings')) return { value: 'true' }; - if (sql.includes('FROM reservation_endpoints')) return { n: 3 }; - return undefined; - }, - all: () => (sql.includes('sync_enabled = 1') ? [{ id: 5, trip_id: 9, external_id: '42', external_hash: 'stale' }] : []), - run: (...args: any[]) => { - runSpy(sql, args); - return {}; - }, - })); - (listFlights as any).mockResolvedValue([{ id: 42 }]); - (getReservation as any).mockReturnValue({ id: 5, metadata: JSON.stringify({}) }); + withLinkedRow(3); + listFlights.mockResolvedValue([{ id: 42 }]); + getReservation.mockReturnValue({ id: 5, metadata: JSON.stringify({}) }); - const { changed } = await runAirtrailSyncForUser(7); + const { changed } = await svc.runAirtrailSyncForUser(7); expect(updateReservation).not.toHaveBeenCalled(); expect(runSpy).toHaveBeenCalledWith(expect.stringContaining('sync_enabled = 0'), [5]); expect(changed).toBe(1); }); it('still applies a remote change to a plain single-leg reservation', async () => { - (db.prepare as any).mockImplementation((sql: string) => ({ - get: () => { - if (sql.includes('app_settings')) return { value: 'true' }; - if (sql.includes('FROM reservation_endpoints')) return { n: 2 }; - return undefined; - }, - all: () => (sql.includes('sync_enabled = 1') ? [{ id: 5, trip_id: 9, external_id: '42', external_hash: 'stale' }] : []), - run: (...args: any[]) => { - runSpy(sql, args); - return {}; - }, - })); - (listFlights as any).mockResolvedValue([{ id: 42 }]); - (getReservation as any).mockReturnValue({ id: 5, metadata: JSON.stringify({}) }); + withLinkedRow(2); + listFlights.mockResolvedValue([{ id: 42 }]); + getReservation.mockReturnValue({ id: 5, metadata: JSON.stringify({}) }); - await runAirtrailSyncForUser(7); + await svc.runAirtrailSyncForUser(7); expect(updateReservation).toHaveBeenCalledTimes(1); expect(runSpy).not.toHaveBeenCalledWith(expect.stringContaining('sync_enabled = 0'), expect.anything()); }); + + it('detaches a flight that vanished from AirTrail, keeping the TREK row', async () => { + withLinkedRow(2); + listFlights.mockResolvedValue([]); // the linked id is no longer there + const { changed } = await svc.runAirtrailSyncForUser(7); + expect(updateReservation).not.toHaveBeenCalled(); + expect(runSpy).toHaveBeenCalledWith(expect.stringContaining('sync_enabled = 0'), [5]); + expect(changed).toBe(1); + }); + + it('leaves a disconnected owner alone rather than detaching their rows', async () => { + withLinkedRow(2); + getAirtrailCredentials.mockReturnValue(null); + const { changed } = await svc.runAirtrailSyncForUser(7); + expect(listFlights).not.toHaveBeenCalled(); + expect(runSpy).not.toHaveBeenCalled(); + expect(changed).toBe(0); + }); }); diff --git a/server/tests/unit/services/airtrailWriteback.test.ts b/server/tests/unit/services/airtrailWriteback.test.ts index 679f81566..41e8f754b 100644 --- a/server/tests/unit/services/airtrailWriteback.test.ts +++ b/server/tests/unit/services/airtrailWriteback.test.ts @@ -8,11 +8,21 @@ vi.mock('../../../src/utils/ssrfGuard', () => ({ import { db } from '../../../src/db/database'; import { createUser } from '../../helpers/factories'; -import { - getConnectionSettings, - isAirtrailWriteEnabled, - saveSettings, -} from '../../../src/services/airtrail/airtrailService'; +import { AirtrailService } from '../../../src/nest/integrations/airtrail.service'; +import { AirtrailClient } from '../../../src/nest/integrations/airtrail.client'; +import { DatabaseService } from '../../../src/nest/database/database.service'; +import { AuditService } from '../../../src/nest/database/../audit/audit.service'; + +// The free functions became methods with the airtrail fold; same SQL, same +// behaviour, one instance over the same db handle. +const svc = new AirtrailService( + new DatabaseService(db), + new AuditService(new DatabaseService(db)), + new AirtrailClient(), +); +const getConnectionSettings = svc.getConnectionSettings.bind(svc); +const isAirtrailWriteEnabled = svc.isAirtrailWriteEnabled.bind(svc); +const saveSettings = svc.saveSettings.bind(svc); describe('airtrail writeback opt-in persistence (#1240)', () => { it('defaults the writeback opt-in to off for a new user', () => { diff --git a/server/vitest.config.ts b/server/vitest.config.ts index ee1b9c7a3..4f8120252 100644 --- a/server/vitest.config.ts +++ b/server/vitest.config.ts @@ -86,7 +86,7 @@ export default defineConfig({ 'src/nest/files/**/*.ts': { statements: 97, branches: 95, functions: 99, lines: 98 }, 'src/nest/health/**/*.ts': { statements: 99, branches: 65, functions: 99, lines: 99 }, 'src/nest/help/**/*.ts': { statements: 81, branches: 70, functions: 99, lines: 86 }, - 'src/nest/integrations/**/*.ts': { statements: 19, branches: 0, functions: 10, lines: 19 }, + 'src/nest/integrations/**/*.ts': { statements: 69, branches: 52, functions: 72, lines: 71 }, 'src/nest/journey/**/*.ts': { statements: 90, branches: 84, functions: 83, lines: 91 }, 'src/nest/llm-parse/**/*.ts': { statements: 91, branches: 85, functions: 85, lines: 94 }, 'src/nest/maps/**/*.ts': { statements: 92, branches: 85, functions: 95, lines: 95 },