The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
import { Injectable } from '@nestjs/common';
import { MikroORM } from '@mikro-orm/core';
import { InjectRepository } from '@mikro-orm/nestjs';
import { CONTINENT_MAP, strongerVisitStatus, todayUtc, tripVisitStatus, VisitStatus } from '@trek/shared';
import type { AtlasLocateResponse } from '@trek/shared';
import { UnitOfWork } from '../database/unit-of-work';
import { withRequestContext } from '../database/request-context';
import { BucketList } from '../../db/entities/BucketList.entity';
import type { BucketListRepository, BucketListRow } from '../../db/repositories/BucketList.repository';
import { HiddenCountries } from '../../db/entities/HiddenCountries.entity';
import type { HiddenCountriesRepository } from '../../db/repositories/HiddenCountries.repository';
import { HiddenRegions } from '../../db/entities/HiddenRegions.entity';
import type { HiddenRegionsRepository } from '../../db/repositories/HiddenRegions.repository';
import { VisitedCountries } from '../../db/entities/VisitedCountries.entity';
import type { VisitedCountriesRepository } from '../../db/repositories/VisitedCountries.repository';
import { VisitedRegions } from '../../db/entities/VisitedRegions.entity';
import type { VisitedRegionsRepository } from '../../db/repositories/VisitedRegions.repository';
import { PlaceRegions } from '../../db/entities/PlaceRegions.entity';
import type { PlaceRegionsRepository } from '../../db/repositories/PlaceRegions.repository';
import { Trips } from '../../db/entities/Trips.entity';
import type { TripsRepository, TripRawRow } from '../../db/repositories/Trips.repository';
import { Places } from '../../db/entities/Places.entity';
import type { PlacesRepository, PlaceRow } from '../../db/repositories/Places.repository';
import { ReservationEndpoints } from '../../db/entities/ReservationEndpoints.entity';
import type { ReservationEndpointsRepository, TravelerOwnedEndpointRow } from '../../db/repositories/ReservationEndpoints.repository';
import {
getCountryFromAddress,
getCountryFromCoords,
getCountryGeoFile,
getRegionFromCoords,
geocodingInFlight,
resolveCountryCodeSync,
resolveRegionFromBundle,
reverseGeocodeRegion,
} from './atlas-geo';
import type { RegionInfo } from './atlas-geo';
import { isCountryName } from './known-countries';
import { cityFromAddress } from './city-from-address';
import { transferEndpointIds } from './transfer-endpoints';
import { countryVisitDates } from './visit-dates';
import { placeCountryResolver } from './place-countries';
import { haversineKm } from '../common/geo';
import { CountryVisits, latestPerCoordinate } from './atlas-visit-order';
/** The part of a place that its cached region is derived from. */
type LocatedPlace = Pick<PlaceRow, 'id' | 'lat' | 'lng' | 'address'>;
/** A place_regions row next to the location of its place. */
type CachedRegionRow = LocatedPlace & { country_code: string; region_code: string };
/** How many cached rows the #2527 repair checks before it lets other work run. */
const REPAIR_YIELD_EVERY = 200;
/**
* Whole days from `today` to `isoDate`, both `YYYY-MM-DD` in UTC: the legacy
* `CAST(julianday(start_date) - julianday(date('now')) AS INTEGER)` (#2542),
* truncated toward zero the same way.
*/
function daysBetween(today: string, isoDate: string): number {
const from = Date.parse(`${today.slice(0, 10)}T00:00:00Z`);
const to = Date.parse(`${isoDate.slice(0, 10)}T00:00:00Z`);
return Math.trunc((to - from) / 86_400_000);
}
/**
* A reservation endpoint plus the two booking columns that decide whether it may
* take part in layover pairing at all (see transfer-endpoints.ts). Structurally
* identical to `ReservationEndpointsRepository`'s own `TravelerOwnedEndpointRow`
* (AT6/AT45's shared projection) — aliased locally so the rest of this file's
* `EndpointRow` references stay unchanged.
*/
type EndpointRow = TravelerOwnedEndpointRow;
export type CreateBucketData = {
name: string;
lat?: number | null;
lng?: number | null;
country_code?: string | null;
notes?: string | null;
target_date?: string | null;
region_code?: string | null;
};
export type UpdateBucketData = {
name?: string;
notes?: string;
lat?: number | null;
lng?: number | null;
country_code?: string | null;
target_date?: string | null;
};
/** The columns that decide whether two bucket-list rows are the same wish (#1898). */
type BucketIdentity = {
name: string;
lat: number | null;
lng: number | null;
country_code: string | null;
target_date: string | null;
};
// Bundled/geocoded region codes are always "<countryCode>-<rest>" (ISO 3166-2 format, and
// buildRegionInfo's synthesized fallback follows the same convention) — used to recover a
// region's country when there's no visited_regions row to read it from (a place-derived
// region was never inserted there).
function countryCodeFromRegionCode(regionCode: string): string {
return (regionCode.split('-')[0] || '').toUpperCase();
}
/**
* The same bucket-list wish, added twice (#1898). Deliberately a plain Error and
* not an HttpException: the service is shared with the MCP tools and the plugin
* RPC host, which shape their own errors — only atlas.controller.ts turns this
* into the 409.
*/
export class BucketItemExistsError extends Error {
constructor() {
super('Already on your bucket list');
this.name = 'BucketItemExistsError';
}
}
// An empty string and NULL are the same "not set" for a bucket item's country and
// target date, so they must not produce two different identities (#1898) — the
// bucket forms send '' where the map dialogs send null.
function blankToNull(value: string | null | undefined): string | null {
return value === undefined || value === null || value === '' ? null : value;
}
/**
* A wished-for region as stored (#1901): ISO 3166-2, upper case as the region
* boundaries carry it, and only when it lies in the item's own country. Anything
* else is no region, which keeps a caller that skips the contract (the plugin RPC)
* from pinning a wish to somebody else's map.
*/
export function bucketRegionCode(region: string | null | undefined, country: string | null): string | null {
const code = blankToNull(region)?.toUpperCase() ?? null;
if (!code || !country || !/^[A-Z]{2}-[A-Z0-9]{1,8}$/.test(code)) return null;
return code.startsWith(`${country.toUpperCase()}-`) ? code : null;
}
/**
* Who ticked a country off, for the detail sheet.
*
* Null when there is no row at all — a country derived from a trip's places was
* never marked by anyone, and reporting 'manual' for it would claim a decision
* nobody made. A row written before the column existed defaults to 'manual',
* which is exactly what it was.
*/
function markedSource(row: { source?: string | null } | undefined): string | null {
if (!row) return null;
return row.source || 'manual';
}
/**
* DI-native atlas domain service — the legacy services/atlasService SQL
* (stats aggregation, visited countries/regions with the #1490 tombstones,
* bucket-list CRUD) folded in verbatim, now through repositories
* (`db/repositories/{BucketList,HiddenCountries,HiddenRegions,
* VisitedCountries,VisitedRegions,PlaceRegions}.repository.ts` plus additive
* reads on `Trips`/`Places`/`ReservationEndpoints`, Plan 3f Task 1). The
* `TRAVELER_OWNS` fragment (#1966) is Task 0's shared
* `_shared/reservation-travelers-owns.ts` predicate, consumed (not
* re-derived) at its three call sites inside `ReservationEndpointsRepository`.
* The pure-geo machinery (bundled admin0/admin1 boundaries, point-in-polygon
* indexes, Nominatim geocoding and its caches) lives in ./atlas-geo — a plain
* module so the multi-MB caches stay process-global across the container
* instance and test helpers (#1576). The country lookup on the admin-0 borders sits in utils/country-borders.ts.
* Returns native service shapes; the client-facing contracts live in
* @trek/shared. Sends nothing itself: AtlasWritesService tells the user's tabs.
*/
@Injectable()
export class AtlasService {
constructor(
@InjectRepository(BucketList) private readonly bucketListRepo: BucketListRepository,
@InjectRepository(HiddenCountries) private readonly hiddenCountries: HiddenCountriesRepository,
@InjectRepository(HiddenRegions) private readonly hiddenRegions: HiddenRegionsRepository,
@InjectRepository(VisitedCountries) private readonly visitedCountries: VisitedCountriesRepository,
@InjectRepository(VisitedRegions) private readonly visitedRegionsRepo: VisitedRegionsRepository,
@InjectRepository(PlaceRegions) private readonly placeRegions: PlaceRegionsRepository,
@InjectRepository(Trips) private readonly trips: TripsRepository,
@InjectRepository(Places) private readonly places: PlacesRepository,
@InjectRepository(ReservationEndpoints) private readonly reservationEndpoints: ReservationEndpointsRepository,
private readonly uow: UnitOfWork,
private readonly orm: MikroORM,
) {}
// ── Shared query: all trips the user owns or is a member of ───────────────
private async getUserTrips(userId: number): Promise<TripRawRow[]> {
return this.trips.listOwnedOrMember(userId); // AT1
}
private async getPlacesForTrips(tripIds: number[]): Promise<PlaceRow[]> {
return this.places.listForTripIds(tripIds); // AT2
}
/**
* Trip id → whether that trip counts as visited, planned or a dateless idea (#1048).
* Everything country-shaped downstream takes its status from here, so the map, the
* counters and the country detail sheet can never disagree about the same trip.
*/
private tripStatusMap(trips: TripRawRow[], today: string): Map<number, VisitStatus> {
return new Map(trips.map((t) => [t.id, tripVisitStatus(t.start_date, t.end_date, today)]));
}
// ── Country resolution (batch DB cache + sync fallback + background geocoding) ──
private async resolvePlaceCountries(places: PlaceRow[]): Promise<Map<number, string>> {
const out = new Map<number, string>();
const geoPlaces = places.filter((p) => p.lat && p.lng);
const placeIds = geoPlaces.map((p) => p.id);
const cached = placeIds.length > 0 ? await this.placeRegions.listCountryCodesForPlaceIds(placeIds) : []; // AT3
const cachedMap = new Map(cached.map((r) => [r.place_id, r.country_code]));
const countryOf = placeCountryResolver();
const uncachedForGeocode: PlaceRow[] = [];
for (const p of places) {
const code = countryOf(p, cachedMap.get(p.id));
if (code) out.set(p.id, code);
else if (p.lat && p.lng && !geocodingInFlight.has(p.id)) uncachedForGeocode.push(p);
}
this.cacheRegionsInBackground(uncachedForGeocode); // AT4
return out;
}
/**
* Resolve each place's region in the background and cache it in place_regions.
*
* The loop outlives the Atlas request that started it, so it forks its own
* request context with `withRequestContext` instead of riding that request's
* `EntityManager` fork — the same shape the import-job runner
* (`ImportJobsService#start`) and the webhook nudge timer
* (`DocSyncWebhookController#schedule`) use for their detached chains.
*/
private cacheRegionsInBackground(places: PlaceRow[]): void {
if (places.length === 0) return;
for (const p of places) geocodingInFlight.add(p.id);
void withRequestContext(this.orm, async () => {
try {
for (const place of places) {
try {
const info = await reverseGeocodeRegion(place.lat!, place.lng!, place.address);
if (info) await this.cacheRegionWhileUnmoved(place, info);
} catch {
// individual failure, continue with the remaining places
} finally {
geocodingInFlight.delete(place.id);
}
}
} catch {
for (const p of places) geocodingInFlight.delete(p.id);
}
});
}
/**
* Cache a resolved region, but only while the place still sits where it was resolved
* from. A place moved while its lookup was running has already had its row dropped by
* the place_regions trigger (#2527), and writing the old answer back would pin it to
* the country it just left. A place deleted in the meantime is skipped the same way.
*/
private async cacheRegionWhileUnmoved(place: LocatedPlace, info: RegionInfo): Promise<boolean> {
return this.placeRegions.upsertRegionWhileUnmoved(place, info); // AT48
}
// ── One time repair of the rows cached before #2527 ───────────────────────
/**
* Before #2527 nothing dropped a place_regions row when its place moved, so an
* install that upgrades still holds the country every corrected place left. This
* re-derives each row with the bundled resolver alone, never Nominatim, and puts
* right the ones that no longer match where their place is now.
*
* Where the bundle answers for the place's current location with another country
* or region, the row gets that answer, which is what a fresh lookup would cache. A
* good row matches it, the address fallback case included.
*
* Where the bundle has no answer (a coastal point outside the simplified polygons,
* a country the bundle has no regions for), the row came from Nominatim and only
* Nominatim could judge it, so it stays, unless the coordinates put the place in
* another country and the address does not name the cached one either. Then it is
* dropped and the next Atlas load looks the place up again.
*
* A place without coordinates keeps no row, the same as the trigger does.
*
* Every write only lands while the place still holds the location it was read with,
* so a place edited while this runs keeps what the trigger and the next lookup give it.
*/
async repairStaleRegionCache(): Promise<{ replaced: number; dropped: number }> {
const rows: CachedRegionRow[] = await this.placeRegions.listWithPlaceLocation(); // AT49
let replaced = 0;
let dropped = 0;
for (const [i, row] of rows.entries()) {
// A big install holds many rows, so requests get a turn every so often.
if (i > 0 && i % REPAIR_YIELD_EVERY === 0) await new Promise((resolve) => setImmediate(resolve));
const fix = await this.staleRegionFix(row);
if (fix === 'drop') {
if (await this.dropRegionWhileUnmoved(row)) dropped++;
} else if (fix && (await this.cacheRegionWhileUnmoved(row, fix))) {
replaced++;
}
}
return { replaced, dropped };
}
/** What a cached row needs: a new region, 'drop', or null when it is right. */
private async staleRegionFix(row: CachedRegionRow): Promise<RegionInfo | 'drop' | null> {
if (row.lat == null || row.lng == null) return 'drop';
const cachedCountry = row.country_code.toUpperCase();
const fresh = await resolveRegionFromBundle(row.lat, row.lng, row.address);
if (fresh) {
const same = fresh.country_code.toUpperCase() === cachedCountry && fresh.region_code === row.region_code;
return same ? null : fresh;
}
const countryNow = resolveCountryCodeSync(row);
const contradicted = !!countryNow && countryNow !== cachedCountry && getCountryFromAddress(row.address) !== cachedCountry;
return contradicted ? 'drop' : null;
}
private async dropRegionWhileUnmoved(row: CachedRegionRow): Promise<boolean> {
return this.placeRegions.deleteRegionWhileUnmoved(row); // AT50
}
// ── Stats ─────────────────────────────────────────────────────────────────
async stats(userId: number) {
const trips = await this.getUserTrips(userId);
const tripIds = trips.map((t) => t.id);
if (tripIds.length === 0) {
const hiddenOnly = await this.getHiddenCountries(userId);
const manualCountryCodes = await this.visitedCountries.listCodesForUser(userId); // AT5
const countries = manualCountryCodes
.filter((code) => !hiddenOnly.has(code))
.map((code) => ({ code, placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null }));
return {
countries,
trips: [],
stats: { totalTrips: 0, totalPlaces: 0, totalCountries: countries.length, totalDays: 0 },
};
}
const places = await this.getPlacesForTrips(tripIds);
const now = todayUtc();
const tripStatus = this.tripStatusMap(trips, now);
interface CountryEntry {
code: string;
places: { id: number; name: string; lat: number | null; lng: number | null }[];
tripIds: Set<number>;
status: VisitStatus;
}
const placeCountries = await this.resolvePlaceCountries(places);
const countrySet = new Map<string, CountryEntry>();
for (const place of places) {
const code = placeCountries.get(place.id);
if (code) {
const status = tripStatus.get(place.trip_id) ?? 'idea';
const entry = countrySet.get(code);
if (entry) {
entry.status = strongerVisitStatus(entry.status, status);
} else {
countrySet.set(code, { code, places: [], tripIds: new Set(), status });
}
countrySet
.get(code)!
.places.push({ id: place.id, name: place.name, lat: place.lat ?? null, lng: place.lng ?? null });
countrySet.get(code)!.tripIds.add(place.trip_id);
}
}
let totalDays = 0;
for (const trip of trips) {
if (trip.start_date && trip.end_date) {
const start = new Date(trip.start_date);
const end = new Date(trip.end_date);
const diff = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1;
if (diff > 0) totalDays += diff;
}
}
// The dates are filled in at the end, once a manual mark or a booking has had its
// say on the status: they come only from the trips that match that final status.
const countries = [...countrySet.values()].map((c) => ({
code: c.code,
placeCount: c.places.length,
tripCount: c.tripIds.size,
firstVisit: null as string | null,
lastVisit: null as string | null,
status: c.status,
}));
// Places and cities come from the same count as the dashboard card and
// GET /api/v1/stats, so the three never show different totals (#3137).
const footprint = await this.placeFootprint(userId);
const totalCities = footprint.cities.length;
// Countries the user explicitly removed. Only the zero-count passes below are
// suppressed — a country with real places isn't removable in the UI anyway, and once
// the user adds a place there the tombstone should stop mattering (#1490).
const hidden = await this.getHiddenCountries(userId);
// Merge manually marked countries
const manualCountryCodes = await this.visitedCountries.listCodesForUser(userId); // AT7
for (const code of manualCountryCodes) {
if (hidden.has(code)) continue;
const existing = countries.find((c) => c.code === code);
if (existing) {
// Marking a country by hand is a statement of fact and outranks the dates of a
// trip that happens to go there later (#1048).
existing.status = 'visited';
} else {
countries.push({
code,
placeCount: 0,
tripCount: 0,
firstVisit: null,
lastVisit: null,
status: 'visited',
});
}
}
// Merge countries reached only by a transport booking. Those store geocoded from/to
// coordinates in reservation_endpoints but create no place row, so they never show up
// via resolvePlaceCountries above and would otherwise be missed (#1366).
// Only 'from'/'to' legs count as actually reached — a 'stop' is an intermediate
// connection/layover (e.g. a plane change) the traveler never really visited.
const endpointRows: EndpointRow[] = await this.reservationEndpoints.listOwnedEndpointsForTrips(tripIds, userId); // AT6, TRAVELER_OWNS (#1966)
// A layover the traveler never left is only marked 'stop' while both its legs sit in
// one booking. Split over two bookings it is a plain 'to' plus 'from' at the same
// airport, so it has to be recognised from the times instead (#1535). Only flights
// pair: a rental car picked up where a flight landed has its own from/to there and
// must keep contributing its country (#1366).
const transfers = transferEndpointIds(
endpointRows.filter((e) => e.reservation_type === 'flight' && e.reservation_status !== 'cancelled'),
);
const endpoints = endpointRows.filter((e) => !transfers.has(e.id));
// Collapse to one entry per coordinate before resolving countries —
// getCountryFromCoords is a point-in-polygon scan and used to run once per point.
const endpointStatus = new Map<string, { lat: number; lng: number; status: VisitStatus; tripIds: Set<number> }>();
for (const e of endpoints) {
const status = tripStatus.get(e.trip_id) ?? 'idea';
const key = `${e.lat},${e.lng}`;
const seen = endpointStatus.get(key);
if (seen) {
seen.status = strongerVisitStatus(seen.status, status);
seen.tripIds.add(e.trip_id);
} else endpointStatus.set(key, { lat: e.lat, lng: e.lng, status, tripIds: new Set([e.trip_id]) });
}
const bookingTripIds = new Map<string, Set<number>>();
for (const e of endpointStatus.values()) {
const code = getCountryFromCoords(e.lat, e.lng);
if (!code || hidden.has(code)) continue;
const existing = countries.find((c) => c.code === code);
if (existing) existing.status = strongerVisitStatus(existing.status, e.status);
else
countries.push({ code, placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null, status: e.status });
const ids = bookingTripIds.get(code) ?? new Set<number>();
for (const id of e.tripIds) ids.add(id);
bookingTripIds.set(code, ids);
}
// A booking can be what makes a country with places visited, so its trip dates the
// country as well. A country reached by bookings alone has no trip in its tooltip
// and stays without dates.
for (const c of countries) {
const fromPlaces = countrySet.get(c.code);
if (!fromPlaces) continue;
const fromBookings = bookingTripIds.get(c.code);
const dated = trips.filter((t) => fromPlaces.tripIds.has(t.id) || fromBookings?.has(t.id));
Object.assign(c, countryVisitDates(dated, c.status, now));
}
// Everything below counts actual visits only. countries[] still carries planned and
// dateless entries so the client can draw them once the user asks for them (#1048).
const visited = countries.filter((c) => c.status === 'visited');
const planned = countries.filter((c) => c.status === 'planned');
const mostVisited =
visited.length > 0 ? visited.reduce((a, b) => (a.placeCount > b.placeCount ? a : b), visited[0]) : null;
const continents: Record<string, number> = {};
visited.forEach((c) => {
const cont = CONTINENT_MAP[c.code] || 'Other';
continents[cont] = (continents[cont] || 0) + 1;
});
const continentsPlanned: Record<string, number> = {};
planned.forEach((c) => {
const cont = CONTINENT_MAP[c.code] || 'Other';
continentsPlanned[cont] = (continentsPlanned[cont] || 0) + 1;
});
const pastTrips = trips
.filter((t) => t.end_date && t.end_date <= now)
.sort((a, b) => b.end_date!.localeCompare(a.end_date!));
const lastTrip: {
id: number;
title: string;
start_date?: string | null;
end_date?: string | null;
countryCode?: string;
} | null = pastTrips[0]
? {
id: pastTrips[0].id,
title: pastTrips[0].title,
start_date: pastTrips[0].start_date,
end_date: pastTrips[0].end_date,
}
: null;
if (lastTrip) {
const lastTripPlaces = places.filter((p) => p.trip_id === lastTrip.id);
for (const p of lastTripPlaces) {
const code = resolveCountryCodeSync(p);
if (code) {
lastTrip.countryCode = code;
break;
}
}
}
const futureTrips = trips
.filter((t) => t.start_date && t.start_date > now)
.sort((a, b) => a.start_date!.localeCompare(b.start_date!));
const nextTrip: { id: number; title: string; start_date?: string | null; daysUntil?: number } | null = futureTrips[0]
? { id: futureTrips[0].id, title: futureTrips[0].title, start_date: futureTrips[0].start_date }
: null;
if (nextTrip) {
const diff = Math.ceil((new Date(nextTrip.start_date!).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24));
nextTrip.daysUntil = Math.max(0, diff);
}
const tripYears = new Set(trips.filter((t) => t.start_date).map((t) => Number.parseInt(t.start_date!.split('-')[0])));
let streak = 0;
const currentYear = new Date().getFullYear();
for (let y = currentYear; y >= 2000; y--) {
if (tripYears.has(y)) streak++;
else break;
}
const firstYear = tripYears.size > 0 ? Math.min(...tripYears) : null;
return {
countries,
stats: {
totalTrips: trips.length,
totalPlaces: footprint.totalPlaces,
totalCountries: visited.length,
totalCountriesPlanned: planned.length,
totalCountriesIdea: countries.length - visited.length - planned.length,
totalDays,
totalCities,
},
mostVisited,
continents,
continentsPlanned,
lastTrip,
nextTrip,
streak,
firstYear,
tripsThisYear: trips.filter((t) => t.start_date && t.start_date.startsWith(String(currentYear))).length,
};
}
// ── Country places ────────────────────────────────────────────────────────
async countryPlaces(userId: number, code: string) {
const trips = await this.getUserTrips(userId);
const tripIds = trips.map((t) => t.id);
if (tripIds.length === 0) {
// Post-fold quirk fix: the legacy early return hardcoded manually_marked
// false, so a trip-less user's manually marked country read as unmarked.
const row = await this.visitedCountries.findSource(userId, code); // AT8
const marked = !!row;
return {
places: [],
trips: [],
manually_marked: marked,
marked_source: markedSource(row),
status: marked ? 'visited' : 'idea',
};
}
const places = await this.getPlacesForTrips(tripIds);
const matchingPlaces: {
id: number;
name: string;
address: string | null;
lat: number | null;
lng: number | null;
trip_id: number;
}[] = [];
const matchingTripIds = new Set<number>();
for (const place of places) {
const pCode = resolveCountryCodeSync(place);
if (pCode === code) {
matchingPlaces.push({
id: place.id,
name: place.name,
address: place.address ?? null,
lat: place.lat ?? null,
lng: place.lng ?? null,
trip_id: place.trip_id,
});
matchingTripIds.add(place.trip_id);
}
}
const matchingTrips = trips
.filter((t) => matchingTripIds.has(t.id))
.map((t) => ({ id: t.id, title: t.title, start_date: t.start_date, end_date: t.end_date }));
const markRow = await this.visitedCountries.findSource(userId, code); // AT9
const isManuallyMarked = !!markRow;
// Take the status from the same trip classification stats() uses rather than deriving
// it again here — the detail sheet and the map must agree on what this country is.
const tripStatus = this.tripStatusMap(trips, todayUtc());
let status: VisitStatus = 'idea';
for (const id of matchingTripIds) status = strongerVisitStatus(status, tripStatus.get(id) ?? 'idea');
if (isManuallyMarked) status = 'visited';
return {
places: matchingPlaces,
trips: matchingTrips,
manually_marked: isManuallyMarked,
// Where the tick came from, so the sheet can say "confirmed from your
// Dawarich recordings" instead of implying the user typed it in. Null when
// the country is only derived from trips and carries no row at all.
marked_source: markedSource(markRow),
status,
};
}
// ── Mark / unmark country ─────────────────────────────────────────────────
async listVisitedCountries(userId: number): Promise<{ country_code: string; created_at: string | null; source: string }[]> {
return this.visitedCountries.listForUser(userId); // AT10
}
/** Countries the user explicitly removed, which stats() must not re-derive (#1490). */
async getHiddenCountries(userId: number): Promise<Set<string>> {
const codes = await this.hiddenCountries.listForUser(userId); // AT11
return new Set(codes);
}
/**
* `source` records who decided. It defaults to 'manual' because that is what
* every mark was until an integration could make one, and `INSERT OR IGNORE`
* means a country already ticked by hand keeps that provenance — confirming
* it again from a recording does not relabel somebody's own work as imported.
* Returns whether this actually added the country, so a caller reporting
* "3 countries added" is not counting the ones that were already there.
*/
async markCountry(userId: number, code: string, source: 'manual' | 'dawarich' = 'manual'): Promise<boolean> {
return await this.uow.transactional(async () => {
const inserted = await this.visitedCountries.markVisited(userId, code, source); // AT12
await this.visitedCountries.promoteFromRegion(userId, code, source); // #2597
// Marking it visited again lifts a previous removal.
await this.hiddenCountries.unhide(userId, code); // AT13
return inserted;
});
}
async unmarkCountry(userId: number, code: string): Promise<void> {
await this.uow.transactional(async () => {
await this.visitedCountries.unmark(userId, code); // AT14
await this.visitedRegionsRepo.unmarkAllInCountry(userId, code); // AT15
// A country derived from a place or a transport endpoint has no visited_countries row,
// so the deletes above are no-ops and stats() would re-derive it on the next request.
// Tombstone it so the removal actually sticks (#1490).
await this.hiddenCountries.hide(userId, code); // AT16
});
}
// ── Mark / unmark region ──────────────────────────────────────────────────
async listManuallyVisitedRegions(userId: number): Promise<{ region_code: string; region_name: string; country_code: string }[]> {
return this.visitedRegionsRepo.listForUser(userId); // AT21
}
/** Regions the user explicitly removed, which visitedRegions() must not re-derive. */
async getHiddenRegions(userId: number): Promise<Set<string>> {
const codes = await this.hiddenRegions.listForUser(userId); // AT22
return new Set(codes);
}
async markRegion(userId: number, code: string, name: string, countryCode: string): Promise<void> {
await this.uow.transactional(async () => {
await this.visitedRegionsRepo.markVisited(userId, code, name, countryCode); // AT17
// Re-marking lifts a previous removal of the region itself...
await this.hiddenRegions.unhide(userId, code); // AT18
// ...and of the parent country, which the "last region removed" cascade in
// unmarkRegion below may have hidden — otherwise marking a region visited again
// would leave its country invisible.
await this.visitedCountries.markFromRegion(userId, countryCode); // AT19
await this.hiddenCountries.unhide(userId, countryCode); // AT20
});
}
// True when the given country still has at least one region that would show as visited —
// derived from place_regions or manually marked — after excluding the given user's hidden
// regions. Used to decide whether removing a region should cascade into hiding the country.
private async hasVisibleRegionForCountry(userId: number, countryCode: string, hidden: Set<string>): Promise<boolean> {
const tripIds = (await this.getUserTrips(userId)).map((t) => t.id);
const placeIds = (await this.getPlacesForTrips(tripIds))
.filter((p) => p.lat && p.lng)
.map((p) => p.id);
const placeRegionCodes =
placeIds.length > 0 ? await this.placeRegions.listDistinctRegionCodesForCountryAndPlaces(countryCode, placeIds) : []; // AT23
const manualRegionCodes = await this.visitedRegionsRepo.listRegionCodesForCountry(userId, countryCode); // AT24
return [...placeRegionCodes, ...manualRegionCodes].some((code) => !hidden.has(code));
}
async unmarkRegion(userId: number, code: string): Promise<void> {
// One transaction across the delete, the tombstone and the country cascade —
// MikroORM turns the nested unmarkCountry() transaction into a savepoint.
await this.uow.transactional(async () => {
const countryCode = (await this.visitedRegionsRepo.findCountryCode(userId, code)) || countryCodeFromRegionCode(code); // AT25
await this.visitedRegionsRepo.unmark(userId, code); // AT26
// Tombstone unconditionally, not just for a manually-marked region — a region derived
// from real place data (the common case) needs to be dismissable too, mirroring
// unmarkCountry's tombstone for a place-derived country (#1490).
if (countryCode) {
await this.hiddenRegions.hide(userId, code, countryCode); // AT27
// If that was the country's last visible region, hide the country too, or it keeps showing
// "visited" with nothing left to drill into. One the user marked itself stays (#2597).
const ownMark = await this.visitedCountries.hasOwnMark(userId, countryCode);
const hidden = await this.getHiddenRegions(userId);
if (!ownMark && !(await this.hasVisibleRegionForCountry(userId, countryCode, hidden))) {
await this.unmarkCountry(userId, countryCode);
}
}
});
}
// ── Visited regions ───────────────────────────────────────────────────────
async visitedRegions(userId: number): Promise<{
regions: Record<
string,
{ code: string; name: string; placeCount: number; status: VisitStatus; manuallyMarked?: boolean }[]
>;
}> {
const trips = await this.getUserTrips(userId);
const tripIds = trips.map((t) => t.id);
const places = await this.getPlacesForTrips(tripIds);
// Regions carry the same status as their country, otherwise zooming into a merely
// planned country would reveal regions painted as visited (#1048).
const tripStatus = this.tripStatusMap(trips, todayUtc());
const placeTrip = new Map(places.map((p) => [p.id, p.trip_id]));
// Check DB cache first
const placeIds = places.filter((p) => p.lat && p.lng).map((p) => p.id);
const cached = placeIds.length > 0 ? await this.placeRegions.listForPlaceIds(placeIds) : []; // AT28
const cachedMap = new Map(cached.map((c) => [c.place_id, c]));
// Kick off background geocoding for uncached places; return cached data immediately.
this.cacheRegionsInBackground(
places.filter((p) => p.lat && p.lng && !cachedMap.has(p.id) && !geocodingInFlight.has(p.id)),
); // AT29
// Group by country → regions with place counts
const regionMap: Record<
string,
Map<string, { code: string; name: string; placeCount: number; status: VisitStatus }>
> = {};
for (const [placeId, entry] of cachedMap) {
const tripId = placeTrip.get(placeId);
const status = (tripId !== undefined ? tripStatus.get(tripId) : undefined) ?? 'idea';
if (!regionMap[entry.country_code]) regionMap[entry.country_code] = new Map();
const existing = regionMap[entry.country_code].get(entry.region_code);
if (existing) {
existing.placeCount++;
existing.status = strongerVisitStatus(existing.status, status);
} else {
regionMap[entry.country_code].set(entry.region_code, {
code: entry.region_code,
name: entry.region_name,
placeCount: 1,
status,
});
}
}
const result: Record<
string,
{ code: string; name: string; placeCount: number; status: VisitStatus; manuallyMarked?: boolean }[]
> = {};
for (const [country, regions] of Object.entries(regionMap)) {
result[country] = [...regions.values()];
}
// Merge manually marked regions
const manualRegions = await this.listManuallyVisitedRegions(userId);
for (const r of manualRegions) {
if (!result[r.country_code]) result[r.country_code] = [];
const existing = result[r.country_code].find((x) => x.code === r.region_code);
if (existing) {
existing.status = 'visited';
} else {
result[r.country_code].push({
code: r.region_code,
name: r.region_name,
placeCount: 0,
status: 'visited',
manuallyMarked: true,
});
}
}
// Suppress regions the user explicitly removed, same as stats() does for countries
// via getHiddenCountries (#1490) — otherwise a region derived fresh from place_regions
// (or a manual mark) on every request could never actually be dismissed.
const hidden = await this.getHiddenRegions(userId);
if (hidden.size > 0) {
for (const country of Object.keys(result)) {
result[country] = result[country].filter((r) => !hidden.has(r.code));
if (result[country].length === 0) delete result[country];
}
}
return { regions: result };
}
// ── Region GeoJSON / country geometry (delegates to the atlas-geo module) ──
/**
* Resolve a coordinate to the country and admin1 region the map draws (#1115), so
* searching for a city can highlight the region it sits in without the user knowing
* which one that is. Reads the same bundled polygons as the visited-region colouring,
* so the answer is always a feature the client can highlight. A country with no admin1
* coverage in the bundle resolves to a country and a null region, which is a real
* answer rather than a failure: zooming to the country is still what the user wanted.
*/
async locate(lat: number, lng: number): Promise<AtlasLocateResponse> {
const countryCode = getCountryFromCoords(lat, lng);
if (!countryCode) return { country_code: null, region_code: null, region_name: null };
const region = await getRegionFromCoords(countryCode, lat, lng);
return {
country_code: countryCode.toUpperCase(),
region_code: region?.region_code ?? null,
region_name: region?.region_name ?? null,
};
}
countryGeoFile(): string | null {
return getCountryGeoFile();
}
// ── Bucket list CRUD ──────────────────────────────────────────────────────
async bucketList(userId: number): Promise<BucketListRow[]> {
return this.bucketListRepo.listForUser(userId); // AT30
}
/**
* What makes two bucket-list rows the same wish (#1898): the same user, the
* same name (trimmed, case-insensitive) and the same country, target date and
* coordinates. The coordinates are part of it so two genuinely different
* places that share a name ("Altstadt") can sit side by side, and the target
* date is part of it because one entry per planned date is exactly what the
* report asks for. `IS` compares NULLs as equal, so "no coordinates" matches
* "no coordinates" instead of the NULL-is-never-equal SQLite default.
* `lower()` is ASCII-only in SQLite, which is what the client mirrors. See
* `BucketListRepository.findDuplicate`'s own docstring for how the NULL-safe
* match is reproduced without raw SQL.
*/
private async findDuplicateBucketItem(userId: number, key: BucketIdentity, excludeId?: number): Promise<number | null> {
return this.bucketListRepo.findDuplicate(userId, key, excludeId ?? null); // AT31
}
async createBucketItem(userId: number, data: CreateBucketData) {
const identity: BucketIdentity = {
name: data.name.trim(),
lat: data.lat ?? null,
lng: data.lng ?? null,
country_code: blankToNull(data.country_code),
target_date: blankToNull(data.target_date),
};
// #1898: the same wish must not stack up. A different target date (or a
// different place under the same name) is a different wish and still lands.
if (await this.findDuplicateBucketItem(userId, identity)) throw new BucketItemExistsError();
const id = await this.bucketListRepo.insertItem({
user_id: userId,
name: identity.name,
lat: identity.lat,
lng: identity.lng,
country_code: identity.country_code,
notes: data.notes ?? null,
target_date: identity.target_date,
region_code: bucketRegionCode(data.region_code, identity.country_code),
}); // AT32
return this.bucketListRepo.findById(id); // AT33
}
async updateBucketItem(userId: number, itemId: string | number, data: UpdateBucketData) {
const item = await this.bucketListRepo.findForUser(itemId, userId); // AT34
if (!item) return null;
// #1898: an edit must not land on top of another wish either — same guard as
// create, over the values the row will have once the UPDATE below ran. The
// row itself is excluded, so re-saving it unchanged stays a no-op.
const next: BucketIdentity = {
name: data.name?.trim() || item.name,
lat: data.lat !== undefined ? (data.lat ?? null) : item.lat,
lng: data.lng !== undefined ? (data.lng ?? null) : item.lng,
country_code: data.country_code !== undefined ? blankToNull(data.country_code) : blankToNull(item.country_code),
target_date: data.target_date !== undefined ? blankToNull(data.target_date) : blankToNull(item.target_date),
};
if (await this.findDuplicateBucketItem(userId, next, item.id)) throw new BucketItemExistsError();
// Post-fold quirk fixes: the value bindings use `?? null` (the legacy
// `|| null` wrote NULL for lat/lng 0 and empty-string notes), and the
// UPDATE + re-select are user-scoped (defense-in-depth; the ownership
// SELECT above stays the primary gate). The whitespace-only name no-op
// (`?.trim() || null` + COALESCE) is deliberate and preserved.
const trimmedName = data.name?.trim();
await this.bucketListRepo.update(itemId, userId, {
name: trimmedName ? [true, trimmedName] : [false, ''],
notes: [data.notes !== undefined, data.notes !== undefined ? (data.notes ?? null) : null],
lat: [data.lat !== undefined, data.lat !== undefined ? (data.lat ?? null) : null],
lng: [data.lng !== undefined, data.lng !== undefined ? (data.lng ?? null) : null],
country_code: [data.country_code !== undefined, data.country_code !== undefined ? next.country_code : null],
target_date: [data.target_date !== undefined, data.target_date !== undefined ? next.target_date : null],
}); // AT35
return this.bucketListRepo.findForUser(itemId, userId); // AT36
}
async deleteBucketItem(userId: number, itemId: string | number): Promise<boolean> {
const item = await this.bucketListRepo.findForUser(itemId, userId); // AT37
if (!item) return false;
// Post-fold quirk fix: user-scoped DELETE (defense-in-depth, see updateBucketItem).
await this.bucketListRepo.deleteForUser(itemId, userId); // AT38
return true;
}
// ---------------------------------------------------------------------------
// Travel stats
//
// Moved here from AuthService, which owned it only for historical reasons. It
// reads places/trips/visited_countries/place_regions and subtracts the same
// hidden countries the Atlas map hides, so every one of its data sources is
// already an Atlas concern. The move is what lets AuthModule drop its
// AtlasModule import: that edge was the reason atlas.mcp.ts had to reach
// AuthService through auth.bridge instead of injecting it.
//
// The route keeps its path (GET /api/auth/travel-stats) and is served by
// travel-stats.controller.ts in this directory.
// ---------------------------------------------------------------------------
/**
* The trip the user most recently took, with the countries it touched.
*
* Started, not created: a trip booked for next spring is not what anybody means
* by their last trip, so the same `<= date('now')` cut the visited-country query
* below uses applies here. All-future trips give null rather than a trip nobody
* has been on yet.
*
* Ordered by end date with the start date as fallback, and the id as a
* tie-break — two trips ending the same day is ordinary (a weekend away either
* side of a work trip), and without the second key which one is "last" would be
* whatever the storage engine happened to return first.
*
* Countries are resolved per place the way the Atlas map resolves them, most
* visited first. A trip none of whose places can be placed reports an empty
* list, which the caller renders as "no country" rather than as a wrong one.
*/
async lastTrip(userId: number): Promise<{ title: string; start_date: string | null; end_date: string | null; countries: string[] } | null> {
const trip = await this.trips.lastStartedTrip(userId, todayUtc()); // AT39
if (!trip) return null;
return {
title: trip.title,
start_date: trip.start_date,
end_date: trip.end_date,
countries: await this.tripCountries(trip.id),
};
}
/**
* The trip the user goes on next, the counterpart of lastTrip for a widget that
* counts down (#2542).
*
* Next means not started yet: a trip that is under way is still the last trip,
* so the two never name the same one. Only a trip with a start date qualifies,
* because a trip with only an end date has nothing to count down to. The days
* are counted against the same UTC `todayUtc()` lastTrip cuts on, so the switch
* from next to last happens at one moment for both fields.
*/
async nextTrip(userId: number): Promise<{ title: string; start_date: string; end_date: string | null; days_until: number; countries: string[] } | null> {
const today = todayUtc();
const trip = await this.trips.nextUpcomingTrip(userId, today); // AT47
if (!trip) return null;
return {
title: trip.title,
start_date: trip.start_date,
end_date: trip.end_date,
days_until: daysBetween(today, trip.start_date),
countries: await this.tripCountries(trip.id),
};
}
/** The countries a trip's places sit in, most-visited first, ties by code. */
private async tripCountries(tripId: number): Promise<string[]> {
const countryOf = placeCountryResolver();
const placesPerCountry = new Map<string, number>();
for (const place of await this.placeRegions.listPlaceCountriesForTrip(tripId)) { // AT40
const code = countryOf(place, place.country_code)?.toUpperCase();
if (code) placesPerCountry.set(code, (placesPerCountry.get(code) ?? 0) + 1);
}
return [...placesPerCountry]
.sort(([codeA, a], [codeB, b]) => b - a || (codeA < codeB ? -1 : 1))
.map(([code]) => code);
}
/**
* The places on every trip the user owns or is a member of, archived ones included,
* with the cities and coordinates derived from them. The one count behind the Atlas
* page, the dashboard card, GET /api/v1/stats and the MCP atlas tool (#3137).
*
* Every place counts once, even when two share an address and coordinates (the same
* hotel saved on two trips). A city is read with cityFromAddress, which skips the
* region named in the same address (#1115), and two spellings that differ only in
* case are one city; the first spelling seen is the one listed.
*/
private async placeFootprint(
userId: number,
): Promise<{ totalPlaces: number; cities: string[]; coords: { lat: number; lng: number }[] }> {
const places = await this.places.listAddressesForUser(userId); // AT41
const cities = new Map<string, string>();
const coords: { lat: number; lng: number }[] = [];
for (const p of places) {
// Explicit null checks: lat/lng of exactly 0 (equator / prime meridian)
// are valid coordinates a falsy check would drop.
if (p.lat != null && p.lng != null) coords.push({ lat: p.lat, lng: p.lng });
const city = cityFromAddress(p.address, isCountryName, p.region_name);
if (city && !cities.has(city.toLowerCase())) cities.set(city.toLowerCase(), city);
}
return { totalPlaces: places.length, cities: [...cities.values()], coords };
}
async getTravelStats(userId: number) {
const today = todayUtc();
const { totalPlaces, cities, coords } = await this.placeFootprint(userId);
// Archived trips still count here, matching the places, countries and flight
// distance widgets (which never filtered on is_archived) so the dashboard stats
// stay consistent — archiving a trip no longer zeroes out trips/days.
const tripStats = await this.trips.countTripsAndDaysForUser(userId); // AT42
// Visited countries: the ones the user marked by hand, plus the countries of
// their places, resolved the way the Atlas map resolves them (#2875). Each
// reached country keeps the last day of its latest trip, for the order.
const manualCountries = (await this.visitedCountries.listCodesForUser(userId)) // AT43
.filter(Boolean)
.map(code => code.toUpperCase());
const visits = new CountryVisits();
// Only trips that have already started count as visited — a country you have merely
// booked a trip to isn't stamped in the passport yet, and one you jotted down without
// any dates even less so (#1048). `today` is UTC, matching tripVisitStatus.
const countryOf = placeCountryResolver();
for (const place of await this.placeRegions.listStartedTripPlaceCountriesForUser(userId, today)) { // AT44
visits.note(countryOf(place, place.country_code), place.trip_last_date);
}
// Transport bookings don't create a place row, so their geocoded endpoints never
// reached place_regions — a country reached only by a flight/train (no lodging or
// planned place there) was never counted as visited (#1366). Resolve each endpoint
// coordinate to a country and fold it in too.
// Only 'from'/'to' legs count as actually reached — a 'stop' is an intermediate
// connection/layover (e.g. a plane change) the traveler never really visited (#1486),
// and the same layover split over two bookings is recognised from its ground time
// instead, because there it is stored as a legitimate 'to'/'from' pair (#1535).
const endpointRows = await this.reservationEndpoints.listOwnedEndpointsForUser(userId, today); // AT45, TRAVELER_OWNS (#1966)
const transfers = transferEndpointIds(
endpointRows.filter(e => e.reservation_type === 'flight' && e.reservation_status !== 'cancelled')
);
// The DISTINCT no longer collapses per coordinate now that the endpoint id has to be
// in the projection, so collapse here instead: getCountryFromCoords is a
// point-in-polygon scan and must stay at one run per coordinate. The latest
// trip through a coordinate is the one its country is dated by.
for (const e of latestPerCoordinate(endpointRows.filter(e => !transfers.has(e.id)))) {
visits.note(getCountryFromCoords(e.lat, e.lng), e.trip_last_date);
}
// Countries the user removed in Atlas stay removed on the dashboard too, so the
// passport card and the Atlas map agree (#1490).
const hidden = new Set([...(await this.getHiddenCountries(userId))].map(code => code.toUpperCase()));
return {
countries: visits.ordered(manualCountries).filter(code => !hidden.has(code)),
cities,
coords,
totalTrips: tripStats.trips || 0,
totalDays: tripStats.days || 0,
totalPlaces,
totalDistanceKm: await this.flightDistanceKm(userId),
};
}
/**
* Total flight distance a user has covered, summed across every non-cancelled
* flight reservation in their trips. Each flight stores its waypoints in
* reservation_endpoints (from → stops → to, ordered by sequence); the legs
* between consecutive points are added up so multi-stop flights count
* correctly.
*/
/**
* Whether a reservation counts toward one person's own travel figures.
*
* It does when they are named on it (#1517 assigns members and guests to
* bookings), and it does when nobody is named at all — an unassigned booking
* still belongs to the whole trip, which is what every reservation made
* before 4.0 looks like.
*
* That second half is what keeps this from being a breaking change: the
* assignment table is empty on any install upgrading from 3.4.1, and a plain
* join would have taken those users' flown distance to zero overnight. With
* no assignments anywhere the result is identical to before (#1966).
*
* Reproduced now by `_shared/reservation-travelers-owns.ts`'s
* `travelerOwnsExpr` (Plan 3f Task 0, R7), consumed by
* `ReservationEndpointsRepository`'s AT6/AT45/AT46 methods — not
* re-derived here.
*/
private async flightDistanceKm(userId: number): Promise<number> {
const rows = await this.reservationEndpoints.listOwnedFlightLegsForUser(userId); // AT46, TRAVELER_OWNS (#1966)
let total = 0;
let prev: { id: number; lat: number; lng: number } | null = null;
for (const point of rows) {
if (prev && prev.id === point.reservation_id) {
total += haversineKm(prev.lat, prev.lng, point.lat, point.lng);
}
prev = { id: point.reservation_id, lat: point.lat, lng: point.lng };
}
return Math.round(total);
}
}