Files
TREK/server/tests/unit/db/entities-index.test.ts
T
Maurice bde2ad2ca8 feat(atlas): sum up the tours you have done, by period and type (STA-02)
With the Tours addon on, the Atlas panel gets a third tab, Tours, beside
Stats and Bucket List: what you have done on your tours across all your
trips. A period (all time, this year, the last 12 months or an earlier year)
and a tour type narrow it; the tab shows the distance large with the number
of tours at its corner, the ascent and descent, and the types with their
distance. "Show tours" opens every tour of the period in a dialog with the
same filters, the sums, the split by type and one row per tour.

What counts is said, never guessed. A tour counts once the day it is on is
over, with the values of the planning, badged "Planned" and explained as
not measured. A linked actual track (ACT-01) replaces those values for its
execution, badged "Recorded" and named, and is never added on top nor
counted as a tour of its own. A tour on several days counts once, a whole
route does not count beside the stages planned from it, a paddle tour sums
no heights, and a value nobody knows stays out of the sum, which then reads
"at least". Only the user's own part counts: a day names them among its
participants, or names nobody on a trip of their own; being able to open
somebody else's trip makes none of its tours theirs. Tours still ahead, on
no day or only on undated days are named as not counting. A tour that fell
through can be left out of the sums ("Leave out"): it stays in the plan
and in the list, dimmed, and "Count again" brings it back. Only the user's
own numbers change.

Server: GET /api/tours/activity-stats answers the user's activity entries
across every trip they can open, and PUT /api/tours/activity-stats/exclusions
leaves a tour out or counts it again (the tour must be in such a trip, else
404). A tour_activity_exclusions table keeps the exclusions per user and
tour. The sums are added up by a shared summary in @trek/shared, so the
Atlas and the assistant say the same numbers. MCP: get_tour_activity_stats
and set_tour_activity_excluded over the same service. The tab reads live
and needs a connection, like the rest of the Atlas statistics.
2026-10-20 15:23:55 +02:00

127 lines
6.1 KiB
TypeScript

import { ALL_ENTITIES } from '../../../src/db/entities';
import { TrekRepository } from '../../../src/db/repositories/_shared/trek-repository';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { EntitySchema, type EntityRepository } from '@mikro-orm/core';
import fs from 'node:fs';
import path from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
const ENTITIES_DIR = path.join(__dirname, '../../../src/db/entities');
const REPOSITORIES_DIR = path.join(__dirname, '../../../src/db/repositories');
describe('ALL_ENTITIES', () => {
it('ENT-001: lists exactly one schema per *.entity.ts file', () => {
const files = fs
.readdirSync(ENTITIES_DIR)
.filter((f) => f.endsWith('.entity.ts'))
.sort();
const names = ALL_ENTITIES.map((s) => s.name).sort();
const expected = files.map((f) => f.replace(/\.entity\.ts$/, '')).sort();
expect(names).toEqual(expected);
});
it('ENT-002: every entry is an EntitySchema with a class', () => {
for (const schema of ALL_ENTITIES) {
expect(schema).toBeInstanceOf(EntitySchema);
expect(typeof schema.meta.class).toBe('function');
}
});
/**
* Plan 2 Task 3: every one of the 135 entities the migrated schema
* describes (120 rewritten + the 5 document-sync tables added this task,
* + push_subscriptions and google_api_usage from legacy steps 245 and 254,
* + tour_types, tours and tour_waypoints from the Tours migration,
* + scheduler_leases from the cron lease migration
* + user_sessions, the session rows behind revocable session tokens
* + ferrata_tiles, the stored via ferrata grid cells
* + paddle_regions, paddle_features and tour_obstacle_reviews, the paddle obstacle data and decisions
* + trip_journal_links and trip_journal_link_members, the journal a trip shows and who it is open to
* + paddle_water_graphs and paddle_region_requests, a region's water network and the regions that wait for an admin
* + tour_station_visits, how far a city walk got on one of its days
* + tour_change_steps, the changes to a tour saved from a confirmed proposal
* + tour_activities, the recorded tracks assigned to a tour
* + tour_activity_exclusions, the tours a user left out of their own activity sums)
* is registered, and no two share a class name (a silent duplicate would
* shadow one of them in `orm.getMetadata()`, exactly the kind of drift
* `entity-schema-parity.test.ts` can't see — it iterates the metadata map,
* which de-duplicates by class name).
*/
it('ENT-003: exactly 146 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(146);
const names = ALL_ENTITIES.map((s) => s.meta.className);
expect(new Set(names).size).toBe(names.length);
});
/**
* Task 1's review flagged this binding as otherwise unpinned: dropping an
* entity's `repository: () => XRepository` mutation stayed green in every
* gate up to here (task-1-review.md, minor 1). `em.getRepository(X)` must
* return an instance of the exact repository class
* `src/db/repositories/<Name>.repository.ts` exports, for every entity —
* the 120 the generator wrote a stub for this task plus the 5 pre-existing,
* hand-written ones (`Days`, `DayNotes`, `Trips`, `BudgetCategoryOrder`,
* `VacayUserSettings`) it left untouched.
*/
describe('ENT-004: em.getRepository(X) is an instance of X.repository.ts', () => {
let t: TestOrm;
const testDb = createSnapshotTestDb();
beforeAll(async () => {
t = await createTestOrm(testDb);
});
afterAll(async () => {
await t.close();
testDb.close();
});
it('every entity resolves to its own repository class', async () => {
const failures: string[] = [];
for (const schema of ALL_ENTITIES) {
const className = schema.meta.className;
const repoFile = path.join(REPOSITORIES_DIR, `${className}.repository.ts`);
if (!fs.existsSync(repoFile)) {
failures.push(`${className}: no src/db/repositories/${className}.repository.ts file`);
continue;
}
const mod: Record<string, unknown> = await import(
/* @vite-ignore */ `../../../src/db/repositories/${className}.repository`
);
const RepoClass = mod[`${className}Repository`];
if (typeof RepoClass !== 'function') {
failures.push(`${className}: repository module has no exported ${className}Repository class`);
continue;
}
const repo: EntityRepository<object> = t.em.getRepository(schema.class as new () => object);
if (!(repo instanceof (RepoClass as abstract new (...args: never[]) => unknown))) {
failures.push(`${className}: em.getRepository() did not return a ${className}Repository instance`);
}
// Task 7 review, H2 carry-list item 1: the `extends EntityRepository`
// ratchet made self-enforcing — every bound repository must also be
// a TrekRepository (validateRequestContext + the disableIdentityMap
// read default), not just an instance of its own named class.
if (!(repo instanceof TrekRepository)) {
failures.push(`${className}: em.getRepository() did not return a TrekRepository instance`);
}
}
expect(failures).toEqual([]);
});
// Task 7 review, H2: a source-scan companion to the instanceof check
// above — belt and suspenders against a repository that extends
// TrekRepository indirectly (or not through this loop's import path).
it('SCAN-001: exactly one repository file extends EntityRepository directly — the base class itself', () => {
const files = fs.readdirSync(REPOSITORIES_DIR).filter((f) => f.endsWith('.repository.ts'));
const hits: string[] = [];
for (const file of files) {
const content = fs.readFileSync(path.join(REPOSITORIES_DIR, file), 'utf-8');
if (/\bextends\s+EntityRepository\b/.test(content)) hits.push(file);
}
expect(hits).toEqual([]); // the base class lives in _shared/, not matched by *.repository.ts
});
});
});