Files
TREK/server/tests/unit/db/entities-index.test.ts
T
Maurice 52552133e3 feat(journey): comment on journal entries and follow a share link by email
The people on a journey can now talk about its entries, and a reader of its
share link can comment there too and follow the journey by email (#1702,

- journey_entry_comments holds a comment under an entry: by an account or
  signed with a name through the link, plain text up to 2000 characters. It
  goes with its entry and journey; a deleted account leaves it as unknown.
  Everyone on the journey reads and writes them, the author or an editor
  deletes one, an editor hides one from everyone but the editors.
- The share link gains allow_comments and allow_subscriptions (default 0,
  kept when a save leaves them out). Readers comment under the entries the
  link shows, behind the link's password gate, with a honeypot field and a
  limit per address and link. The public payload says what a reader may do.
- journey_share_subscribers holds an address following a link, with double
  opt-in: one mail asks to confirm it, nothing else is sent before. The mail
  links open app pages that post the token, so a scanner changes nothing.
  The owner lists and removes the addresses; they go with the link.
- A daily job (journey-digest) tells everyone on a journey about entries
  published since the last run (journey_entry_published, their settings
  apply, not about their own), mails each confirmed follower once a day in
  their language with an unsubscribe link and a List-Unsubscribe header, and
  forgets addresses unconfirmed for a week. journey_entries.announced marks
  what was told; existing published entries start as told.
- The owner hears about a new comment (journey_comment). Both events are
  translated in every locale, as are the follower mails.
- journey:entry:commented pings the journey's people; the journal page
  leaves it to the comments reader instead of reloading.
- MCP: list_journey_comments, set_journey_comment_hidden,
  delete_journey_comment, list_journey_subscribers, remove_journey_subscriber,
  and create_journey_share_link takes both switches like the REST route. The
  assistant is not offered the follower tools.
2026-11-30 16:56:15 +01:00

151 lines
8.0 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
* + collection_tours, the whole tours a collection keeps
* + tour_packing_links, the packing list or category a tour points at
* + tour_source_hints, what the wanderer watch found about a snapshot's source
* + journey_recorded_days, the recorded route a journey keeps per day
* + journey_entry_stays, the recorded stays a journey entry was taken over from
* + journey_recording_prep, how far preparing a journey's recorded days got for each person
* + tour_drafts, the Tours planner's unsaved draft per user and trip
* + ai_connections, the AI assistant's connections to a language model
* + assistant_threads, assistant_messages, assistant_tool_calls and assistant_usage,
* the trip assistant's conversations, the changes it proposed and what it used
* + trek_photo_signals, what a photo's pixels say, for picking photos for a book
* + journey_book_revisions, the books a whole-book design replaced, for its undo
* + trip_member_removals, who another member took off a trip, so its invite link refuses them
* + assistant_attachments, the files attached in the trip chat, kept with their conversation
* + mail_ingest_addresses, _prefs, _cursor, _messages and _candidates, the forwarded
* booking mails, the bookings read from them and the switches and addresses behind them
* + trip_addon_overrides, the owner's per-trip on or off for a trip addon
* + user_places, user_place_links, user_place_merges and user_place_merge_dismissals,
* a user's own place identities, the uses they group, the merges and the dismissed pairs
* + trip_collection_links, the lists a trip links
* + place_change_log, what changed in the details of a trip place or a saved place
* + place_activity_links, the bookings and tours a trip place or a saved place names
* + journey_entry_comments and journey_share_subscribers, the comments under a journey's
* entries and the addresses that follow its share link)
* 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 183 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(183);
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
});
});
});