feat(atlas): flight routes, travellers and badges on the server

- GET /api/addons/atlas/flights folds the user's flight bookings into
  routes, airports and totals for the globe's arcs (#1369, #2642).
- GET /api/addons/atlas/people answers the Atlas side of other travellers
  on the instance: counts, visited countries and earned badges, never
  trips, places or dates. A user hides themselves with the atlas_hidden
  setting; the admin switch atlas_compare_enabled turns it off for all.
- shared/src/atlas/atlas-badges.ts holds the badge rules, computed from the
  data a user already has, so nothing is stored.
- MCP: list_atlas_flight_routes, list_atlas_badges, list_atlas_travellers.
This commit is contained in:
Maurice
2026-11-28 22:34:41 +01:00
parent 8510d4a729
commit 04d134755a
22 changed files with 1472 additions and 6 deletions
@@ -269,6 +269,37 @@ export class ReservationEndpointsRepository extends TrekRepository<ReservationEn
.execute();
}
/**
* The Atlas flight map: every endpoint of the user's own flight bookings with
* its airport and date, in leg order. Same ownership rule as
* {@link listOwnedFlightLegsForUser} (TRAVELER_OWNS), cancelled flights left out.
*/
async listOwnedFlightRoutesForUser(userId: number): Promise<
{
reservation_id: number;
sequence: number;
code: string | null;
name: string;
lat: number;
lng: number;
local_date: string | null;
}[]
> {
return await this.kysely<TravelerOwnedEndpointsWithTripsKyselyDB>()
.selectFrom('reservation_endpoints as re')
.innerJoin('reservations as r', 'r.id', 're.reservation_id')
.innerJoin('trips as t', 't.id', 'r.trip_id')
.leftJoin('trip_members as tm', (join) => join.onRef('tm.trip_id', '=', 't.id').on('tm.user_id', '=', userId))
.select(['re.reservation_id', 're.sequence', 're.code', 're.name', 're.lat', 're.lng', 're.local_date'])
.where((eb) => eb.or([eb('t.user_id', '=', userId), eb('tm.user_id', 'is not', null)]))
.where('r.type', '=', 'flight')
.where('r.status', '!=', 'cancelled')
.where((eb) => travelerOwnsExpr(eb, userId))
.orderBy('re.reservation_id', 'asc')
.orderBy('re.sequence', 'asc')
.execute();
}
/**
* RPL6 (`RoadtripPlanService.withTerminals`) — `SELECT e.reservation_id,
* e.role, e.sequence, e.name, e.code, e.lat, e.lng FROM
@@ -391,8 +391,9 @@ const CORE_TOOL_GROUPS: ToolGroups = {
controllers: ['VacayMcp', 'SchoolHolidaysMcp'],
},
atlas: {
about: 'Atlas: visited countries and regions, the bucket list, and both checked against the Dawarich recordings.',
controllers: ['AtlasMcp', 'DawarichAtlasMcp'],
about:
'Atlas: visited countries and regions, the bucket list, flights, badges and other travellers, and both checked against the Dawarich recordings.',
controllers: ['AtlasMcp', 'AtlasGlobeMcp', 'DawarichAtlasMcp'],
},
collections: {
about: 'Collections: saved places across trips, their labels and ratings.',
@@ -0,0 +1,113 @@
import { ReservationEndpoints } from '../../db/entities/ReservationEndpoints.entity';
import type { ReservationEndpointsRepository } from '../../db/repositories/ReservationEndpoints.repository';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
export interface AtlasFlightRoute {
/** Airports of the route, ordered alphabetically so A→B and B→A are one route. */
a: AtlasAirport;
b: AtlasAirport;
count: number;
km: number;
firstDate: string | null;
lastDate: string | null;
}
export interface AtlasAirport {
code: string | null;
name: string;
lat: number;
lng: number;
}
export interface AtlasFlights {
routes: AtlasFlightRoute[];
airports: Array<AtlasAirport & { count: number }>;
totals: { flights: number; km: number; airports: number; longestKm: number };
}
const EARTH_KM = 6371;
export function greatCircleKm(a: { lat: number; lng: number }, b: { lat: number; lng: number }): number {
const r = Math.PI / 180;
const dLat = (b.lat - a.lat) * r;
const dLng = (b.lng - a.lng) * r;
const h = Math.sin(dLat / 2) ** 2 + Math.cos(a.lat * r) * Math.cos(b.lat * r) * Math.sin(dLng / 2) ** 2;
return 2 * EARTH_KM * Math.asin(Math.min(1, Math.sqrt(h)));
}
function airportKey(p: AtlasAirport): string {
return p.code ? `c:${p.code.toUpperCase()}` : `p:${p.lat.toFixed(2)},${p.lng.toFixed(2)}`;
}
/**
* The flight map of the Atlas (#2642, #1369): the user's own flight bookings,
* each consecutive pair of endpoints one leg, legs between the same two airports
* folded into one route with a count. AirTrail imports land here too, since
* they arrive as flight reservations.
*/
@Injectable()
export class AtlasFlightsService {
constructor(@InjectRepository(ReservationEndpoints) private readonly endpoints: ReservationEndpointsRepository) {}
async flights(userId: number): Promise<AtlasFlights> {
const rows = await this.endpoints.listOwnedFlightRoutesForUser(userId);
return aggregateFlights(rows);
}
}
export function aggregateFlights(
rows: Array<{
reservation_id: number;
code: string | null;
name: string;
lat: number;
lng: number;
local_date: string | null;
}>,
): AtlasFlights {
const routes = new Map<string, AtlasFlightRoute>();
const airports = new Map<string, AtlasAirport & { count: number }>();
let flights = 0;
let km = 0;
let longestKm = 0;
for (let i = 1; i < rows.length; i++) {
const p = rows[i - 1];
const q = rows[i];
if (p.reservation_id !== q.reservation_id) continue;
if (!Number.isFinite(p.lat) || !Number.isFinite(q.lat)) continue;
const a: AtlasAirport = { code: p.code, name: p.name, lat: p.lat, lng: p.lng };
const b: AtlasAirport = { code: q.code, name: q.name, lat: q.lat, lng: q.lng };
const ka = airportKey(a);
const kb = airportKey(b);
if (ka === kb) continue;
const [first, second] = ka < kb ? [a, b] : [b, a];
const key = ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`;
const legKm = greatCircleKm(a, b);
const date = p.local_date ?? q.local_date ?? null;
const route = routes.get(key);
if (route) {
route.count++;
if (date && (!route.firstDate || date < route.firstDate)) route.firstDate = date;
if (date && (!route.lastDate || date > route.lastDate)) route.lastDate = date;
} else {
routes.set(key, { a: first, b: second, count: 1, km: Math.round(legKm), firstDate: date, lastDate: date });
}
for (const [k, ap] of [
[ka, a],
[kb, b],
] as const) {
const have = airports.get(k);
if (have) have.count++;
else airports.set(k, { ...ap, count: 1 });
}
flights++;
km += legKm;
longestKm = Math.max(longestKm, legKm);
}
return {
routes: [...routes.values()].sort((x, y) => y.count - x.count),
airports: [...airports.values()].sort((x, y) => y.count - x.count),
totals: { flights, km: Math.round(km), airports: airports.size, longestKm: Math.round(longestKm) },
};
}
+6
View File
@@ -593,6 +593,12 @@ function parseRegionFeatures(cc: string): RegionFeature[] {
return out;
}
/** A bundled admin-1 region's name by its ISO code (`DE-BY`), or null when the bundle has none. */
export function regionNameByCode(countryCode: string, regionCode: string): string | null {
const code = regionCode.toUpperCase();
return getRegionFeatures(countryCode).find((f) => f.code.toUpperCase() === code)?.name ?? null;
}
// Resolve (lat,lng) to a bundled admin1 region within the given country, smallest
// matching-part-first (mirroring getCountryFromCoords' candidate ranking) so a point near
// a shared border prefers the tighter-fitting candidate. Returns null when the country has
+68
View File
@@ -0,0 +1,68 @@
import { ADDON_IDS } from '../../addons';
import { McpController, Tool, type McpContext, TOOL_ANNOTATIONS_READONLY, ok } from '../../nest-mcp';
import { addonGate } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { AtlasFlightsService } from './atlas-flights.service';
import { AtlasPeopleService } from './atlas-people.service';
import { atlasTravellersRequestSchema } from '@trek/shared';
/** The whole Atlas MCP surface rides the atlas addon, like AtlasMcp. */
const atlasAddonOn = addonGate(ADDON_IDS.ATLAS);
const ATLAS_READ = { group: 'atlas', mode: 'read' } as const;
/**
* The globe Atlas on MCP: the flight map, the badges and the comparison with
* other travellers. Each tool is an adapter over the service its REST route
* calls (GET /flights, GET /people), with the fields taken from the same
* @trek/shared request schemas, so validation and refusals are the same.
*/
@McpController()
export class AtlasGlobeMcp {
constructor(
private readonly flights: AtlasFlightsService,
private readonly people: AtlasPeopleService,
readonly addons: AddonsService,
) {}
// ── Flights, badges, travellers ─────────────────────────────────────────
@Tool({
name: 'list_atlas_flight_routes',
description:
'Your flight map: every route you flew (both directions folded into one) with how often, its distance and first and last date, the airports with their visit counts, and the totals (flights, km, airports, longest flight).',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
when: atlasAddonOn,
access: ATLAS_READ,
})
async listAtlasFlightRoutes(_args: Record<string, never>, ctx: McpContext) {
return ok(await this.flights.flights(ctx.userId));
}
@Tool({
name: 'list_atlas_badges',
description:
'Your Atlas badges, earned or not, with progress (current of target), tier and, where known, the year one was reached. titleKey and params name the badge.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
when: atlasAddonOn,
access: ATLAS_READ,
})
async listAtlasBadges(_args: Record<string, never>, ctx: McpContext) {
return ok({ badges: await this.people.badges(ctx.userId) });
}
@Tool({
name: 'list_atlas_travellers',
description:
'Compare with other travellers of this instance, by user id: their visited-country, continent and region counts, flown km, visited country codes and earned badges. Whoever hid themselves from the comparison is left out, and nobody is answered while the admin has switched the comparison off.',
inputSchema: atlasTravellersRequestSchema.shape,
annotations: TOOL_ANNOTATIONS_READONLY,
when: atlasAddonOn,
access: ATLAS_READ,
})
async listAtlasTravellers({ ids }: { ids: number[] }) {
return ok({ people: await this.people.people(ids) });
}
}
@@ -0,0 +1,145 @@
import { SettingsService } from '../settings/settings.service';
import { AtlasFlightsService } from './atlas-flights.service';
import { AtlasService } from './atlas.service';
import { Injectable } from '@nestjs/common';
import { computeBadges, continentForCountry, crossesDateline, type Badge } from '@trek/shared';
import fs from 'node:fs';
import path from 'node:path';
/** The setting a user flips to leave the comparison; everyone else is visible. */
const ATLAS_HIDDEN_SETTING = 'atlas_hidden';
export const ATLAS_PEOPLE_MAX = 200;
export interface AtlasPerson {
id: number;
countries: number;
continents: number;
regions: number;
flightKm: number;
/** Visited countries by ISO A2, for laying one map over another. No trips, dates or places. */
codes: string[];
/** The badges this traveller has earned (same rules as the user's own Passport). */
badges: Array<Pick<Badge, 'id' | 'motif' | 'tier' | 'titleKey' | 'params' | 'year' | 'target'>>;
}
// __dirname is server/dist/nest/atlas at runtime and server/src/nest/atlas under vitest.
const MANIFEST = path.join(__dirname, '..', '..', '..', 'assets', 'atlas-mesh', 'manifest.json');
let regionTotals: Record<string, number> | null = null;
/** How many regions count for "x of n" per country, from the built globe manifest. */
function countedRegions(): Record<string, number> {
if (regionTotals) return regionTotals;
try {
const m = JSON.parse(fs.readFileSync(MANIFEST, 'utf8')) as { regions?: Record<string, { counted: number }> };
regionTotals = Object.fromEntries(Object.entries(m.regions ?? {}).map(([k, v]) => [k, v.counted]));
} catch {
regionTotals = {};
}
return regionTotals;
}
/**
* The travellers of an instance, as far as Atlas shows them: counts, the
* visited countries and the earned badges, never trips, places or dates.
* Everybody is visible unless they switched themselves off in the Atlas
* (`atlas_hidden`), and nobody is while the admin has switched the comparison
* off (`atlas_compare_enabled`). The directory of users itself is the app's existing one
* (/api/auth/users); this only answers for the ids it is asked about.
*/
@Injectable()
export class AtlasPeopleService {
constructor(
private readonly atlas: AtlasService,
private readonly flights: AtlasFlightsService,
private readonly settings: SettingsService,
) {}
async isHidden(userId: number): Promise<boolean> {
const s = await this.settings.getUserSettings(userId);
const v = s[ATLAS_HIDDEN_SETTING];
return v === true || v === 'true' || v === 1 || v === '1';
}
/** The admin switch `atlas_compare_enabled`: on until an admin stores 'false'. */
async compareEnabled(): Promise<boolean> {
return (await this.settings.getAppSetting('atlas_compare_enabled')) !== 'false';
}
async people(ids: number[]): Promise<AtlasPerson[]> {
if (!(await this.compareEnabled())) return [];
const out: AtlasPerson[] = [];
for (const id of [...new Set(ids)].slice(0, ATLAS_PEOPLE_MAX)) {
if (await this.isHidden(id)) continue;
out.push(await this.person(id));
}
return out;
}
/** Every badge of one user, earned or not, the way their Passport judges them. */
async badges(userId: number): Promise<Badge[]> {
return (await this.profile(userId)).badges;
}
private async person(id: number): Promise<AtlasPerson> {
const { person, badges } = await this.profile(id);
return {
...person,
badges: badges
.filter((b) => b.earned)
.map(({ id: bid, motif, tier, titleKey, params, year, target }) => ({
id: bid,
motif,
tier,
titleKey,
params,
year,
target,
})),
};
}
private async profile(id: number): Promise<{ person: Omit<AtlasPerson, 'badges'>; badges: Badge[] }> {
const stats = await this.atlas.stats(id);
const visited = (stats.countries as Array<{ code: string; status?: string; firstVisit?: string | null }>).filter(
(c) => (c.status ?? 'visited') === 'visited',
);
const codes = visited.map((c) => c.code);
const continents = codes.map((c) => continentForCountry(c)).filter((c): c is string => !!c);
const { regions } = await this.atlas.visitedRegions(id);
const totals = countedRegions();
let regionCount = 0;
const perCountry: Array<{ country: string; visited: number; total: number }> = [];
for (const [country, rows] of Object.entries(regions ?? {})) {
const n = rows.filter((r) => (r.status ?? 'visited') === 'visited').length;
regionCount += n;
perCountry.push({ country, visited: n, total: totals[country] ?? rows.length });
}
const fl = await this.flights.flights(id);
const bucket = await this.atlas.bucketList(id);
const badges = computeBadges({
countries: visited.map((c) => ({ code: c.code, year: c.firstVisit ? Number(c.firstVisit.slice(0, 4)) : null })),
continents,
regions: perCountry,
flights: {
count: fl.totals.flights,
km: fl.totals.km,
longestKm: fl.totals.longestKm,
crossesDateline: fl.routes.some((r) => crossesDateline(r.a.lng, r.b.lng)),
},
streak: Number((stats as { streak?: number }).streak ?? 0),
wishesReached: bucket.filter((b) => !!(b as { visited_at?: string | null }).visited_at).length,
});
return {
person: {
id,
countries: codes.length,
continents: new Set(continents).size,
regions: regionCount,
flightKm: fl.totals.km,
codes,
},
badges,
};
}
}
+29 -1
View File
@@ -1,9 +1,12 @@
import type { User } from '../../types';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { rowId } from '../common/row-id.pipe';
import { ZodValidationPipe } from '../common/zod-validation.pipe';
import { AtlasFlightsService } from './atlas-flights.service';
import { getRegionGeoGz, getRegionGeoJson } from './atlas-geo';
import { AtlasPeopleService, ATLAS_PEOPLE_MAX } from './atlas-people.service';
import { AtlasWritesService } from './atlas-writes.service';
import { AtlasMarkRegionDto, AtlasCreateBucketItemDto, AtlasUpdateBucketItemDto } from './atlas.dto';
import { AtlasService, BucketItemExistsError } from './atlas.service';
@@ -23,7 +26,7 @@ import {
Res,
UseGuards,
} from '@nestjs/common';
import { regionGeoParamsSchema } from '@trek/shared';
import { atlasFlightsResponseSchema, atlasPeopleResponseSchema, regionGeoParamsSchema } from '@trek/shared';
import type { AtlasLocateResponse, RegionGeoParams } from '@trek/shared';
import type { Response } from 'express';
@@ -52,8 +55,33 @@ export class AtlasController {
constructor(
private readonly atlas: AtlasService,
private readonly writes: AtlasWritesService,
private readonly flightMap: AtlasFlightsService,
private readonly peopleService: AtlasPeopleService,
) {}
/**
* Other travellers of this instance for the comparison and the ranking: counts and
* visited countries of the ids asked for, leaving out whoever hid themselves, and
* nobody while the admin has switched the comparison off (`atlas_compare_enabled`).
*/
@Get('people')
@ResponseContract(atlasPeopleResponseSchema)
async people(@Query('ids') ids: string | undefined) {
const list = String(ids ?? '')
.split(',')
.filter((x) => /^\d{1,10}$/.test(x))
.map(Number)
.slice(0, ATLAS_PEOPLE_MAX);
return { people: await this.peopleService.people(list) };
}
/** The flight map: the user's flown routes folded by airport pair (#2642). */
@Get('flights')
@ResponseContract(atlasFlightsResponseSchema)
async flights(@CurrentUser() user: User) {
return this.flightMap.flights(user.id);
}
@Get('stats')
async stats(@CurrentUser() user: User) {
return this.atlas.stats(user.id);
+20 -2
View File
@@ -14,7 +14,12 @@ import { RateLimitModule } from '../common/rate-limit.module';
import { ApiTokenGuard } from '../public-api/api-token.guard';
import { RealtimeModule } from '../realtime/realtime.module';
import { SchedulingModule } from '../scheduling/scheduling.module';
import { SettingsModule } from '../settings/settings.module';
import { TokensModule } from '../tokens/tokens.module';
import { AtlasFlightsService } from './atlas-flights.service';
import { AtlasGlobeMcp } from './atlas-globe.mcp';
import { AtlasMeshController } from './atlas-mesh.controller';
import { AtlasPeopleService } from './atlas-people.service';
import { AtlasWritesService } from './atlas-writes.service';
import { AtlasController } from './atlas.controller';
import { AtlasMcp } from './atlas.mcp';
@@ -57,10 +62,13 @@ import { Module } from '@nestjs/common';
* followed by `atlas:changed` to the user; it is exported for the Dawarich
* confirmations, which announce through it after their own commit. RealtimeModule
* is imported for it, so the module boots on its own (atlas.e2e) as in the app.
*
* AtlasGlobeMcp is the MCP twin of the flights, badges and travellers.
*/
@Module({
imports: [
PluginGuardsModule,
SettingsModule,
AddonsModule,
TokensModule,
RateLimitModule,
@@ -79,8 +87,18 @@ import { Module } from '@nestjs/common';
AppSettings,
]),
],
controllers: [AtlasController, TravelStatsController, PublicStatsController],
providers: [AtlasService, AtlasWritesService, AtlasMcp, AtlasRpc, ApiTokenGuard, PlaceRegionsRepairJob],
controllers: [AtlasController, AtlasMeshController, TravelStatsController, PublicStatsController],
providers: [
AtlasFlightsService,
AtlasGlobeMcp,
AtlasPeopleService,
AtlasService,
AtlasWritesService,
AtlasMcp,
AtlasRpc,
ApiTokenGuard,
PlaceRegionsRepairJob,
],
exports: [AtlasService, AtlasWritesService],
})
export class AtlasModule {}
+3
View File
@@ -338,6 +338,8 @@ export class AuthService {
// instance records what its users search for is something a visitor is
// entitled to know before logging in, not a detail to keep behind the door.
const placeShadowEnabled = settings.get('place_shadow_enabled') === 'true';
// The Atlas comparison of travellers; on until an admin stores 'false'.
const atlasCompareEnabled = settings.get('atlas_compare_enabled') !== 'false';
const setupComplete = userCount > 0 && (await this.usersRepo.findAdminNeedingPasswordChange()) === null;
return {
@@ -392,6 +394,7 @@ export class AuthService {
places_details_enabled: placesDetailsEnabled,
places_enrich_enabled: placesEnrichEnabled,
place_shadow_enabled: placeShadowEnabled,
atlas_compare_enabled: atlasCompareEnabled,
permissions: authenticatedUser ? (await this.permissions.getAllPermissions()) : undefined,
// Case-sensitive on purpose (legacy parity).
dev_mode: readEnv().app.nodeEnv === 'development',
@@ -99,6 +99,9 @@ export const APP_SETTINGS = {
places_provider: { schema: text, default: 'auto', adminForm: true, publicConfig: true, managedLocked: true },
// Live flight status from the keyless ADS-B feeds (flight-live). On by default; FLIGHT_LIVE_ENABLED wins over it.
flight_live_enabled: { schema: flag, default: 'true', env: (e) => e.integrations.flightLiveEnabled, adminForm: true },
// Whether the Atlas compares travellers of this instance (ranking, overlays). On by default;
// off, GET /api/addons/atlas/people answers nobody and the client hides the ranking.
atlas_compare_enabled: { schema: flag, default: 'true', adminForm: true, publicConfig: true },
// Read by name elsewhere.
oidc_issuer: { schema: text, default: null, env: (e) => e.oidc.issuer, publicConfig: true },
+1
View File
@@ -155,6 +155,7 @@ export const MANAGED_CUSTOMER_KEYS = [
'admin_webhook_url',
'allow_registration',
'allowed_file_types',
'atlas_compare_enabled',
'blur_booking_codes',
'dark_mode',
'default_currency',