mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 18:34:09 +00:00
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:
@@ -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', () => {
|
||||
|
||||
Reference in New Issue
Block a user