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',
@@ -0,0 +1,82 @@
/**
* Unit tests for the globe Atlas MCP tools (atlas-globe.mcp.ts):
* list_atlas_flight_routes, list_atlas_badges and list_atlas_travellers, through
* a real MCP session on the booted container. They answer as the REST routes
* do, the admin switch for the travellers included.
*/
import { setAppSetting, setUserSetting } from '../../helpers/factories/settings';
import { makeUser } from '../../helpers/factories/users';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { resetDatabase } from '../../helpers/reset-database';
import { bootTestApp } from '../../helpers/test-app';
import { MikroORM } from '@mikro-orm/core';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
let orm: MikroORM;
beforeAll(async () => {
orm = (await bootTestApp()).get(MikroORM);
});
beforeEach(async () => {
await resetDatabase(orm);
delete process.env.DEMO_MODE;
});
afterAll(async () => {
await (await bootTestApp()).close();
});
async function withHarness(userId: number, fn: (h: McpHarness) => Promise<void>) {
const h = await createMcpHarness({ userId, withResources: false });
try {
await fn(h);
} finally {
await h.cleanup();
}
}
async function call(h: McpHarness, name: string, args: Record<string, unknown> = {}) {
return h.client.callTool({ name, arguments: args });
}
describe('flights, badges and travellers', () => {
it('ATGLOBE-MCP-010: list_atlas_flight_routes answers the empty flight map of a user without flights', async () => {
const { user } = await makeUser(orm);
await withHarness(user.id, async (h) => {
expect(parseToolResult(await call(h, 'list_atlas_flight_routes'))).toEqual({
routes: [],
airports: [],
totals: { flights: 0, km: 0, airports: 0, longestKm: 0 },
});
});
});
it('ATGLOBE-MCP-011: list_atlas_badges answers every badge with its progress', async () => {
const { user } = await makeUser(orm);
await withHarness(user.id, async (h) => {
const { badges } = parseToolResult(await call(h, 'list_atlas_badges')) as {
badges: Array<{ id: string; earned: boolean; current: number }>;
};
expect(badges.find((b) => b.id === 'countries-5')).toMatchObject({ earned: false, current: 0 });
});
});
it('ATGLOBE-MCP-012: list_atlas_travellers leaves out the hidden, and everybody while the admin switch is off', async () => {
const { user } = await makeUser(orm);
const { user: shown } = await makeUser(orm);
const { user: hiddenUser } = await makeUser(orm);
await setUserSetting(orm, hiddenUser.id, 'atlas_hidden', 'true');
await withHarness(user.id, async (h) => {
const on = parseToolResult(await call(h, 'list_atlas_travellers', { ids: [shown.id, hiddenUser.id] })) as {
people: Array<{ id: number }>;
};
expect(on.people.map((p) => p.id)).toEqual([shown.id]);
await setAppSetting(orm, 'atlas_compare_enabled', 'false');
expect(parseToolResult(await call(h, 'list_atlas_travellers', { ids: [shown.id] }))).toEqual({ people: [] });
const empty = await call(h, 'list_atlas_travellers', { ids: [] });
expect(empty.isError).toBe(true);
});
});
});
@@ -51,6 +51,7 @@ describe('the derived key lists', () => {
'webauthn_origins',
'places_provider',
'flight_live_enabled',
'atlas_compare_enabled',
'mail_ingest_enabled',
'mail_ingest_transport',
'mail_ingest_imap_host',
@@ -104,6 +105,7 @@ describe('the derived key lists', () => {
'places_enrich_enabled',
'place_shadow_enabled',
'oidc_auto_redirect',
'atlas_compare_enabled',
].sort(),
);
});
@@ -0,0 +1,51 @@
import { aggregateFlights, greatCircleKm } from '../../../src/nest/atlas/atlas-flights.service';
import { describe, expect, it } from 'vitest';
const FRA = { code: 'FRA', name: 'Frankfurt', lat: 50.033, lng: 8.57 };
const JFK = { code: 'JFK', name: 'New York JFK', lat: 40.641, lng: -73.778 };
const SFO = { code: 'SFO', name: 'San Francisco', lat: 37.621, lng: -122.379 };
function leg(reservation_id: number, a: typeof FRA, b: typeof FRA, date: string | null = null) {
return [
{ reservation_id, ...a, local_date: date },
{ reservation_id, ...b, local_date: null },
];
}
describe('atlas flight map', () => {
it('measures great circles in kilometres', () => {
expect(greatCircleKm(FRA, JFK)).toBeGreaterThan(6100);
expect(greatCircleKm(FRA, JFK)).toBeLessThan(6300);
expect(greatCircleKm(FRA, FRA)).toBe(0);
});
it('folds both directions of a route into one with a count and its dates', () => {
const r = aggregateFlights([
...leg(1, FRA, JFK, '2018-05-01'),
...leg(2, JFK, FRA, '2019-02-03'),
...leg(3, FRA, JFK, '2017-01-01'),
]);
expect(r.routes).toHaveLength(1);
expect(r.routes[0]).toMatchObject({ count: 3, firstDate: '2017-01-01', lastDate: '2019-02-03' });
expect(r.totals.flights).toBe(3);
expect(r.airports.find((a) => a.code === 'FRA')?.count).toBe(3);
});
it('makes one leg per consecutive pair inside a booking, never across bookings', () => {
const rows = [
{ reservation_id: 7, ...FRA, local_date: null },
{ reservation_id: 7, ...JFK, local_date: null },
{ reservation_id: 7, ...SFO, local_date: null },
{ reservation_id: 8, ...FRA, local_date: null },
];
const r = aggregateFlights(rows);
expect(r.totals.flights).toBe(2);
expect(r.routes.map((x) => `${x.a.code}-${x.b.code}`).sort()).toEqual(['FRA-JFK', 'JFK-SFO']);
expect(r.totals.longestKm).toBe(Math.round(greatCircleKm(FRA, JFK)));
});
it('skips a leg that lands where it started', () => {
expect(aggregateFlights(leg(1, FRA, FRA)).totals.flights).toBe(0);
});
});
@@ -0,0 +1,107 @@
/**
* AtlasPeopleService: who the Atlas comparison answers for. Everybody asked
* for is visible unless they hid themselves (`atlas_hidden`), nobody is while
* the admin has switched the comparison off (`atlas_compare_enabled`), and a
* traveller goes out with counts, codes and earned badges only. The caller's
* own badges (list_atlas_badges) come with the unearned ones and their progress.
*/
import { AtlasFlightsService } from '../../../src/nest/atlas/atlas-flights.service';
import { AtlasPeopleService } from '../../../src/nest/atlas/atlas-people.service';
import { AtlasService } from '../../../src/nest/atlas/atlas.service';
import { SettingsService } from '../../../src/nest/settings/settings.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let people: AtlasPeopleService;
const hidden = new Set<number>();
let compare: string | null = null;
const settings = {
getUserSettings: vi.fn(async (id: number) => (hidden.has(id) ? { atlas_hidden: true } : {})),
getAppSetting: vi.fn(async () => compare),
};
const FIVE = ['FR', 'DE', 'IT', 'ES', 'PT'];
const atlas = {
stats: vi.fn(async () => ({
countries: [
...FIVE.map((code, i) => ({ code, status: 'visited', firstVisit: `${2015 + i}-06-01` })),
{ code: 'JP', status: 'planned', firstVisit: null },
],
streak: 2,
})),
visitedRegions: vi.fn(async () => ({
regions: { FR: [{ code: 'FR-IDF', name: 'Île-de-France', status: 'visited' }] },
})),
bucketList: vi.fn(async () => [{ id: 1, visited_at: '2020-01-01' }]),
};
const flights = {
flights: vi.fn(async () => ({
routes: [],
airports: [],
totals: { flights: 2, km: 1800, airports: 2, longestKm: 900 },
})),
};
beforeAll(async () => {
t = await createTestModule({
db,
imports: [],
providers: [
AtlasPeopleService,
{ provide: SettingsService, useValue: settings },
{ provide: AtlasService, useValue: atlas },
{ provide: AtlasFlightsService, useValue: flights },
],
});
people = t.get(AtlasPeopleService);
});
beforeEach(() => {
hidden.clear();
compare = null;
vi.clearAllMocks();
});
afterAll(async () => {
await t.close();
db.close();
});
describe('AtlasPeopleService', () => {
it('ATPEOPLE-001: answers every traveller asked for once, with counts, visited codes and earned badges only', async () => {
const answer = await people.people([4, 5, 4]);
expect(answer.map((p) => p.id)).toEqual([4, 5]);
expect(answer[0]).toMatchObject({ countries: 5, continents: 1, regions: 1, flightKm: 1800, codes: FIVE });
expect(answer[0].badges.map((b) => b.id)).toEqual(expect.arrayContaining(['countries-5', 'wishes-1']));
expect(answer[0].badges.every((b) => !('earned' in b) && !('current' in b))).toBe(true);
});
it('ATPEOPLE-002: leaves out whoever hid themselves', async () => {
hidden.add(5);
expect((await people.people([4, 5])).map((p) => p.id)).toEqual([4]);
expect(await people.isHidden(5)).toBe(true);
expect(await people.isHidden(4)).toBe(false);
});
it('ATPEOPLE-003: answers nobody while the admin switch is off, without reading anybody', async () => {
compare = 'false';
expect(await people.people([4, 5])).toEqual([]);
expect(atlas.stats).not.toHaveBeenCalled();
expect(settings.getAppSetting).toHaveBeenCalledWith('atlas_compare_enabled');
compare = 'true';
expect(await people.people([4])).toHaveLength(1);
});
it('ATPEOPLE-004: the own badges come earned and unearned, with their progress', async () => {
const badges = await people.badges(4);
const five = badges.find((b) => b.id === 'countries-5');
const ten = badges.find((b) => b.id === 'countries-10');
expect(five).toMatchObject({ earned: true, current: 5, target: 5, year: 2019 });
expect(ten).toMatchObject({ earned: false, current: 5, target: 10 });
});
});
@@ -1,3 +1,5 @@
import type { AtlasFlightsService } from '../../../src/nest/atlas/atlas-flights.service';
import type { AtlasPeopleService } from '../../../src/nest/atlas/atlas-people.service';
import type { AtlasWritesService } from '../../../src/nest/atlas/atlas-writes.service';
import { AtlasController } from '../../../src/nest/atlas/atlas.controller';
import { BucketItemExistsError } from '../../../src/nest/atlas/atlas.service';
@@ -15,7 +17,12 @@ const user = { id: 8 } as User;
/** The reads come from AtlasService, the writes from AtlasWritesService; one stub stands in for both. */
function makeController(svc: Partial<AtlasService> & Partial<AtlasWritesService>) {
return new AtlasController(svc as unknown as AtlasService, svc as unknown as AtlasWritesService);
return new AtlasController(
svc as unknown as AtlasService,
svc as unknown as AtlasWritesService,
svc as unknown as AtlasFlightsService,
svc as unknown as AtlasPeopleService,
);
}
function makeRes() {
@@ -890,6 +890,15 @@ describe('getAppConfig', () => {
await set.run('true');
expect((await svc.getAppConfig(null)).place_shadow_enabled).toBe(true);
});
it('AUTH-DB-052h: atlas_compare_enabled is on until an admin stores false', async () => {
createUser(testDb);
expect((await svc.getAppConfig(null)).atlas_compare_enabled).toBe(true);
await appSetting('atlas_compare_enabled', 'false');
expect((await svc.getAppConfig(null)).atlas_compare_enabled).toBe(false);
await appSetting('atlas_compare_enabled', 'true');
expect((await svc.getAppConfig(null)).atlas_compare_enabled).toBe(true);
});
});
describe('demoLogin', () => {
+80
View File
@@ -0,0 +1,80 @@
import { computeBadges, crossesDateline, type BadgeInput } from './atlas-badges';
import { describe, expect, it } from 'vitest';
const base: BadgeInput = {
countries: [],
continents: [],
regions: [],
flights: { count: 0, km: 0, longestKm: 0, crossesDateline: false },
streak: 0,
wishesReached: 0,
};
const byId = (input: BadgeInput) => new Map(computeBadges(input).map((b) => [b.id, b]));
describe('atlas badges', () => {
it('counts countries up the steps with the year the step was reached', () => {
const countries = Array.from({ length: 12 }, (_, i) => ({ code: `C${i}`, year: 2010 + i }));
const b = byId({ ...base, countries });
expect(b.get('countries-1')).toMatchObject({ earned: true, year: 2010, country: 'C0' });
expect(b.get('countries-5')).toMatchObject({ earned: true, year: 2014, country: 'C4' });
expect(b.get('countries-10')).toMatchObject({ earned: true, year: 2019 });
expect(b.get('countries-25')).toMatchObject({ earned: false, current: 12, target: 25 });
});
it('needs six inhabited continents for the collector and Antarctica for all seven', () => {
const six = ['Europe', 'Asia', 'Africa', 'North America', 'South America', 'Oceania'];
expect(byId({ ...base, continents: six }).get('continents-6')?.earned).toBe(true);
expect(byId({ ...base, continents: six }).get('continents-7')?.earned).toBe(false);
expect(byId({ ...base, continents: [...six, 'Antarctica'] }).get('continents-7')?.earned).toBe(true);
});
it('gives a country badge for half and for all of its regions', () => {
const half = byId({ ...base, regions: [{ country: 'US', visited: 26, total: 50 }] });
expect(half.get('regions-half-US')?.earned).toBe(true);
expect(half.get('regions-all-US')).toBeUndefined();
expect(half.get('regions-next-US')).toMatchObject({ earned: false, current: 26, target: 50 });
const all = byId({ ...base, regions: [{ country: 'US', visited: 50, total: 50 }] });
expect(all.get('regions-all-US')?.earned).toBe(true);
// A country with fewer than five regions never has one.
expect(byId({ ...base, regions: [{ country: 'LU', visited: 3, total: 3 }] }).get('regions-all-LU')).toBeUndefined();
});
it('measures flights against the Earth and the Moon', () => {
const b = byId({ ...base, flights: { count: 30, km: 50000, longestKm: 9500, crossesDateline: true } });
expect(b.get('flights-earth')?.earned).toBe(true);
expect(b.get('flights-moon')).toMatchObject({ earned: false, current: 50000 });
expect(b.get('flights-10')?.earned).toBe(true);
expect(b.get('flights-50')).toMatchObject({ earned: false, current: 30 });
expect(b.get('flights-longhaul')?.earned).toBe(true);
expect(b.get('flights-dateline')?.earned).toBe(true);
});
it('shows every goal from the start and earns the equator south of it', () => {
const b = byId(base);
for (const id of ['continents-7', 'flights-dateline', 'equator', 'polar']) {
expect(b.get(id)).toMatchObject({ earned: false });
expect(b.get(id)).not.toHaveProperty('secret');
}
const south = byId({ ...base, countries: [{ code: 'NZ' }] });
expect(south.get('equator')?.earned).toBe(true);
});
it('finds three new countries in one year', () => {
const countries = [2019, 2019, 2019, 2020].map((year, i) => ({ code: `X${i}`, year }));
expect(byId({ ...base, countries }).get('burst-3')).toMatchObject({ earned: true, year: 2019 });
});
it('gives every badge a category and a way to earn it', () => {
for (const b of computeBadges(base)) {
expect(b.category).toBeTruthy();
expect(b.descKey).toMatch(/^atlas\.badge\./);
}
});
it('crosses the date line only across 180 degrees', () => {
expect(crossesDateline(170, -170)).toBe(true);
expect(crossesDateline(10, 120)).toBe(false);
});
});
+610
View File
@@ -0,0 +1,610 @@
/**
* Atlas badges. Every badge is a rule over Atlas data the user already has
* (countries, regions, flights, years, wishes), so nothing is stored:
* remove a mark and the badge goes with it, add a rule and every user is judged
* by it at once. Server (profiles, assistant) and client (Passport) run this file.
*/
export type BadgeTier = 'bronze' | 'silver' | 'gold' | 'aurora';
export type BadgeCategory = 'countries' | 'continents' | 'regions' | 'flights' | 'explorer' | 'collector';
export const BADGE_CATEGORIES: BadgeCategory[] = [
'countries',
'continents',
'regions',
'flights',
'explorer',
'collector',
];
export type BadgeMotif =
| 'first'
| 'countries'
| 'continents'
| 'seven'
| 'region'
| 'earth'
| 'moon'
| 'flights'
| 'longhaul'
| 'airports'
| 'dateline'
| 'equator'
| 'hemispheres'
| 'tropics'
| 'polar'
| 'streak'
| 'burst'
| 'wish'
| 'islands';
export interface BadgeInput {
/** Visited countries by ISO A2, with the year of the first visit where known. */
countries: Array<{ code: string; year?: number | null }>;
/** Continent of each visited country (Antarctica counted as its own). */
continents: string[];
/** Regions per country: how many are visited and how many count. */
regions: Array<{ country: string; visited: number; total: number }>;
flights: { count: number; km: number; longestKm: number; crossesDateline: boolean; airports?: number };
/** Years in a row with a trip, as the Atlas stats report it. */
streak: number;
/** Wishes on the bucket list that were reached. */
wishesReached: number;
}
export interface Badge {
id: string;
category: BadgeCategory;
motif: BadgeMotif;
tier: BadgeTier;
/** Translation key of the title; params fill it. */
titleKey: string;
params?: Record<string, string | number>;
/** Translation key saying how the badge is earned; shares params. */
descKey: string;
earned: boolean;
current: number;
target: number;
/** Year the badge was reached, where the data says. */
year?: number | null;
/** The country that made it happen, where there is one (the n-th country, a region's country). */
country?: string | null;
}
const EARTH_KM = 40075;
const MOON_KM = 384400;
const ARCTIC = new Set(['IS', 'NO', 'SE', 'FI', 'GL', 'SJ', 'RU', 'CA', 'FO']);
const SOUTHERN = new Set([
'AU',
'NZ',
'ZA',
'AR',
'CL',
'BR',
'PE',
'BO',
'PY',
'UY',
'NA',
'BW',
'ZW',
'MZ',
'MG',
'AO',
'ZM',
'MW',
'TZ',
'ID',
'FJ',
'PG',
'MU',
'LS',
'SZ',
'RE',
'NC',
'PF',
'WS',
'TO',
'VU',
'SB',
'TL',
]);
/** Countries wholly or largely west of Greenwich, for the two hemispheres. */
const WESTERN = new Set([
'US',
'CA',
'MX',
'BR',
'AR',
'CL',
'PE',
'CO',
'EC',
'BO',
'PY',
'UY',
'VE',
'GY',
'SR',
'CR',
'PA',
'NI',
'HN',
'SV',
'GT',
'BZ',
'CU',
'JM',
'HT',
'DO',
'PR',
'BS',
'BB',
'TT',
'IS',
'PT',
'IE',
'MA',
'SN',
'GM',
'GN',
'SL',
'LR',
'CI',
'ML',
'MR',
'CV',
'GW',
'GL',
]);
const TROPICS = new Set([
'TH',
'VN',
'KH',
'LA',
'MY',
'SG',
'ID',
'PH',
'LK',
'MV',
'IN',
'BR',
'CO',
'EC',
'PE',
'VE',
'CR',
'PA',
'NI',
'HN',
'GT',
'BZ',
'CU',
'JM',
'DO',
'HT',
'BS',
'KE',
'TZ',
'UG',
'RW',
'ET',
'GH',
'NG',
'SN',
'CM',
'MG',
'MU',
'SC',
'FJ',
'PG',
'SB',
'VU',
'WS',
'TO',
'BB',
'TT',
'MX',
'AU',
'BO',
]);
const ISLANDS = new Set([
'IS',
'IE',
'GB',
'MT',
'CY',
'JP',
'PH',
'ID',
'LK',
'MV',
'MU',
'SC',
'MG',
'NZ',
'FJ',
'CU',
'JM',
'BS',
'BB',
'TT',
'DO',
'HT',
'TW',
'SG',
'BH',
'CV',
'ST',
'KM',
'WS',
'TO',
'VU',
'SB',
'PG',
'TL',
'BN',
'NR',
]);
const TIERS: BadgeTier[] = ['bronze', 'silver', 'gold'];
function steps(values: number[]): Array<{ target: number; tier: BadgeTier }> {
return values.map((target, i) => ({
target,
tier: i === values.length - 1 && values.length > 3 ? 'aurora' : TIERS[Math.min(i, 2)],
}));
}
/** The countries in the order they were first reached (unknown years last, by code). */
function byFirstVisit(countries: BadgeInput['countries']): BadgeInput['countries'] {
return [...countries].sort((a, b) => (a.year ?? 9999) - (b.year ?? 9999) || a.code.localeCompare(b.code));
}
function count(input: BadgeInput['countries'], set: Set<string>): number {
return input.filter((c) => set.has(c.code)).length;
}
export function computeBadges(input: BadgeInput): Badge[] {
const out: Badge[] = [];
const ordered = byFirstVisit(input.countries);
const n = ordered.length;
const push = (b: Omit<Badge, 'earned' | 'current'> & { current: number }) => {
out.push({ ...b, current: Math.min(b.current, b.target), earned: b.current >= b.target });
};
// ---- countries
push({
id: 'countries-1',
category: 'countries',
motif: 'first',
tier: 'bronze',
titleKey: 'atlas.badge.first',
descKey: 'atlas.badge.firstDesc',
current: n,
target: 1,
year: ordered[0]?.year ?? null,
country: ordered[0]?.code ?? null,
});
for (const { target, tier } of steps([5, 10, 25, 50, 75, 100, 150])) {
const nth = n >= target ? ordered[target - 1] : undefined;
push({
id: `countries-${target}`,
category: 'countries',
motif: 'countries',
tier,
titleKey: 'atlas.badge.countries',
params: { count: target },
descKey: 'atlas.badge.countriesDesc',
current: n,
target,
year: nth?.year ?? null,
country: nth?.code ?? null,
});
}
// ---- continents
const inhabited = new Set(input.continents.filter((c) => c !== 'Antarctica'));
for (const { target, tier } of steps([2, 3, 4, 5])) {
push({
id: `continents-${target}`,
category: 'continents',
motif: 'continents',
tier,
titleKey: 'atlas.badge.continentsN',
params: { count: target },
descKey: 'atlas.badge.continentsNDesc',
current: inhabited.size,
target,
});
}
push({
id: 'continents-6',
category: 'continents',
motif: 'continents',
tier: 'gold',
titleKey: 'atlas.badge.continents',
descKey: 'atlas.badge.continentsDesc',
current: inhabited.size,
target: 6,
});
const all = new Set(input.continents);
push({
id: 'continents-7',
category: 'continents',
motif: 'seven',
tier: 'aurora',
titleKey: 'atlas.badge.seven',
descKey: 'atlas.badge.sevenDesc',
current: all.size,
target: 7,
});
// ---- regions: one badge per country with five regions or more, plus totals
for (const r of input.regions) {
if (r.total < 5) continue;
const half = Math.ceil(r.total / 2);
if (r.visited >= r.total) {
push({
id: `regions-all-${r.country}`,
category: 'regions',
motif: 'region',
tier: 'aurora',
titleKey: 'atlas.badge.regionsAll',
params: { country: r.country },
descKey: 'atlas.badge.regionsAllDesc',
current: r.visited,
target: r.total,
country: r.country,
});
} else if (r.visited >= half) {
push({
id: `regions-half-${r.country}`,
category: 'regions',
motif: 'region',
tier: 'silver',
titleKey: 'atlas.badge.regionsHalf',
params: { country: r.country },
descKey: 'atlas.badge.regionsHalfDesc',
current: r.visited,
target: half,
country: r.country,
});
}
}
const best = [...input.regions]
.filter((r) => r.total >= 5 && r.visited < r.total)
.sort((a, b) => b.visited / b.total - a.visited / a.total)[0];
if (best) {
push({
id: `regions-next-${best.country}`,
category: 'regions',
motif: 'region',
tier: 'aurora',
titleKey: 'atlas.badge.regionsAll',
params: { country: best.country },
descKey: 'atlas.badge.regionsAllDesc',
current: best.visited,
target: best.total,
country: best.country,
});
}
const regionTotal = input.regions.reduce((s, r) => s + r.visited, 0);
for (const { target, tier } of steps([10, 50, 100])) {
push({
id: `regions-${target}`,
category: 'regions',
motif: 'region',
tier,
titleKey: 'atlas.badge.regionsN',
params: { count: target },
descKey: 'atlas.badge.regionsNDesc',
current: regionTotal,
target,
});
}
// ---- flights
const f = input.flights;
for (const { target, tier } of steps([1, 10, 50, 100])) {
push({
id: `flights-${target}`,
category: 'flights',
motif: 'flights',
tier,
titleKey: 'atlas.badge.flights',
params: { count: target },
descKey: 'atlas.badge.flightsDesc',
current: f.count,
target,
});
}
push({
id: 'flights-earth',
category: 'flights',
motif: 'earth',
tier: 'gold',
titleKey: 'atlas.badge.earth',
descKey: 'atlas.badge.earthDesc',
current: Math.round(f.km),
target: EARTH_KM,
});
push({
id: 'flights-earth-5',
category: 'flights',
motif: 'earth',
tier: 'gold',
titleKey: 'atlas.badge.earth5',
descKey: 'atlas.badge.earth5Desc',
current: Math.round(f.km),
target: EARTH_KM * 5,
});
push({
id: 'flights-moon',
category: 'flights',
motif: 'moon',
tier: 'aurora',
titleKey: 'atlas.badge.moon',
descKey: 'atlas.badge.moonDesc',
current: Math.round(f.km),
target: MOON_KM,
});
push({
id: 'flights-longhaul',
category: 'flights',
motif: 'longhaul',
tier: 'bronze',
titleKey: 'atlas.badge.longhaul',
descKey: 'atlas.badge.longhaulDesc',
current: Math.round(f.longestKm),
target: 9000,
});
push({
id: 'flights-ultra',
category: 'flights',
motif: 'longhaul',
tier: 'gold',
titleKey: 'atlas.badge.ultra',
descKey: 'atlas.badge.ultraDesc',
current: Math.round(f.longestKm),
target: 13000,
});
for (const { target, tier } of steps([10, 25])) {
push({
id: `airports-${target}`,
category: 'flights',
motif: 'airports',
tier,
titleKey: 'atlas.badge.airports',
params: { count: target },
descKey: 'atlas.badge.airportsDesc',
current: f.airports ?? 0,
target,
});
}
push({
id: 'flights-dateline',
category: 'flights',
motif: 'dateline',
tier: 'gold',
titleKey: 'atlas.badge.dateline',
descKey: 'atlas.badge.datelineDesc',
current: f.crossesDateline ? 1 : 0,
target: 1,
});
// ---- explorer
const south = count(input.countries, SOUTHERN);
push({
id: 'equator',
category: 'explorer',
motif: 'equator',
tier: 'silver',
titleKey: 'atlas.badge.equator',
descKey: 'atlas.badge.equatorDesc',
current: south ? 1 : 0,
target: 1,
});
const west = count(input.countries, WESTERN);
const both = west > 0 && n - west > 0 ? 1 : 0;
push({
id: 'hemispheres',
category: 'explorer',
motif: 'hemispheres',
tier: 'silver',
titleKey: 'atlas.badge.hemispheres',
descKey: 'atlas.badge.hemispheresDesc',
current: both,
target: 1,
});
push({
id: 'tropics',
category: 'explorer',
motif: 'tropics',
tier: 'bronze',
titleKey: 'atlas.badge.tropics',
descKey: 'atlas.badge.tropicsDesc',
current: count(input.countries, TROPICS) ? 1 : 0,
target: 1,
});
push({
id: 'polar',
category: 'explorer',
motif: 'polar',
tier: 'aurora',
titleKey: 'atlas.badge.polar',
descKey: 'atlas.badge.polarDesc',
current: count(input.countries, ARCTIC) ? 1 : 0,
target: 1,
});
const islands = count(input.countries, ISLANDS);
for (const { target, tier } of steps([5, 10])) {
push({
id: `islands-${target}`,
category: 'explorer',
motif: 'islands',
tier,
titleKey: 'atlas.badge.islands',
params: { count: target },
descKey: 'atlas.badge.islandsDesc',
current: islands,
target,
});
}
for (const { target, tier } of steps([3, 5, 10])) {
push({
id: `streak-${target}`,
category: 'explorer',
motif: 'streak',
tier,
titleKey: 'atlas.badge.streak',
params: { count: target },
descKey: 'atlas.badge.streakDesc',
current: input.streak,
target,
});
}
const perYear = new Map<number, number>();
for (const c of input.countries) if (typeof c.year === 'number') perYear.set(c.year, (perYear.get(c.year) ?? 0) + 1);
const bestYear = [...perYear.entries()].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0];
for (const { target, tier } of steps([3, 5])) {
const hit = !!bestYear && bestYear[1] >= target;
push({
id: `burst-${target}`,
category: 'explorer',
motif: 'burst',
tier,
titleKey: 'atlas.badge.burst',
params: { count: target },
descKey: 'atlas.badge.burstDesc',
current: bestYear?.[1] ?? 0,
target,
year: hit ? bestYear[0] : null,
});
}
// ---- collector
for (const { target, tier } of steps([1, 5, 10])) {
push({
id: `wishes-${target}`,
category: 'collector',
motif: 'wish',
tier,
titleKey: 'atlas.badge.wishes',
params: { count: target },
descKey: 'atlas.badge.wishesDesc',
current: input.wishesReached,
target,
});
}
return out;
}
/** Whether a great-circle leg between two longitudes crosses the antimeridian. */
export function crossesDateline(lng1: number, lng2: number): boolean {
return Math.abs(lng2 - lng1) > 180;
}
@@ -0,0 +1,40 @@
import {
atlasFlightsResponseSchema,
atlasPeopleResponseSchema,
atlasTravellersRequestSchema,
} from './atlas-globe.schema';
import { describe, expect, it } from 'vitest';
describe('atlas globe contract', () => {
it('asks for 1 to 200 travellers', () => {
expect(atlasTravellersRequestSchema.safeParse({ ids: [1, 2] }).success).toBe(true);
expect(atlasTravellersRequestSchema.safeParse({ ids: [] }).success).toBe(false);
expect(atlasTravellersRequestSchema.safeParse({ ids: Array.from({ length: 201 }, (_, i) => i + 1) }).success).toBe(
false,
);
});
it('describes the flights answer', () => {
const airport = { code: 'LIS', name: 'Lisbon', lat: 38.77, lng: -9.13 };
const flights = {
routes: [
{ a: airport, b: { ...airport, code: null }, count: 2, km: 1500, firstDate: '2024-05-01', lastDate: null },
],
airports: [{ ...airport, count: 2 }],
totals: { flights: 2, km: 3000, airports: 2, longestKm: 1500 },
};
expect(atlasFlightsResponseSchema.safeParse(flights).success).toBe(true);
expect(atlasFlightsResponseSchema.safeParse({ ...flights, totals: {} }).success).toBe(false);
});
it('describes the people answer', () => {
const badge = { id: 'countries-5', motif: 'globe', tier: 'bronze', titleKey: 'atlas.badge.countries', target: 5 };
const person = { id: 1, countries: 3, continents: 1, regions: 4, flightKm: 0, codes: ['PT'], badges: [badge] };
expect(atlasPeopleResponseSchema.safeParse({ people: [person] }).success).toBe(true);
expect(
atlasPeopleResponseSchema.safeParse({ people: [{ ...person, badges: [{ ...badge, tier: 'platinum' }] }] })
.success,
).toBe(false);
});
});
+59
View File
@@ -0,0 +1,59 @@
import { z } from 'zod';
/** Atlas globe contract: the flight map and the comparison with other travellers. */
const atlasAirportSchema = z.object({
code: z.string().nullable(),
name: z.string(),
lat: z.number(),
lng: z.number(),
});
/** GET /api/addons/atlas/flights — flown routes folded by airport pair. */
export const atlasFlightsResponseSchema = z.object({
routes: z.array(
z.object({
a: atlasAirportSchema,
b: atlasAirportSchema,
count: z.number(),
km: z.number(),
firstDate: z.string().nullable(),
lastDate: z.string().nullable(),
}),
),
airports: z.array(atlasAirportSchema.extend({ count: z.number() })),
totals: z.object({ flights: z.number(), km: z.number(), airports: z.number(), longestKm: z.number() }),
});
export type AtlasFlightsResponse = z.infer<typeof atlasFlightsResponseSchema>;
export const atlasBadgeSchema = z.object({
id: z.string(),
motif: z.string(),
tier: z.enum(['bronze', 'silver', 'gold', 'aurora']),
titleKey: z.string(),
params: z.record(z.string(), z.union([z.string(), z.number()])).optional(),
year: z.number().nullable().optional(),
target: z.number(),
});
/** GET /api/addons/atlas/people — the travellers asked for, minus whoever hid themselves. */
export const atlasPeopleResponseSchema = z.object({
people: z.array(
z.object({
id: z.number(),
countries: z.number(),
continents: z.number(),
regions: z.number(),
flightKm: z.number(),
codes: z.array(z.string()),
badges: z.array(atlasBadgeSchema),
}),
),
});
export type AtlasPeopleResponse = z.infer<typeof atlasPeopleResponseSchema>;
/** The travellers to compare with, by user id (the MCP twin of `GET /people?ids=`). */
export const atlasTravellersRequestSchema = z.object({
ids: z.array(z.number().int().positive()).min(1).max(200),
});
export type AtlasTravellersRequest = z.infer<typeof atlasTravellersRequestSchema>;
+2
View File
@@ -34,6 +34,8 @@ export * from './tag/trip-tag.schema';
export * from './notification/notification.schema';
export * from './memories/memories.schema';
export * from './atlas/atlas.schema';
export * from './atlas/atlas-badges';
export * from './atlas/atlas-globe.schema';
export * from './vacay/vacay.schema';
export * from './packing/packing.schema';
export * from './packing/packed-count';