feat(api): add GET /api/v1/stats for dashboard widgets

Homepage's customapi widget and everything shaped like it want a handful
of numbers from one request; /api/v1/trips hands out the rows, but a
widget maps fields, it cannot aggregate a list.

The figures come from AtlasService.getTravelStats, the same call behind
the dashboard's passport card, rather than from a second count. Visited
countries carries years of rules — countries reached only by a flight,
layovers that do not count, countries hidden by hand — and a second
implementation would disagree with the card next to it within a release.

That is also why the controller sits in atlas/ and not in public-api/:
PublicApiModule stays a leaf, so the route comes to the data instead.
TravelStatsController next door already does this for
/api/auth/travel-stats. ApiTokenGuard is provided locally rather than
imported with PublicApiModule — @UseGuards instantiates a guard in the
declaring controller's module, so an export would still leave its
TokenService unresolvable here.

last_trip means the most recently started trip, not the most recently
created one, and is null while every trip is still ahead.

Closes #1367
This commit is contained in:
Maurice
2026-08-28 14:45:28 +02:00
committed by Maurice
parent 7cbd4e5c42
commit 5a7b8d75aa
11 changed files with 561 additions and 34 deletions
+15 -3
View File
@@ -7,6 +7,10 @@ import { PluginGuardsModule } from '../plugins/host/plugin-guards.module';
import { AtlasMcp } from './atlas.mcp';
import { AddonsModule } from '../addons/addons.module';
import { AuthModule } from '../auth/auth.module';
import { PublicStatsController } from './public-stats.controller';
import { ApiTokenGuard } from '../public-api/api-token.guard';
import { TokensModule } from '../tokens/tokens.module';
import { RateLimitModule } from '../common/rate-limit.module';
/**
* Atlas addon domain (L7 leaf module). Registered in AppModule. Exports
@@ -17,11 +21,19 @@ import { AuthModule } from '../auth/auth.module';
* TravelStatsController serves GET /api/auth/travel-stats. The path stays where
* the client expects it; the code sits here because getTravelStats reads Atlas
* data. See the comment in that file.
*
* PublicStatsController serves GET /api/v1/stats on the same reasoning, one prefix
* over: the public API's own module is deliberately a leaf and importing
* AtlasModule there would drag AuthModule and the storage registry into it, so the
* route comes to the data instead. ApiTokenGuard is listed as a provider rather
* than pulled in with PublicApiModule: @UseGuards instantiates a guard in the
* declaring controller's module, so exporting it from over there would still leave
* its TokenService unresolvable here. TokensModule is a leaf, so the edge is free.
*/
@Module({
imports: [AuthModule, PluginGuardsModule, AddonsModule],
controllers: [AtlasController, TravelStatsController],
providers: [AtlasService, AtlasMcp, AtlasRpc],
imports: [AuthModule, PluginGuardsModule, AddonsModule, TokensModule, RateLimitModule],
controllers: [AtlasController, TravelStatsController, PublicStatsController],
providers: [AtlasService, AtlasMcp, AtlasRpc, ApiTokenGuard],
exports: [AtlasService],
})
export class AtlasModule {}
+49
View File
@@ -925,6 +925,55 @@ export class AtlasService {
// 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 come from `place_regions`, Atlas's own cache, most-visited first.
* No fallback to `getCountryFromCoords` here on purpose: this answers a
* dashboard widget, and a point-in-polygon scan over 4MB of boundaries is too
* much to spend on a label. An unresolved trip reports an empty list, which the
* caller renders as "no country" rather than as a wrong one.
*/
lastTrip(userId: number): { title: string; start_date: string | null; end_date: string | null; countries: string[] } | null {
const trip = this.db.get<{ id: number; title: string; start_date: string | null; end_date: string | null }>(`
SELECT t.id, t.title, t.start_date, t.end_date
FROM trips t
LEFT JOIN trip_members tm ON t.id = tm.trip_id
WHERE (t.user_id = ? OR tm.user_id = ?)
AND COALESCE(t.start_date, t.end_date) IS NOT NULL
AND COALESCE(t.start_date, t.end_date) <= date('now')
ORDER BY COALESCE(t.end_date, t.start_date) DESC, t.id DESC
LIMIT 1
`, userId, userId);
if (!trip) return null;
const rows = this.db.all<{ country_code: string; places: number }>(`
SELECT pr.country_code, COUNT(DISTINCT p.id) AS places
FROM place_regions pr
JOIN places p ON p.id = pr.place_id
WHERE p.trip_id = ? AND pr.country_code IS NOT NULL
GROUP BY pr.country_code
ORDER BY places DESC, pr.country_code ASC
`, trip.id);
return {
title: trip.title,
start_date: trip.start_date,
end_date: trip.end_date,
countries: rows.map(r => r.country_code.toUpperCase()),
};
}
getTravelStats(userId: number) {
// The resolved region rides along so cityFromAddress can tell the city apart from
// the region sitting right above it in the same address (#1115).
@@ -0,0 +1,72 @@
import { Controller, Get, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import type { PublicApiStats } from '@trek/shared';
import { AtlasService } from './atlas.service';
import { ApiTokenGuard } from '../public-api/api-token.guard';
import { enforcePublicApiRateLimit, requireUserId } from '../public-api/public-api-request';
import { RateLimitService } from '../common/rate-limit.service';
/**
* GET /api/v1/stats — aggregate counts for a dashboard widget (#1367).
*
* Homepage's `customapi` widget and everything shaped like it want a handful of
* numbers from one request. `/api/v1/trips` already hands out the rows, but a
* widget cannot aggregate a list; it maps a field to a label.
*
* ── Why this controller sits in atlas/ and not in public-api/ ────────────────
*
* The figures come from `AtlasService.getTravelStats`, the same call behind the
* dashboard's passport card. That is deliberate and is the whole reason this is
* not a fresh count: "visited countries" carries years of accumulated rules —
* countries reached only by a flight (#1366), layovers that do not count as
* visited (#1486, #1535), countries the user hid by hand (#1490), bookings that
* belong to someone else on the trip (#1966). A second implementation would
* disagree with the card sitting next to it within a release.
*
* PublicApiModule is deliberately a leaf — its own docblock explains that pulling
* AtlasModule in would drag AuthModule and the storage registry behind it, and a
* read-only surface that cannot boot without half the application is one that
* breaks for reasons it has nothing to do with. So the route comes to the data
* instead. TravelStatsController next door already does exactly this for
* `/api/auth/travel-stats`, and for the same reason.
*
* What crosses the boundary is only the request handling: the guard and the shared
* rate-limit bucket, so an integration polling `/trips` and `/stats` spends one
* budget rather than two.
*/
@Controller('api/v1')
@UseGuards(ApiTokenGuard)
export class PublicStatsController {
constructor(
private readonly atlas: AtlasService,
private readonly rl: RateLimitService,
) {}
@Get('stats')
stats(@Req() req: Request): PublicApiStats {
enforcePublicApiRateLimit(this.rl, req);
const userId = requireUserId(req);
const travel = this.atlas.getTravelStats(userId);
const last = this.atlas.lastTrip(userId);
// Counts, not the arrays behind them. A consumer that wants the members asks
// /api/v1/trips; this endpoint exists for the one that wants a number.
return {
total_trips: travel.totalTrips,
total_countries: travel.countries.length,
total_cities: travel.cities.length,
total_places: travel.totalPlaces,
total_days: travel.totalDays,
total_distance_km: travel.totalDistanceKm,
last_trip: last && {
title: last.title,
start_date: last.start_date,
end_date: last.end_date,
// The list's head, so `country` and `countries[0]` can never disagree.
country: last.countries[0] ?? null,
countries: last.countries,
},
};
}
}
@@ -0,0 +1,46 @@
import { HttpException } from '@nestjs/common';
import type { Request } from 'express';
import type { RateLimitService } from '../common/rate-limit.service';
/**
* What every `/api/v1` route does with the incoming request, in one place because
* the surface is served by two controllers: the routes in this directory, and the
* stats route that lives in `atlas/` because that is where its data does.
*
* Sharing these is the point. One rate-limit bucket means an integration polling
* both surfaces spends a single budget rather than two, and one user-narrowing
* means a route cannot accidentally answer with a different idea of who is calling.
*/
/**
* Keyed by the caller rather than by IP: a self-hosted integration and its user's
* browser routinely share an address, and limiting by IP would let one starve the
* other. Generous — this is a sync surface, not a login form — but bounded, so a
* runaway poll degrades its own integration instead of the instance.
*/
export const PUBLIC_API_RATE_WINDOW_MS = 60_000;
export const PUBLIC_API_RATE_MAX_PER_MINUTE = 120;
/**
* Falls back to a constant key when a request somehow carries no user, so the
* limiter can never end up with one shared bucket for every anonymous caller.
*/
export function enforcePublicApiRateLimit(rl: RateLimitService, req: Request): void {
const key = `user:${req.user?.id ?? 'unknown'}`;
if (!rl.check('public-api', key, PUBLIC_API_RATE_MAX_PER_MINUTE, PUBLIC_API_RATE_WINDOW_MS, Date.now())) {
throw new HttpException({ error: 'Too many requests. Please slow down.' }, 429);
}
}
/**
* The guard has already resolved the user; this is the type narrowing plus a
* belt-and-braces check. If it ever throws, a route was mounted without the guard —
* a 401 is then the right answer, and a loud one.
*/
export function requireUserId(req: Request): number {
const id = req.user?.id;
if (typeof id !== 'number') {
throw new HttpException({ error: 'API token required', code: 'API_TOKEN_REQUIRED' }, 401);
}
return id;
}
@@ -10,8 +10,8 @@ import {
} from '@trek/shared';
import { ApiTokenGuard } from './api-token.guard';
import { PublicApiService } from './public-api.service';
import { enforcePublicApiRateLimit, requireUserId } from './public-api-request';
import { RateLimitService } from '../common/rate-limit.service';
import type { User } from '../../types';
/**
* `/api/v1` — the versioned, read-only surface for third-party integrations.
@@ -28,15 +28,10 @@ import type { User } from '../../types';
* yet, and a token that reads everything is a very different thing from one that
* can also delete a trip.
*
* Rate limited per token rather than per IP: a self-hosted integration and its
* user's browser routinely share an address, and limiting by IP would let one
* starve the other. The budget is generous — this is a sync surface, not a login
* form — but bounded, so a runaway poll degrades its own integration instead of
* the instance.
* Rate limited per caller rather than per IP — the budget lives in
* `public-api-request.ts`, because the stats route enforces the same one from
* `atlas/`.
*/
const RATE_WINDOW_MS = 60_000;
const RATE_MAX_PER_MINUTE = 120;
@Controller('api/v1')
@UseGuards(ApiTokenGuard)
export class PublicApiController {
@@ -45,16 +40,8 @@ export class PublicApiController {
private readonly rl: RateLimitService,
) {}
/**
* Keyed by token id, not by IP. Falls back to the user id when a token somehow
* carries none, so the limiter can never end up with a shared bucket.
*/
private limit(req: Request): void {
const user = req.user as User | undefined;
const key = `user:${user?.id ?? 'unknown'}`;
if (!this.rl.check('public-api', key, RATE_MAX_PER_MINUTE, RATE_WINDOW_MS, Date.now())) {
throw new HttpException({ error: 'Too many requests. Please slow down.' }, 429);
}
enforcePublicApiRateLimit(this.rl, req);
}
/** Every trip the token's owner can reach, without itineraries. */
@@ -100,19 +87,6 @@ export class PublicApiController {
}
}
/**
* The guard has already resolved the user; this is the type narrowing plus a
* belt-and-braces check. If it ever throws, a route was mounted without the guard —
* a 401 is then the right answer, and a loud one.
*/
function requireUserId(req: Request): number {
const id = req.user?.id;
if (typeof id !== 'number') {
throw new HttpException({ error: 'API token required', code: 'API_TOKEN_REQUIRED' }, 401);
}
return id;
}
/**
* Trip ids are integers. Anything else is rejected before it reaches a query —
* `parseInt` would happily turn "12abc" into 12, and a route that quietly accepts
@@ -18,6 +18,10 @@ import { RateLimitModule } from '../common/rate-limit.module';
* graph along: AtlasModule needs AuthModule, which boots the storage registry,
* which reads app_settings on init. A read-only surface that cannot start without
* half the application is one that breaks for reasons it has nothing to do with.
*
* That constraint is why `GET /api/v1/stats` is not declared here: its figures are
* AtlasService's, so the route lives in `atlas/` instead and provides this guard
* class itself. No module edge either way — which is the point.
*/
@Module({
imports: [TokensModule, TripMembershipModule, RateLimitModule],