refactor(days): days and day notes through repositories

This commit is contained in:
jubnl
2026-09-23 05:31:36 +02:00
parent d2e0d7e320
commit d7f5bc64c1
18 changed files with 1104 additions and 207 deletions
+28 -66
View File
@@ -1,10 +1,21 @@
/**
* Days + day-notes module e2e — exercises both migrated mounts through the real
* JwtAuthGuard against a temp SQLite db. DaysService and DayNotesService run
* their real SQL via DatabaseModule (the DATABASE_CONNECTION factory picks up
* the mocked db singleton); trip access resolves through a real-SQL
* canAccessTrip over the temp db. Only the permission check and the WebSocket
* broadcast stay mocked.
* JwtAuthGuard against a real migrated-and-seeded temp SQLite db
* (createSnapshotTestDb(), Plan 3c Task 2 — this used to hand-roll a dozen
* CREATE TABLEs, a second hand-maintained schema copy that omitted
* `roadtrip_day_tracks` and the rest of the entity graph `DaysRepository
* .listByTrip`'s ORM `find()` now needs to resolve at query time, the exact
* "e2e suites build their schema from hand-written partial DDL" risk the
* plan's inventory §15c flagged — `no such table: roadtrip_day_tracks` on
* this suite's very first `GET /api/trips/:id/days` was the failure that
* proved it). DaysService and DayNotesService now run through real
* repositories over the same migrated connection; trip access resolves
* through `TripsRepository.findAccessible` via the real request-scoped
* `EntityManager` `createTestMikroOrmModule` wires in, not a hand-rolled
* `canAccessTrip` mock (the legacy override this file used to export from
* `db/database.ts` — deleted there since Plan 3c Task 0b; a stale mock here
* would silently do nothing, not fail loudly, which is worse than removing
* it). Only the permission check and the WebSocket broadcast stay mocked.
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi, type MockInstance } from 'vitest';
import request from 'supertest';
@@ -13,70 +24,15 @@ import type { Server } from 'http';
import { DatabaseModule } from '../../src/nest/database/database.module';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { Test } from '@nestjs/testing';
import { seedUser, sessionCookie } from './harness';
import { sessionCookie } from './harness';
const { db } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const Database = require('better-sqlite3');
const tmp = new Database(':memory:');
tmp.exec('PRAGMA journal_mode = WAL');
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0,
avatar TEXT);`);
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, title TEXT, end_date TEXT, currency TEXT);');
tmp.exec('CREATE TABLE trip_members (trip_id INTEGER NOT NULL, user_id INTEGER NOT NULL);');
// The tables DaysService really queries (real SQL, no service mock).
tmp.exec(`CREATE TABLE days (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
day_number INTEGER, date TEXT, title TEXT, notes TEXT, default_transport_mode TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(trip_id, day_number));`);
tmp.exec('CREATE TABLE categories (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, color TEXT, icon TEXT);');
tmp.exec(`CREATE TABLE places (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL, name TEXT,
description TEXT, lat REAL, lng REAL, address TEXT, category_id INTEGER, price REAL, currency TEXT,
place_time TEXT, end_time TEXT, duration_minutes INTEGER, notes TEXT, image_url TEXT, transport_mode TEXT,
google_place_id TEXT, google_ftid TEXT, osm_id TEXT, amap_poi_id TEXT, website TEXT, phone TEXT, stop_type TEXT, fill_percent INTEGER);`);
tmp.exec(`CREATE TABLE day_assignments (id INTEGER PRIMARY KEY AUTOINCREMENT, day_id INTEGER NOT NULL,
place_id INTEGER NOT NULL, order_index INTEGER DEFAULT 0, notes TEXT,
assignment_time TEXT, assignment_end_time TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
tmp.exec('CREATE TABLE tags (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER, name TEXT, color TEXT);');
tmp.exec('CREATE TABLE place_tags (place_id INTEGER NOT NULL, tag_id INTEGER NOT NULL);');
tmp.exec(`CREATE TABLE assignment_participants (assignment_id INTEGER NOT NULL, user_id INTEGER NOT NULL,
PRIMARY KEY (assignment_id, user_id));`);
tmp.exec(`CREATE TABLE day_notes (id INTEGER PRIMARY KEY AUTOINCREMENT, day_id INTEGER NOT NULL,
trip_id INTEGER NOT NULL, text TEXT NOT NULL, time TEXT, icon TEXT DEFAULT '📝',
color TEXT, sort_order REAL DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
// Reorder/insert touch accommodations + reservation restamping.
tmp.exec(`CREATE TABLE day_accommodations (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
place_id INTEGER, start_day_id INTEGER, end_day_id INTEGER, check_in TEXT, check_in_end TEXT,
check_out TEXT, confirmation TEXT, notes TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
tmp.exec(`CREATE TABLE reservations (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER, title TEXT,
day_id INTEGER, end_day_id INTEGER, type TEXT, status TEXT DEFAULT 'pending', reservation_time TEXT,
reservation_end_time TEXT, location TEXT, confirmation_number TEXT, notes TEXT, accommodation_id TEXT,
metadata TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
tmp.exec(`CREATE TABLE reservation_endpoints (id INTEGER PRIMARY KEY AUTOINCREMENT, reservation_id INTEGER NOT NULL,
local_date TEXT);`);
// StorageRegistryService (behind StorageModule, now in this module chain) reads
// this at onModuleInit.
tmp.exec('CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);');
return { db: tmp };
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
return buildDbMock(createSnapshotTestDb());
});
vi.mock('../../src/db/database', () => ({
db,
// Real-SQL trip access over the temp db — DaysService.verifyTripAccess and
// DatabaseModule both read the mocked singleton.
canAccessTrip: (tripId: number | string, userId: number) =>
db.prepare(`
SELECT t.id, t.user_id FROM trips t
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
`).get(userId, tripId, userId),
isOwner: () => false,
getPlaceWithTags: () => null,
closeDb: () => {},
reinitialize: () => {},
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
import { db } from '../../src/db/database';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
// Since the permissions DI migration, the check is a spy on the container's
@@ -108,7 +64,13 @@ describe('Days + day-notes e2e (real auth guard + temp SQLite, real day SQL)', (
}
beforeAll(async () => {
seedUser(db as never, { id: 1 });
// harness.ts's seedUser() omits password_hash, which the real migrated
// schema requires NOT NULL (addons.e2e.test.ts/share.e2e.test.ts hit the
// same thing) — a raw insert here instead, matching the SeededUser shape
// id/role/password_version=0 that sessionCookie(1) needs.
db.prepare(
"INSERT INTO users (id, username, email, password_hash, role, password_version) VALUES (1, 'e2e-user', 'e2e@example.test', 'x', 'user', 0)",
).run();
db.prepare('INSERT INTO trips (id, user_id, title) VALUES (5, 1, ?)').run('Trip');
db.prepare('INSERT INTO days (id, trip_id, day_number) VALUES (3, 5, 1)').run();
app = await build();
+15 -2
View File
@@ -114,7 +114,10 @@ import { AirtrailImportService } from '../../src/nest/integrations/airtrail-impo
import { ReservationImportMcp } from '../../src/nest/reservation-import/reservation-import.mcp';
import { HelpMcp } from '../../src/nest/help/help.mcp';
import { AddonsMcp } from '../../src/nest/addons/addons.mcp';
import { createTestUnitOfWork, createTestAppSettingsRepo, createTestCategoriesRepo, createTestTagsRepo, createTestSettingsRepo } from './test-uow';
import {
createTestUnitOfWork, createTestAppSettingsRepo, createTestCategoriesRepo, createTestTagsRepo, createTestSettingsRepo,
createTestDaysRepo, createTestDayAssignmentsRepo, createTestDayNotesRepo, createTestTripsRepo,
} from './test-uow';
import { createTestOrm } from './test-orm';
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
@@ -170,7 +173,17 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
appSettings, usersRepo, inviteTokensRepo, mcpTokensRepoForAuth, oauthTokensRepo, webauthnCredentialsRepoForAuth, passwordResetTokensRepo,
);
const queryHelpersService = new QueryHelpersService(dbService);
const daysService = new DaysService(dbService, permissionsService, realtimeService, queryHelpersService, await createTestUnitOfWork(dbService.connection));
const daysService = new DaysService(
dbService,
permissionsService,
realtimeService,
queryHelpersService,
await createTestUnitOfWork(dbService.connection),
await createTestDaysRepo(dbService.connection),
await createTestDayAssignmentsRepo(dbService.connection),
await createTestDayNotesRepo(dbService.connection),
await createTestTripsRepo(dbService.connection),
);
const todoService = new TodoService(dbService, permissionsService, realtimeService, await createTestUnitOfWork(dbService.connection));
const packingService = new PackingService(dbService, permissionsService, realtimeService, notificationsStub(), await createTestUnitOfWork(dbService.connection));
const collabService = new CollabService(dbService, permissionsService, realtimeService, notificationsStub(), generalStorage, new RateLimitService(), await createTestUnitOfWork(dbService.connection));
+15 -2
View File
@@ -72,7 +72,10 @@ import { PlacePhotoCacheService } from '../../src/nest/place-photos/place-photo-
import { TrekPhotosRepository } from '../../src/nest/photos/trek-photos.repository';
import { RuntimeEnvService } from '../../src/nest/app-config/runtime-env.service';
import { makeStorageFixture } from './storage-fixture';
import { createTestUnitOfWork, createTestAppSettingsRepo, createTestCategoriesRepo, createTestTagsRepo, createTestSettingsRepo, sharedTestOrm } from './test-uow';
import {
createTestUnitOfWork, createTestAppSettingsRepo, createTestCategoriesRepo, createTestTagsRepo, createTestSettingsRepo, sharedTestOrm,
createTestDaysRepo, createTestDayAssignmentsRepo, createTestDayNotesRepo, createTestTripsRepo,
} from './test-uow';
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import { Users } from '../../src/db/entities/Users.entity';
@@ -102,7 +105,17 @@ export async function createPluginRpcHostFactory(dbs: DatabaseService): Promise<
const files = new FilesService(dbs, permissions, realtime, new EphemeralTokenService(), generalStorage, (await sharedTestOrm(dbs.connection)).em);
const collab = new CollabService(dbs, permissions, realtime, notificationsStub(), generalStorage, new RateLimitService(), await createTestUnitOfWork(dbs.connection));
const vacay = new VacayService(dbs, realtime, notificationsStub(), await createTestUnitOfWork(dbs.connection));
const days = new DaysService(dbs, permissions, realtime, queryHelpers, await createTestUnitOfWork(dbs.connection));
const days = new DaysService(
dbs,
permissions,
realtime,
queryHelpers,
await createTestUnitOfWork(dbs.connection),
await createTestDaysRepo(dbs.connection),
await createTestDayAssignmentsRepo(dbs.connection),
await createTestDayNotesRepo(dbs.connection),
await createTestTripsRepo(dbs.connection),
);
const photoCache = new PlacePhotoCacheService(dbs, makeStorageFixture('photos/google/').storage);
const unsplash = new UnsplashService(appSettings, usersRepo, new RuntimeEnvService(), generalStorage);
const journey = new JourneyDomainService(dbs, realtime, new TrekPhotosRepository(dbs), await createTestUnitOfWork(dbs.connection));
+44
View File
@@ -31,6 +31,12 @@ import type { TripMembersRepository } from '../../src/db/repositories/TripMember
import { Places } from '../../src/db/entities/Places.entity';
import type { PlacesRepository } from '../../src/db/repositories/Places.repository';
import { DatabaseService } from '../../src/nest/database/database.service';
import { Days } from '../../src/db/entities/Days.entity';
import type { DaysRepository } from '../../src/db/repositories/Days.repository';
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
import type { DayAssignmentsRepository } from '../../src/db/repositories/DayAssignments.repository';
import { DayNotes } from '../../src/db/entities/DayNotes.entity';
import type { DayNotesRepository } from '../../src/db/repositories/DayNotes.repository';
const perHandle = new WeakMap<Database.Database, Promise<UnitOfWork>>();
const appSettingsPerHandle = new WeakMap<Database.Database, Promise<AppSettingsRepository>>();
@@ -342,3 +348,41 @@ export async function createTestDatabaseService(db: Database.Database): Promise<
const t = await sharedTestOrm(db);
return new DatabaseService(db, t.em);
}
// ---------------------------------------------------------------------------
// Plan 3c Task 2 (`DaysService` + day notes onto `DaysRepository`/
// `DayAssignmentsRepository`/`DayNotesRepository`/`TripsRepository.setEndDate`)
// — appended at the end per the task's own file-ownership rule (append only).
// Same memoisation-per-handle pattern as every helper above.
// ---------------------------------------------------------------------------
const daysRepoPerHandle = new WeakMap<Database.Database, Promise<DaysRepository>>();
const dayAssignmentsRepoPerHandle = new WeakMap<Database.Database, Promise<DayAssignmentsRepository>>();
const dayNotesRepoPerHandle = new WeakMap<Database.Database, Promise<DayNotesRepository>>();
/** The `DaysRepository` a hand-constructed `DaysService` needs. */
export function createTestDaysRepo(db: Database.Database): Promise<DaysRepository> {
const existing = daysRepoPerHandle.get(db);
if (existing !== undefined) return existing;
const pending = sharedTestOrm(db).then((t) => t.repo(Days));
daysRepoPerHandle.set(db, pending);
return pending;
}
/** The `DayAssignmentsRepository` a hand-constructed `DaysService` needs. */
export function createTestDayAssignmentsRepo(db: Database.Database): Promise<DayAssignmentsRepository> {
const existing = dayAssignmentsRepoPerHandle.get(db);
if (existing !== undefined) return existing;
const pending = sharedTestOrm(db).then((t) => t.repo(DayAssignments));
dayAssignmentsRepoPerHandle.set(db, pending);
return pending;
}
/** The `DayNotesRepository` a hand-constructed `DaysService` needs (DY4). */
export function createTestDayNotesRepo(db: Database.Database): Promise<DayNotesRepository> {
const existing = dayNotesRepoPerHandle.get(db);
if (existing !== undefined) return existing;
const pending = sharedTestOrm(db).then((t) => t.repo(DayNotes));
dayNotesRepoPerHandle.set(db, pending);
return pending;
}
+15 -2
View File
@@ -25,11 +25,24 @@ import { PermissionsService } from '../../src/nest/permissions/permissions.servi
import { DaysService, DayReorderError } from '../../src/nest/days/days.service';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { QueryHelpersService } from '../../src/nest/query-helpers/query-helpers.service';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../helpers/test-uow';
import {
createTestUnitOfWork, createTestAppSettingsRepo,
createTestDaysRepo, createTestDayAssignmentsRepo, createTestDayNotesRepo, createTestTripsRepo,
} from '../helpers/test-uow';
let svc: DaysService;
beforeAll(async () => {
svc = new DaysService(new DatabaseService(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new RealtimeService(), new QueryHelpersService(new DatabaseService(testDb)), await createTestUnitOfWork(testDb));
svc = new DaysService(
new DatabaseService(testDb),
new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)),
new RealtimeService(),
new QueryHelpersService(new DatabaseService(testDb)),
await createTestUnitOfWork(testDb),
await createTestDaysRepo(testDb),
await createTestDayAssignmentsRepo(testDb),
await createTestDayNotesRepo(testDb),
await createTestTripsRepo(testDb),
);
});
const reorderDays = async (tripId: number, orderedIds: number[]) => await svc.reorder(tripId, orderedIds);
const insertDay = async (tripId: number, position?: number) => await svc.insert(tripId, position);
@@ -0,0 +1,266 @@
/**
* `DayAssignmentsRepository` (Plan 3c Task 2) — the DY1/DY3/AS1/AS3
* assignment-with-place projection contract (built here, Task 3 consumes it
* unchanged for AS1/AS3) plus DY24's `reanchorToDay` (a correlated scalar
* subquery in an UPDATE SET clause, via Kysely).
*/
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { createCategory, createDay, createDayAssignment, createPlace, createTrip, createUser } from '../../../helpers/factories';
import { DayAssignments } from '../../../../src/db/entities/DayAssignments.entity';
import type { DayAssignmentsRepository } from '../../../../src/db/repositories/DayAssignments.repository';
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
import { withRequestContext } from '../../../../src/nest/database/request-context';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let assignments: DayAssignmentsRepository;
let uow: UnitOfWork;
beforeAll(async () => {
t = await createTestOrm(testDb);
assignments = t.repo(DayAssignments);
uow = new UnitOfWork(t.em);
});
beforeEach(() => { resetTestDb(testDb); t.clear(); });
afterAll(async () => { await t.close(); testDb.close(); });
/** The DY1/DY3/AS1/AS3 statement, run raw — the parity oracle every assertion below is checked against. */
function legacyProjectionRow(id: number): unknown {
return testDb.prepare(`
SELECT da.*, p.id as place_id, p.name as place_name, p.description as place_description,
p.lat, p.lng, p.address, p.category_id, p.price, p.currency as place_currency,
COALESCE(da.assignment_time, p.place_time) as place_time,
COALESCE(da.assignment_end_time, p.end_time) as end_time,
p.duration_minutes, p.notes as place_notes,
p.image_url, p.transport_mode, p.google_place_id, p.google_ftid, p.osm_id, p.amap_poi_id, p.website, p.phone, p.stop_type, p.fill_percent,
c.name as category_name, c.color as category_color, c.icon as category_icon
FROM day_assignments da
JOIN places p ON da.place_id = p.id
LEFT JOIN categories c ON p.category_id = c.id
WHERE da.id = ?
`).get(id);
}
async function withQueryCount<T>(fn: () => Promise<T>): Promise<{ value: T; queries: number }> {
const connection = t.orm.em.getConnection();
const spy = vi.spyOn(connection, 'execute');
try {
const value = await fn();
return { value, queries: spy.mock.calls.length };
} finally {
spy.mockRestore();
}
}
describe('DayAssignmentsRepository — the DY1/DY3/AS1/AS3 projection', () => {
it('ASSIGNPLACEREPO-001: listForDay returns [] for a day with no assignments', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
expect(await assignments.listForDay(day.id)).toEqual([]);
});
it('ASSIGNPLACEREPO-002: listForDay is byte-identical to the legacy statement, column for column', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const category = createCategory(testDb, { name: 'Museum', color: '#111111', icon: '🏛️' });
const place = createPlace(testDb, trip.id, { name: 'Louvre', category_id: category.id });
const assignment = createDayAssignment(testDb, day.id, place.id);
const rows = await assignments.listForDay(day.id);
expect(rows).toHaveLength(1);
expect(rows[0]).toStrictEqual(legacyProjectionRow(assignment.id));
// Named spot-checks so a future field rename fails loudly here, not just via toStrictEqual.
expect(rows[0]).toMatchObject({
id: assignment.id, day_id: day.id, place_id: place.id,
place_name: 'Louvre', category_id: category.id,
category_name: 'Museum', category_color: '#111111', category_icon: '🏛️',
});
});
it('ASSIGNPLACEREPO-003: findWithPlaceAndCategory(id) is the same row, and null for a missing id', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id, { name: 'Eiffel Tower' });
const assignment = createDayAssignment(testDb, day.id, place.id);
expect(await assignments.findWithPlaceAndCategory(assignment.id)).toStrictEqual(legacyProjectionRow(assignment.id));
expect(await assignments.findWithPlaceAndCategory(999999)).toBeNull();
});
it('ASSIGNPLACEREPO-004: place_time/end_time COALESCE — the assignment\'s own time wins, the place\'s time is the fallback', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
testDb.prepare('UPDATE places SET place_time = ?, end_time = ? WHERE id = ?').run('09:00', '10:00', place.id);
const withOwnTime = createDayAssignment(testDb, day.id, place.id);
testDb.prepare('UPDATE day_assignments SET assignment_time = ?, assignment_end_time = ? WHERE id = ?').run('14:00', '15:00', withOwnTime.id);
const withoutOwnTime = createDayAssignment(testDb, day.id, place.id);
const rows = await assignments.listForDay(day.id);
const own = rows.find((r) => r.id === withOwnTime.id)!;
const fallback = rows.find((r) => r.id === withoutOwnTime.id)!;
expect(own.place_time).toBe('14:00');
expect(own.end_time).toBe('15:00');
expect(fallback.place_time).toBe('09:00');
expect(fallback.end_time).toBe('10:00');
});
it('ASSIGNPLACEREPO-005: category is null for an uncategorised place (LEFT JOIN, not INNER)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
testDb.prepare('UPDATE places SET category_id = NULL WHERE id = ?').run(place.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
const [row] = await assignments.listForDay(day.id);
expect(row.category_id).toBeNull();
expect(row.category_name).toBeNull();
expect(row.category_color).toBeNull();
expect(row.category_icon).toBeNull();
expect(row.id).toBe(assignment.id);
});
it('ASSIGNPLACEREPO-006: ORDER BY order_index ASC, created_at ASC', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const placeA = createPlace(testDb, trip.id, { name: 'Second' });
const placeB = createPlace(testDb, trip.id, { name: 'First' });
createDayAssignment(testDb, day.id, placeA.id, { order_index: 2 });
createDayAssignment(testDb, day.id, placeB.id, { order_index: 1 });
const rows = await assignments.listForDay(day.id);
expect(rows.map((r) => r.place_name)).toEqual(['First', 'Second']);
});
it('ASSIGNPLACEREPO-007: listWithPlaceAndCategory spans several days, in the same order; an empty array short-circuits with 0 queries', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const dayA = createDay(testDb, trip.id, { day_number: 1 });
const dayB = createDay(testDb, trip.id, { day_number: 2 });
const placeA = createPlace(testDb, trip.id, { name: 'A' });
const placeB = createPlace(testDb, trip.id, { name: 'B' });
const a = createDayAssignment(testDb, dayA.id, placeA.id);
const b = createDayAssignment(testDb, dayB.id, placeB.id);
const rows = await assignments.listWithPlaceAndCategory([dayA.id, dayB.id]);
expect(rows.map((r) => r.id).sort()).toEqual([a.id, b.id].sort());
const { value, queries } = await withQueryCount(() => assignments.listWithPlaceAndCategory([]));
expect(value).toEqual([]);
expect(queries).toBe(0);
});
// D-shape: every method here is a `qb().execute(..., false)` projection, which
// never hydrates an entity into the identity map by construction — proven
// anyway, the "not required, proven regardless" shape (AssignmentParticipants
// precedent).
it('ASSIGNPLACEREPO-008 (D-shape): a place rename after an unrelated identity-map read is visible in the FIRST wider projection', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id, { name: 'Old Name' });
const assignment = createDayAssignment(testDb, day.id, place.id);
await t.repo(DayAssignments).find({}); // populate the identity map with an unrelated read
testDb.prepare('UPDATE places SET name = ? WHERE id = ?').run('Renamed', place.id);
const [row] = await assignments.listForDay(day.id);
expect(row.place_name).toBe('Renamed');
expect(row.id).toBe(assignment.id);
});
});
describe('DayAssignmentsRepository.reanchorToDay (DY24, Kysely)', () => {
function setAccommodation(assignmentId: number, accId: number): void {
testDb.prepare('UPDATE day_assignments SET accommodation_id = ? WHERE id = ?').run(accId, assignmentId);
}
it('REANCHORDAY-001: moves the stop to the target day, re-indexed past the target day\'s existing max order_index', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const fromDay = createDay(testDb, trip.id, { day_number: 1 });
const toDay = createDay(testDb, trip.id, { day_number: 2 });
const stopPlace = createPlace(testDb, trip.id, { name: 'Hotel stop' });
const otherPlace = createPlace(testDb, trip.id, { name: 'Existing stop' });
createDayAssignment(testDb, toDay.id, otherPlace.id, { order_index: 5 });
const stop = createDayAssignment(testDb, fromDay.id, stopPlace.id, { order_index: 0 });
setAccommodation(stop.id, 4242);
await withRequestContext(t.orm, async () => {
await assignments.reanchorToDay(4242, toDay.id);
});
const row = testDb.prepare('SELECT day_id, order_index FROM day_assignments WHERE id = ?').get(stop.id) as { day_id: number; order_index: number };
expect(row.day_id).toBe(toDay.id);
expect(row.order_index).toBe(6);
});
it('REANCHORDAY-002: the target day starting empty yields order_index 0 (COALESCE(NULL, -1) + 1)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const fromDay = createDay(testDb, trip.id, { day_number: 1 });
const toDay = createDay(testDb, trip.id, { day_number: 2 });
const place = createPlace(testDb, trip.id);
const stop = createDayAssignment(testDb, fromDay.id, place.id, { order_index: 0 });
setAccommodation(stop.id, 7);
await withRequestContext(t.orm, async () => {
await assignments.reanchorToDay(7, toDay.id);
});
const row = testDb.prepare('SELECT day_id, order_index FROM day_assignments WHERE id = ?').get(stop.id) as { day_id: number; order_index: number };
expect(row.day_id).toBe(toDay.id);
expect(row.order_index).toBe(0);
});
it('REANCHORDAY-003: inside a uow.transactional that then ROLLS BACK, the row is left un-moved (joins the ambient transaction, proven by rollback)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const fromDay = createDay(testDb, trip.id, { day_number: 1 });
const toDay = createDay(testDb, trip.id, { day_number: 2 });
const place = createPlace(testDb, trip.id);
const stop = createDayAssignment(testDb, fromDay.id, place.id, { order_index: 0 });
setAccommodation(stop.id, 99);
let caught: unknown;
try {
await withRequestContext(t.orm, async () => {
await uow.transactional(async () => {
await assignments.reanchorToDay(99, toDay.id);
throw new Error('force rollback');
});
});
} catch (e) { caught = e; }
expect((caught as Error).message).toBe('force rollback');
const row = testDb.prepare('SELECT day_id FROM day_assignments WHERE id = ?').get(stop.id) as { day_id: number };
expect(row.day_id).toBe(fromDay.id);
});
it('REANCHORDAY-004: the same sequence, committed, actually moves the row', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const fromDay = createDay(testDb, trip.id, { day_number: 1 });
const toDay = createDay(testDb, trip.id, { day_number: 2 });
const place = createPlace(testDb, trip.id);
const stop = createDayAssignment(testDb, fromDay.id, place.id, { order_index: 0 });
setAccommodation(stop.id, 100);
await withRequestContext(t.orm, async () => {
await uow.transactional(async () => {
await assignments.reanchorToDay(100, toDay.id);
});
});
const row = testDb.prepare('SELECT day_id FROM day_assignments WHERE id = ?').get(stop.id) as { day_id: number };
expect(row.day_id).toBe(toDay.id);
});
});
@@ -2,7 +2,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vites
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { createDay, createTrip, createUser } from '../../../helpers/factories';
import { createDay, createDayNote, createTrip, createUser } from '../../../helpers/factories';
import { DayNotes } from '../../../../src/db/entities/DayNotes.entity';
import type { DayNotesRepository } from '../../../../src/db/repositories/DayNotes.repository';
import { DB_TIMESTAMP_RE } from '../../../../src/db/types';
@@ -59,3 +59,38 @@ describe('DayNotesRepository timestamps', () => {
spy.mockRestore();
});
});
// ---------------------------------------------------------------------------
// Plan 3c Task 2 (DY4) — DaysService.list's day_notes batch load.
// ---------------------------------------------------------------------------
describe('DayNotesRepository.listByDayIds (DY4)', () => {
it('NOTEREPO-005: an empty day_ids array short-circuits to [] without querying', async () => {
const connection = t.orm.em.getConnection();
const spy = vi.spyOn(connection, 'execute');
expect(await notes.listByDayIds([])).toEqual([]);
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
});
it('NOTEREPO-006: spans several days, ordered by sort_order ASC then created_at ASC', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const dayA = createDay(testDb, trip.id, { day_number: 1 });
const dayB = createDay(testDb, trip.id, { day_number: 2 });
createDayNote(testDb, dayA.id, trip.id, { text: 'Second', sort_order: 2 });
createDayNote(testDb, dayA.id, trip.id, { text: 'First', sort_order: 1 });
createDayNote(testDb, dayB.id, trip.id, { text: 'Only' });
const rows = await notes.listByDayIds([dayA.id, dayB.id]);
expect(rows.map((r) => r.text)).toEqual(['First', 'Second', 'Only']);
expect(rows.map((r) => r.day_id)).toEqual([dayA.id, dayA.id, dayB.id]);
});
it('NOTEREPO-007: a day with no notes contributes no rows', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
expect(await notes.listByDayIds([day.id])).toEqual([]);
});
});
@@ -86,3 +86,106 @@ describe('DaysRepository', () => {
spy.mockRestore();
});
});
// ---------------------------------------------------------------------------
// Plan 3c Task 2 — the DaysService conversion's remaining methods (DY7/DY9/
// DY11/DY13/DY21/DY26–DY36).
// ---------------------------------------------------------------------------
describe('DaysRepository — Task 2 additions', () => {
it('DAYREPO-010: findById is the SELECT * row, undefined for a missing id', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id, { title: 'Arrival' });
expect(await days.findById(day.id)).toStrictEqual(rawDay(day.id));
expect(await days.findById(999999)).toBeUndefined();
});
it('DAYREPO-011: updateNotesAndTitle writes both columns verbatim (the presence-sentinel decision itself lives in the service)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
await days.updateNotesAndTitle(day.id, 'Walking day', 'Arrival');
expect(await days.findById(day.id)).toMatchObject({ notes: 'Walking day', title: 'Arrival' });
await days.updateNotesAndTitle(day.id, null, null);
expect(await days.findById(day.id)).toMatchObject({ notes: null, title: null });
});
it('DAYREPO-012: setDefaultTransportMode sets and clears the column', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
await days.setDefaultTransportMode(day.id, 'walk');
expect(await days.findById(day.id)).toMatchObject({ default_transport_mode: 'walk' });
await days.setDefaultTransportMode(day.id, null);
expect(await days.findById(day.id)).toMatchObject({ default_transport_mode: null });
});
it('DAYREPO-013: deleteById is unscoped by trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
await days.deleteById(day.id);
expect(await days.findById(day.id)).toBeUndefined();
});
it('DAYREPO-014: listOrderedForReorder returns {id, day_number, date}, ordered by day_number', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const d2 = createDay(testDb, trip.id, { day_number: 2, date: '2026-01-02' });
const d1 = createDay(testDb, trip.id, { day_number: 1, date: '2026-01-01' });
const rows = await days.listOrderedForReorder(trip.id);
expect(rows).toEqual([
{ id: d1.id, day_number: 1, date: '2026-01-01' },
{ id: d2.id, day_number: 2, date: '2026-01-02' },
]);
});
it('DAYREPO-015: setDayNumber and setDayNumberAndDate write their columns; the two-phase (negative then positive) sequence a caller drives here never collides', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const a = createDay(testDb, trip.id, { day_number: 1 });
const b = createDay(testDb, trip.id, { day_number: 2 });
// Phase 1: negative, to dodge UNIQUE(trip_id, day_number) while swapping.
await days.setDayNumber(a.id, -2);
await days.setDayNumber(b.id, -1);
// Phase 2: positive (the swap).
await days.setDayNumberAndDate(a.id, 2, '2026-02-02');
await days.setDayNumberAndDate(b.id, 1, '2026-02-01');
expect(await days.findById(a.id)).toMatchObject({ day_number: 2, date: '2026-02-02' });
expect(await days.findById(b.id)).toMatchObject({ day_number: 1, date: '2026-02-01' });
});
it('DAYREPO-016: insertDay writes trip_id/day_number/date only (no notes column named) and returns the inserted id', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const id = await days.insertDay({ trip_id: trip.id, day_number: 1, date: '2026-03-01' });
expect(typeof id).toBe('number');
const row = rawDay(id) as { notes: string | null; date: string | null; day_number: number; trip_id: number };
expect(row).toMatchObject({ trip_id: trip.id, day_number: 1, date: '2026-03-01', notes: null });
});
it('DAYREPO-017: findByTripAndDate finds the day at that date, undefined otherwise, scoped to the trip', async () => {
const { user } = createUser(testDb);
const tripA = createTrip(testDb, user.id);
const tripB = createTrip(testDb, user.id);
const day = createDay(testDb, tripA.id, { date: '2026-04-01' });
createDay(testDb, tripB.id, { date: '2026-04-01' });
expect(await days.findByTripAndDate(tripA.id, '2026-04-01')).toEqual({ id: day.id, day_number: day.day_number });
expect(await days.findByTripAndDate(tripA.id, '2026-04-02')).toBeUndefined();
});
// D-shape: `findById` (findOne-based, `disableIdentityMap: true` by the base
// class default) must see a column written after an unrelated identity-map
// read populated the same entity type — written column (`notes`) is outside
// the narrower read's own projection scope, so a stale write-back would
// revert it if the base class's guarantee ever regressed.
it('DAYREPO-018 (D-shape): a notes write after an unrelated identity-map read is visible in findById', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
await t.repo(Days).find({}); // populate the identity map with an unrelated read
await days.updateNotesAndTitle(day.id, 'Fresh notes', null);
expect(await days.findById(day.id)).toMatchObject({ notes: 'Fresh notes' });
});
});
@@ -80,3 +80,18 @@ describe('TripsRepository.findAccessible — parity with canAccessTrip', () => {
expect(wrap(entity).toObject()).toStrictEqual(raw);
});
});
// Plan 3c Task 2 (DY35): `days.service.ts::insert`'s dated path extends the
// trip by one day. Owned exclusively by Task 2 per the plan's file
// ownership (`Trips.repository.ts` ONLY for `setEndDate`) — appended here
// rather than interleaved with Task 1's blocks above.
describe('TripsRepository.setEndDate (Plan 3c Task 2, DY35)', () => {
it('TRIPREPO-013: writes end_date verbatim, including clearing it to null', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await trips.setEndDate(trip.id, '2026-09-30');
expect((testDb.prepare('SELECT end_date FROM trips WHERE id = ?').get(trip.id) as { end_date: string | null }).end_date).toBe('2026-09-30');
await trips.setEndDate(trip.id, null);
expect((testDb.prepare('SELECT end_date FROM trips WHERE id = ?').get(trip.id) as { end_date: string | null }).end_date).toBeNull();
});
});
+26 -3
View File
@@ -64,12 +64,25 @@ import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpers.service';
import { makeAccommodationsService } from '../../helpers/accommodations-service';
import type { Day } from '../../../src/types';
import { createTestUnitOfWork, createTestAppSettingsRepo, createTestDatabaseService } from '../../helpers/test-uow';
import {
createTestUnitOfWork, createTestAppSettingsRepo, createTestDatabaseService,
createTestDaysRepo, createTestDayAssignmentsRepo, createTestDayNotesRepo, createTestTripsRepo,
} from '../../helpers/test-uow';
let svc: DaysService;
beforeAll(async () => {
const dbs = await createTestDatabaseService(testDb);
svc = new DaysService(dbs, new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new RealtimeService(), new QueryHelpersService(dbs), await createTestUnitOfWork(testDb));
svc = new DaysService(
dbs,
new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)),
new RealtimeService(),
new QueryHelpersService(dbs),
await createTestUnitOfWork(testDb),
await createTestDaysRepo(testDb),
await createTestDayAssignmentsRepo(testDb),
await createTestDayNotesRepo(testDb),
await createTestTripsRepo(testDb),
);
});
let accommodations: Awaited<ReturnType<typeof makeAccommodationsService>>;
beforeAll(async () => {
@@ -799,7 +812,17 @@ describe('DaysService.canEdit', () => {
it('DAY-SVC-090 asks for day_edit and flags a non-owner as shared', async () => {
const checkPermission = vi.fn(() => true);
const permissions = { checkPermission } as unknown as PermissionsService;
const withStub = new DaysService(new DatabaseService(testDb), permissions, new RealtimeService(), new QueryHelpersService(new DatabaseService(testDb)), await createTestUnitOfWork(testDb));
const withStub = new DaysService(
new DatabaseService(testDb),
permissions,
new RealtimeService(),
new QueryHelpersService(new DatabaseService(testDb)),
await createTestUnitOfWork(testDb),
await createTestDaysRepo(testDb),
await createTestDayAssignmentsRepo(testDb),
await createTestDayNotesRepo(testDb),
await createTestTripsRepo(testDb),
);
const trip = { id: 1, user_id: 1 } as never;
expect(await withStub.canEdit(trip, { id: 1, role: 'user' } as never)).toBe(true);
@@ -78,7 +78,10 @@ import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.serv
import { makeStorageFixture } from '../../helpers/storage-fixture';
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
import { createTestUnitOfWork, createTestAppSettingsRepo, createTestUsersRepo, sharedTestOrm } from '../../helpers/test-uow';
import {
createTestUnitOfWork, createTestAppSettingsRepo, createTestUsersRepo, sharedTestOrm,
createTestDaysRepo, createTestDayAssignmentsRepo, createTestDayNotesRepo, createTestTripsRepo,
} from '../../helpers/test-uow';
// Real sibling services over the same in-memory DB — the aggregation runs the
// actual SQL of every domain it fans out to, so a shape change downstream shows
@@ -100,7 +103,17 @@ let placesSvc: PlacesService;
let membersSvc: TripMembersService;
beforeAll(async () => {
budgetSvc = new BudgetService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(dbs().connection));
daysSvc = new DaysService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), new QueryHelpersService(dbs()), await createTestUnitOfWork(dbs().connection));
daysSvc = new DaysService(
dbs(),
new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)),
new RealtimeService(),
new QueryHelpersService(dbs()),
await createTestUnitOfWork(dbs().connection),
await createTestDaysRepo(dbs().connection),
await createTestDayAssignmentsRepo(dbs().connection),
await createTestDayNotesRepo(dbs().connection),
await createTestTripsRepo(dbs().connection),
);
placesSvc = new PlacesService(
dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(),
new MapsService(dbs(), photoCache, await createTestAppSettingsRepo(dbs().connection), await createTestUsersRepo(dbs().connection)), new QueryHelpersService(dbs()),
+15 -2
View File
@@ -88,7 +88,10 @@ import fs from 'fs';
import path from 'path';
import { notificationsStub } from '../../helpers/notifications';
import { EphemeralTokenService } from '../../../src/nest/auth/ephemeral-token.service';
import { createTestUnitOfWork, createTestAppSettingsRepo, createTestUsersRepo, sharedTestOrm } from '../../helpers/test-uow';
import {
createTestUnitOfWork, createTestAppSettingsRepo, createTestUsersRepo, sharedTestOrm,
createTestDaysRepo, createTestDayAssignmentsRepo, createTestDayNotesRepo, createTestTripsRepo,
} from '../../helpers/test-uow';
// Real sibling services over the same in-memory DB — updateTrip's date-shift
// resyncs and the summary/bundle aggregation run their actual SQL.
@@ -133,7 +136,17 @@ let readModelSvc: TripReadModelService;
beforeAll(async () => {
dbsEm = (await sharedTestOrm(testDb)).em;
budgetSvc = new BudgetService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(dbs().connection));
daysSvc = new DaysService(dbs(), new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)), new RealtimeService(), new QueryHelpersService(dbs()), await createTestUnitOfWork(dbs().connection));
daysSvc = new DaysService(
dbs(),
new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)),
new RealtimeService(),
new QueryHelpersService(dbs()),
await createTestUnitOfWork(dbs().connection),
await createTestDaysRepo(dbs().connection),
await createTestDayAssignmentsRepo(dbs().connection),
await createTestDayNotesRepo(dbs().connection),
await createTestTripsRepo(dbs().connection),
);
placesSvc = new PlacesService(
dbs(),
new PermissionsService(await createTestAppSettingsRepo(dbs().connection), await createTestUnitOfWork(dbs().connection)),