mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 09:22:15 +00:00
refactor(roadtrip): roadtrip tables through repositories
This commit is contained in:
@@ -2,7 +2,18 @@ import { RoadtripSearchService } from '../../src/nest/roadtrip/roadtrip-search.s
|
||||
import { GoogleRouteService } from '../../src/nest/roadtrip/google-route.service';
|
||||
import { ChargingService } from '../../src/nest/roadtrip/charging.service';
|
||||
/**
|
||||
* Road trip module e2e — the real guard chain against a temp SQLite db.
|
||||
* Road trip module e2e — the real guard chain against a real migrated-and-
|
||||
* seeded temp SQLite db (`createSnapshotTestDb()`, Plan 3d Task 1 — this used
|
||||
* to hand-roll ten CREATE TABLEs, a second hand-maintained schema copy that
|
||||
* omitted `day_assignments`/`day_accommodations`/most `users`/`trips`/
|
||||
* `places` columns and even LEFT JOINed the inverse 1:1 `roadtrip_day_tracks`
|
||||
* relation `Days` carries — the exact "e2e suites build their schema from
|
||||
* hand-written partial DDL" risk the plan's inventory §15c flagged, and the
|
||||
* same class of failure `days.e2e.test.ts`'s own conversion, Plan 3c Task 2,
|
||||
* fixed for that file). Every service in this module now runs its real SQL
|
||||
* through repositories (DI-injected, no service mock) against the real
|
||||
* request-scoped `EntityManager` `createTestMikroOrmModule` wires in; only
|
||||
* the permission check and the WebSocket broadcast stay mocked.
|
||||
*
|
||||
* The unit test next door pins the handler bodies. What only a booted container
|
||||
* can show is the thing the controller's own comment calls load-bearing: that
|
||||
@@ -21,7 +32,7 @@ import { PermissionsService } from '../../src/nest/permissions/permissions.servi
|
||||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||||
import { RoadtripModule } from '../../src/nest/roadtrip/roadtrip.module';
|
||||
import { RoadtripHazardsService } from '../../src/nest/roadtrip/roadtrip-hazards.service';
|
||||
import { seedUser, sessionCookie } from './harness';
|
||||
import { sessionCookie } from './harness';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
@@ -31,63 +42,21 @@ import { describe, it, expect, beforeAll, afterAll, beforeEach, vi, type MockIns
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { createTestMikroOrmModule } from '../helpers/test-orm';
|
||||
|
||||
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('PRAGMA foreign_keys = ON');
|
||||
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 roadtrip_preferences (trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY(trip_id, key));',
|
||||
);
|
||||
tmp.exec('CREATE TABLE trip_members (trip_id INTEGER NOT NULL, user_id INTEGER NOT NULL);');
|
||||
tmp.exec(`CREATE TABLE days (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
|
||||
day_number INTEGER, date TEXT, title TEXT, notes TEXT);`);
|
||||
tmp.exec(`CREATE TABLE places (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL, name TEXT,
|
||||
lat REAL, lng REAL, route_geometry TEXT, stop_type TEXT, fill_percent INTEGER);`);
|
||||
tmp.exec(`CREATE TABLE roadtrip_vias (id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
|
||||
after_order_index INTEGER NOT NULL, sequence INTEGER NOT NULL DEFAULT 0,
|
||||
lat REAL NOT NULL, lng REAL NOT NULL, created_at TEXT DEFAULT CURRENT_TIMESTAMP);`);
|
||||
tmp.exec(`CREATE TABLE roadtrip_day_tracks (
|
||||
day_id INTEGER PRIMARY KEY REFERENCES days(id) ON DELETE CASCADE,
|
||||
place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE, stray_km REAL);`);
|
||||
// AddonsService reads this; StorageRegistryService reads app_settings at init.
|
||||
tmp.exec(`CREATE TABLE addons (id TEXT PRIMARY KEY, enabled INTEGER NOT NULL DEFAULT 0,
|
||||
name TEXT, description TEXT, category TEXT, sort_order INTEGER DEFAULT 0);`);
|
||||
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,
|
||||
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';
|
||||
|
||||
const ADDON_ID = 'roadtrip';
|
||||
|
||||
function setAddon(enabled: boolean): void {
|
||||
db.prepare(
|
||||
'INSERT INTO addons (id, enabled) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET enabled = excluded.enabled',
|
||||
).run(ADDON_ID, enabled ? 1 : 0);
|
||||
// The seeder (`AddonSeeder`, run once as part of `createSnapshotTestDb()`'s
|
||||
// migration pass) already inserted this row, disabled — a plain UPDATE,
|
||||
// not an upsert, matching every other addon-toggling e2e in this file set.
|
||||
db.prepare('UPDATE addons SET enabled = ? WHERE id = ?').run(enabled ? 1 : 0, ADDON_ID);
|
||||
}
|
||||
|
||||
describe('Roadtrip e2e (real guard chain + temp SQLite)', () => {
|
||||
@@ -108,8 +77,12 @@ describe('Roadtrip e2e (real guard chain + temp SQLite)', () => {
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
seedUser(db as never, { id: 1 });
|
||||
seedUser(db as never, { id: 2, email: 'other@example.test' });
|
||||
// harness.ts's seedUser() omits password_hash, which the real migrated
|
||||
// schema requires NOT NULL (days.e2e.test.ts/assignments.e2e.test.ts's
|
||||
// own precedent) — raw inserts here instead, matching the SeededUser
|
||||
// shape id/role/password_version=0 that sessionCookie() 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 users (id, username, email, password_hash, role, password_version) VALUES (2, 'other', 'other@example.test', 'x', 'user', 0)").run();
|
||||
db.prepare('INSERT INTO trips (id, user_id, title) VALUES (5, 1, ?)').run('Norway');
|
||||
db.prepare('INSERT INTO trips (id, user_id, title) VALUES (6, 2, ?)').run('Somebody else');
|
||||
db.prepare('INSERT INTO days (id, trip_id, day_number) VALUES (3, 5, 1)').run();
|
||||
|
||||
@@ -10,7 +10,7 @@ import { TrekPhotosRepository } from '../../src/nest/photos/trek-photos.reposito
|
||||
import {
|
||||
createTestUnitOfWork, createTestAppSettingsRepo, createTestTagsRepo, createTestPlaceRatingsRepo,
|
||||
createTestAssignmentParticipantsRepo, createTestDayAssignmentsRepo, createTestDaysRepo, createTestPlacesRepo,
|
||||
createTestTripMembersRepo, sharedTestOrm,
|
||||
createTestTripMembersRepo, createTestRoadtripViasRepo, sharedTestOrm,
|
||||
} from './test-uow';
|
||||
|
||||
/**
|
||||
@@ -50,6 +50,7 @@ export async function accommodationsOver(dbs: DatabaseService): Promise<Accommod
|
||||
await createTestDaysRepo(dbs.connection),
|
||||
await createTestPlacesRepo(dbs.connection),
|
||||
await createTestTripMembersRepo(dbs.connection),
|
||||
await createTestRoadtripViasRepo(dbs.connection),
|
||||
);
|
||||
return new AccommodationsService(dbs, permissions, realtime, assignments, await createTestUnitOfWork(dbs.connection));
|
||||
}
|
||||
|
||||
@@ -118,7 +118,9 @@ import {
|
||||
createTestUnitOfWork, createTestAppSettingsRepo, createTestCategoriesRepo, createTestTagsRepo, createTestSettingsRepo,
|
||||
createTestDaysRepo, createTestDayAssignmentsRepo, createTestDayNotesRepo, createTestTripsRepo,
|
||||
createTestTripMembersRepo, createTestPlaceRatingsRepo, createTestAssignmentParticipantsRepo,
|
||||
createTestGooglePlacePhotoMetaRepo, createTestPlacesRepo,
|
||||
createTestGooglePlacePhotoMetaRepo, createTestPlacesRepo, createTestRoadtripViasRepo, createTestRoadtripDayTracksRepo,
|
||||
createTestReservationsRepo,
|
||||
createTestReservationEndpointsRepo,
|
||||
} from './test-uow';
|
||||
import { createTestOrm } from './test-orm';
|
||||
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
|
||||
@@ -185,6 +187,8 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
|
||||
await createTestDayAssignmentsRepo(dbService.connection),
|
||||
await createTestDayNotesRepo(dbService.connection),
|
||||
await createTestTripsRepo(dbService.connection),
|
||||
await createTestReservationsRepo(dbService.connection),
|
||||
await createTestReservationEndpointsRepo(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));
|
||||
@@ -208,6 +212,7 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
|
||||
await createTestDaysRepo(dbService.connection),
|
||||
await createTestPlacesRepo(dbService.connection),
|
||||
await createTestTripMembersRepo(dbService.connection),
|
||||
await createTestRoadtripViasRepo(dbService.connection),
|
||||
);
|
||||
const accommodationsService = new AccommodationsService(dbService, permissionsService, realtimeService, assignmentsService, await createTestUnitOfWork(dbService.connection));
|
||||
// Built after it: deleting a place cancels the nights booked at it through this one.
|
||||
@@ -276,7 +281,20 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
|
||||
new ReservationsMcp(reservationsService, daysService, budgetService, authService, assignmentsService, guards),
|
||||
new DayNotesMcp(new DayNotesService(dbService, permissionsService, realtimeService), authService, guards),
|
||||
new DaysMcp(daysService, authService, guards),
|
||||
new RoadtripMcp(new RoadtripService(dbService, realtimeService, await createTestUnitOfWork(dbService.connection)), dbService, guards, authService, addonsService),
|
||||
new RoadtripMcp(
|
||||
new RoadtripService(
|
||||
realtimeService,
|
||||
await createTestUnitOfWork(dbService.connection),
|
||||
await createTestDaysRepo(dbService.connection),
|
||||
await createTestPlacesRepo(dbService.connection),
|
||||
await createTestRoadtripViasRepo(dbService.connection),
|
||||
await createTestRoadtripDayTracksRepo(dbService.connection),
|
||||
),
|
||||
await createTestTripsRepo(dbService.connection),
|
||||
guards,
|
||||
authService,
|
||||
addonsService,
|
||||
),
|
||||
new FilesMcp(new FilesService(dbService, permissionsService, realtimeService, new EphemeralTokenService(), generalStorage, mcpOrm.em), authService, guards),
|
||||
new AccommodationsMcp(accommodationsService, dbService, placesService, authService, guards, await createTestUnitOfWork(dbService.connection)),
|
||||
new AssignmentsMcp(assignmentsService, daysService, authService, guards),
|
||||
|
||||
@@ -76,7 +76,9 @@ import {
|
||||
createTestUnitOfWork, createTestAppSettingsRepo, createTestCategoriesRepo, createTestTagsRepo, createTestSettingsRepo, sharedTestOrm,
|
||||
createTestDaysRepo, createTestDayAssignmentsRepo, createTestDayNotesRepo, createTestTripsRepo,
|
||||
createTestTripMembersRepo, createTestPlaceRatingsRepo, createTestAssignmentParticipantsRepo,
|
||||
createTestGooglePlacePhotoMetaRepo, createTestPlacesRepo,
|
||||
createTestGooglePlacePhotoMetaRepo, createTestPlacesRepo, createTestRoadtripViasRepo,
|
||||
createTestReservationsRepo,
|
||||
createTestReservationEndpointsRepo,
|
||||
} from './test-uow';
|
||||
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
|
||||
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
|
||||
@@ -117,6 +119,8 @@ export async function createPluginRpcHostFactory(dbs: DatabaseService): Promise<
|
||||
await createTestDayAssignmentsRepo(dbs.connection),
|
||||
await createTestDayNotesRepo(dbs.connection),
|
||||
await createTestTripsRepo(dbs.connection),
|
||||
await createTestReservationsRepo(dbs.connection),
|
||||
await createTestReservationEndpointsRepo(dbs.connection),
|
||||
);
|
||||
const photoCache = new PlacePhotoCacheService(dbs, makeStorageFixture('photos/google/').storage, await createTestGooglePlacePhotoMetaRepo(dbs.connection), await createTestPlacesRepo(dbs.connection));
|
||||
const unsplash = new UnsplashService(appSettings, usersRepo, new RuntimeEnvService(), generalStorage);
|
||||
@@ -131,6 +135,7 @@ export async function createPluginRpcHostFactory(dbs: DatabaseService): Promise<
|
||||
await createTestDaysRepo(dbs.connection),
|
||||
await createTestPlacesRepo(dbs.connection),
|
||||
await createTestTripMembersRepo(dbs.connection),
|
||||
await createTestRoadtripViasRepo(dbs.connection),
|
||||
);
|
||||
const membership = new TripMembershipService(await createTestTripsRepo(dbs.connection), await createTestTripMembersRepo(dbs.connection));
|
||||
const notifications = await makeNotificationsService(dbs, realtime);
|
||||
|
||||
@@ -47,6 +47,24 @@ import { GooglePlacePhotoMeta } from '../../src/db/entities/GooglePlacePhotoMeta
|
||||
import type { GooglePlacePhotoMetaRepository } from '../../src/db/repositories/GooglePlacePhotoMeta.repository';
|
||||
import { PlaceDetailsCache } from '../../src/db/entities/PlaceDetailsCache.entity';
|
||||
import type { PlaceDetailsCacheRepository } from '../../src/db/repositories/PlaceDetailsCache.repository';
|
||||
import { Reservations } from '../../src/db/entities/Reservations.entity';
|
||||
import type { ReservationsRepository } from '../../src/db/repositories/Reservations.repository';
|
||||
import { ReservationEndpoints } from '../../src/db/entities/ReservationEndpoints.entity';
|
||||
import type { ReservationEndpointsRepository } from '../../src/db/repositories/ReservationEndpoints.repository';
|
||||
import { ReservationTravelers } from '../../src/db/entities/ReservationTravelers.entity';
|
||||
import type { ReservationTravelersRepository } from '../../src/db/repositories/ReservationTravelers.repository';
|
||||
import { ReservationDayPositions } from '../../src/db/entities/ReservationDayPositions.entity';
|
||||
import type { ReservationDayPositionsRepository } from '../../src/db/repositories/ReservationDayPositions.repository';
|
||||
import { DayAccommodations } from '../../src/db/entities/DayAccommodations.entity';
|
||||
import type { DayAccommodationsRepository } from '../../src/db/repositories/DayAccommodations.repository';
|
||||
import { RoadtripVias } from '../../src/db/entities/RoadtripVias.entity';
|
||||
import type { RoadtripViasRepository } from '../../src/db/repositories/RoadtripVias.repository';
|
||||
import { RoadtripDayTracks } from '../../src/db/entities/RoadtripDayTracks.entity';
|
||||
import type { RoadtripDayTracksRepository } from '../../src/db/repositories/RoadtripDayTracks.repository';
|
||||
import { RoadtripPreferences } from '../../src/db/entities/RoadtripPreferences.entity';
|
||||
import type { RoadtripPreferencesRepository } from '../../src/db/repositories/RoadtripPreferences.repository';
|
||||
import { RoadtripDayBoundaries } from '../../src/db/entities/RoadtripDayBoundaries.entity';
|
||||
import type { RoadtripDayBoundariesRepository } from '../../src/db/repositories/RoadtripDayBoundaries.repository';
|
||||
|
||||
const perHandle = new WeakMap<Database.Database, Promise<UnitOfWork>>();
|
||||
const appSettingsPerHandle = new WeakMap<Database.Database, Promise<AppSettingsRepository>>();
|
||||
@@ -459,3 +477,112 @@ export function createTestPlaceDetailsCacheRepo(db: Database.Database): Promise<
|
||||
placeDetailsCacheRepoPerHandle.set(db, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3d Task 2 (`ReservationsService`/`DaysService`'s DY14–DY18/DY23 onto
|
||||
// `ReservationsRepository`/`ReservationEndpointsRepository`/
|
||||
// `ReservationTravelersRepository`/`ReservationDayPositionsRepository`/
|
||||
// `DayAccommodationsRepository`) — appended at the end per the task's own
|
||||
// file-ownership rule (append only). Same memoisation-per-handle pattern as
|
||||
// every helper above.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const reservationsRepoPerHandle = new WeakMap<Database.Database, Promise<ReservationsRepository>>();
|
||||
const reservationEndpointsRepoPerHandle = new WeakMap<Database.Database, Promise<ReservationEndpointsRepository>>();
|
||||
const reservationTravelersRepoPerHandle = new WeakMap<Database.Database, Promise<ReservationTravelersRepository>>();
|
||||
const reservationDayPositionsRepoPerHandle = new WeakMap<Database.Database, Promise<ReservationDayPositionsRepository>>();
|
||||
const dayAccommodationsRepoPerHandle = new WeakMap<Database.Database, Promise<DayAccommodationsRepository>>();
|
||||
|
||||
/** The `ReservationsRepository` a hand-constructed `ReservationsService`/`DaysService` needs. */
|
||||
export function createTestReservationsRepo(db: Database.Database): Promise<ReservationsRepository> {
|
||||
const existing = reservationsRepoPerHandle.get(db);
|
||||
if (existing !== undefined) return existing;
|
||||
const pending = sharedTestOrm(db).then((t) => t.repo(Reservations));
|
||||
reservationsRepoPerHandle.set(db, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** The `ReservationEndpointsRepository` a hand-constructed `ReservationsService`/`DaysService` needs. */
|
||||
export function createTestReservationEndpointsRepo(db: Database.Database): Promise<ReservationEndpointsRepository> {
|
||||
const existing = reservationEndpointsRepoPerHandle.get(db);
|
||||
if (existing !== undefined) return existing;
|
||||
const pending = sharedTestOrm(db).then((t) => t.repo(ReservationEndpoints));
|
||||
reservationEndpointsRepoPerHandle.set(db, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** The `ReservationTravelersRepository` a hand-constructed `ReservationsService` needs. */
|
||||
export function createTestReservationTravelersRepo(db: Database.Database): Promise<ReservationTravelersRepository> {
|
||||
const existing = reservationTravelersRepoPerHandle.get(db);
|
||||
if (existing !== undefined) return existing;
|
||||
const pending = sharedTestOrm(db).then((t) => t.repo(ReservationTravelers));
|
||||
reservationTravelersRepoPerHandle.set(db, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** The `ReservationDayPositionsRepository` a hand-constructed `ReservationsService` needs. */
|
||||
export function createTestReservationDayPositionsRepo(db: Database.Database): Promise<ReservationDayPositionsRepository> {
|
||||
const existing = reservationDayPositionsRepoPerHandle.get(db);
|
||||
if (existing !== undefined) return existing;
|
||||
const pending = sharedTestOrm(db).then((t) => t.repo(ReservationDayPositions));
|
||||
reservationDayPositionsRepoPerHandle.set(db, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** The `DayAccommodationsRepository` a hand-constructed `ReservationsService` needs. */
|
||||
export function createTestDayAccommodationsRepo(db: Database.Database): Promise<DayAccommodationsRepository> {
|
||||
const existing = dayAccommodationsRepoPerHandle.get(db);
|
||||
if (existing !== undefined) return existing;
|
||||
const pending = sharedTestOrm(db).then((t) => t.repo(DayAccommodations));
|
||||
dayAccommodationsRepoPerHandle.set(db, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3d Task 1 (`RoadtripService`/`RoadtripPlanService`/
|
||||
// `RoadtripPreferencesService`/`DayBoundariesService`/`ChargingService`/
|
||||
// `GoogleRouteService`, `AssignmentsService`'s AS20–AS23) — appended at the
|
||||
// end per this task's own file-ownership rule (append only). Same
|
||||
// memoisation-per-handle pattern as every helper above.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const roadtripViasRepoPerHandle = new WeakMap<Database.Database, Promise<RoadtripViasRepository>>();
|
||||
const roadtripDayTracksRepoPerHandle = new WeakMap<Database.Database, Promise<RoadtripDayTracksRepository>>();
|
||||
const roadtripPreferencesRepoPerHandle = new WeakMap<Database.Database, Promise<RoadtripPreferencesRepository>>();
|
||||
const roadtripDayBoundariesRepoPerHandle = new WeakMap<Database.Database, Promise<RoadtripDayBoundariesRepository>>();
|
||||
|
||||
/** The `RoadtripViasRepository` a hand-constructed `RoadtripService`/`AssignmentsService` needs. */
|
||||
export function createTestRoadtripViasRepo(db: Database.Database): Promise<RoadtripViasRepository> {
|
||||
const existing = roadtripViasRepoPerHandle.get(db);
|
||||
if (existing !== undefined) return existing;
|
||||
const pending = sharedTestOrm(db).then((t) => t.repo(RoadtripVias));
|
||||
roadtripViasRepoPerHandle.set(db, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** The `RoadtripDayTracksRepository` a hand-constructed `RoadtripService` needs. */
|
||||
export function createTestRoadtripDayTracksRepo(db: Database.Database): Promise<RoadtripDayTracksRepository> {
|
||||
const existing = roadtripDayTracksRepoPerHandle.get(db);
|
||||
if (existing !== undefined) return existing;
|
||||
const pending = sharedTestOrm(db).then((t) => t.repo(RoadtripDayTracks));
|
||||
roadtripDayTracksRepoPerHandle.set(db, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** The `RoadtripPreferencesRepository` a hand-constructed `RoadtripPreferencesService` needs. */
|
||||
export function createTestRoadtripPreferencesRepo(db: Database.Database): Promise<RoadtripPreferencesRepository> {
|
||||
const existing = roadtripPreferencesRepoPerHandle.get(db);
|
||||
if (existing !== undefined) return existing;
|
||||
const pending = sharedTestOrm(db).then((t) => t.repo(RoadtripPreferences));
|
||||
roadtripPreferencesRepoPerHandle.set(db, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** The `RoadtripDayBoundariesRepository` a hand-constructed `DayBoundariesService` needs. */
|
||||
export function createTestRoadtripDayBoundariesRepo(db: Database.Database): Promise<RoadtripDayBoundariesRepository> {
|
||||
const existing = roadtripDayBoundariesRepoPerHandle.get(db);
|
||||
if (existing !== undefined) return existing;
|
||||
const pending = sharedTestOrm(db).then((t) => t.repo(RoadtripDayBoundaries));
|
||||
roadtripDayBoundariesRepoPerHandle.set(db, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* `RoadtripDayBoundariesRepository` (Plan 3d Task 1). RB1 (`listForTrip`),
|
||||
* RB3 (`upsertBoundary`, `ON CONFLICT (trip_id, day_number) DO UPDATE SET
|
||||
* from_assignment_id = excluded.from_assignment_id, to_assignment_id =
|
||||
* excluded.to_assignment_id, fraction = excluded.fraction`) and RB4
|
||||
* (`deleteForDay`).
|
||||
*/
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
import { createDay, createDayAssignment, createPlace, createTrip, createUser } from '../../../helpers/factories';
|
||||
import { RoadtripDayBoundaries } from '../../../../src/db/entities/RoadtripDayBoundaries.entity';
|
||||
import type { RoadtripDayBoundariesRepository } from '../../../../src/db/repositories/RoadtripDayBoundaries.repository';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let repo: RoadtripDayBoundariesRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
repo = t.repo(RoadtripDayBoundaries);
|
||||
});
|
||||
beforeEach(() => { resetTestDb(testDb); t.clear(); });
|
||||
afterAll(async () => { await t.close(); testDb.close(); });
|
||||
|
||||
function fixture() {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const day = createDay(testDb, trip.id);
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const from = createDayAssignment(testDb, day.id, place.id);
|
||||
const to = createDayAssignment(testDb, day.id, place.id);
|
||||
return { trip, day, from, to };
|
||||
}
|
||||
|
||||
describe('RoadtripDayBoundariesRepository', () => {
|
||||
it('RB1REPO-001: listForTrip is empty for a trip with no boundaries', async () => {
|
||||
const { trip } = fixture();
|
||||
expect(await repo.listForTrip(trip.id)).toEqual([]);
|
||||
});
|
||||
|
||||
it('UPSERTBOUNDARYREPO-001: upsertBoundary inserts a fresh (trip, day_number) row with every column', async () => {
|
||||
const { trip, from, to } = fixture();
|
||||
await repo.upsertBoundary(trip.id, { day_number: 1, from_assignment_id: from.id, to_assignment_id: to.id, fraction: 0.4 });
|
||||
expect(await repo.listForTrip(trip.id)).toEqual([{ day_number: 1, from_assignment_id: from.id, to_assignment_id: to.id, fraction: 0.4 }]);
|
||||
});
|
||||
|
||||
it('UPSERTBOUNDARYREPO-002: re-upserting the SAME (trip, day_number) replaces in place — one row, never touching the key', async () => {
|
||||
const { trip, from, to } = fixture();
|
||||
await repo.upsertBoundary(trip.id, { day_number: 1, from_assignment_id: from.id, to_assignment_id: to.id, fraction: 0.4 });
|
||||
await repo.upsertBoundary(trip.id, { day_number: 1, from_assignment_id: to.id, to_assignment_id: null, fraction: 1 });
|
||||
|
||||
const rows = await repo.listForTrip(trip.id);
|
||||
expect(rows).toEqual([{ day_number: 1, from_assignment_id: to.id, to_assignment_id: null, fraction: 1 }]);
|
||||
});
|
||||
|
||||
it('RB1REPO-002: listForTrip orders by day_number ascending', async () => {
|
||||
const { trip, from, to } = fixture();
|
||||
await repo.upsertBoundary(trip.id, { day_number: 3, from_assignment_id: from.id, to_assignment_id: to.id, fraction: 0.5 });
|
||||
await repo.upsertBoundary(trip.id, { day_number: 1, from_assignment_id: from.id, to_assignment_id: to.id, fraction: 0.5 });
|
||||
await repo.upsertBoundary(trip.id, { day_number: 2, from_assignment_id: from.id, to_assignment_id: to.id, fraction: 0.5 });
|
||||
|
||||
expect((await repo.listForTrip(trip.id)).map((b) => b.day_number)).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('RB4REPO-001: deleteForDay removes only the named day_number, silent on a miss', async () => {
|
||||
const { trip, from, to } = fixture();
|
||||
await repo.upsertBoundary(trip.id, { day_number: 1, from_assignment_id: from.id, to_assignment_id: to.id, fraction: 0.4 });
|
||||
await repo.upsertBoundary(trip.id, { day_number: 2, from_assignment_id: from.id, to_assignment_id: to.id, fraction: 0.4 });
|
||||
|
||||
await expect(repo.deleteForDay(trip.id, 99)).resolves.toBeUndefined();
|
||||
expect(await repo.listForTrip(trip.id)).toHaveLength(2);
|
||||
|
||||
await repo.deleteForDay(trip.id, 1);
|
||||
expect((await repo.listForTrip(trip.id)).map((b) => b.day_number)).toEqual([2]);
|
||||
});
|
||||
|
||||
it('boundaries of one trip are never boundaries of another', async () => {
|
||||
const { trip: tripA, from: fromA, to: toA } = fixture();
|
||||
const { trip: tripB, from: fromB, to: toB } = fixture();
|
||||
await repo.upsertBoundary(tripA.id, { day_number: 1, from_assignment_id: fromA.id, to_assignment_id: toA.id, fraction: 0.4 });
|
||||
await repo.upsertBoundary(tripB.id, { day_number: 1, from_assignment_id: fromB.id, to_assignment_id: toB.id, fraction: 0.9 });
|
||||
|
||||
expect(await repo.listForTrip(tripA.id)).toEqual([{ day_number: 1, from_assignment_id: fromA.id, to_assignment_id: toA.id, fraction: 0.4 }]);
|
||||
expect(await repo.listForTrip(tripB.id)).toEqual([{ day_number: 1, from_assignment_id: fromB.id, to_assignment_id: toB.id, fraction: 0.9 }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* `RoadtripDayTracksRepository` (Plan 3d Task 1). RT7 (`deleteForDay`), RT8
|
||||
* (`upsertTrack`) and RT12 (`listForTrip`).
|
||||
*
|
||||
* RT8's `onConflictFields: ['day']` targets `RoadtripDayTracks.day` — this
|
||||
* table's PRIMARY KEY, a NULLABLE one-to-one relation (Task 0's RULE12/
|
||||
* generator finding, ruled NOT a defect). Task 0's review carried a live
|
||||
* finding forward to this task: SQLite accepts `INSERT … VALUES (NULL, …)`
|
||||
* on an INTEGER PRIMARY KEY column and silently assigns the next free
|
||||
* rowid instead of refusing — so an unguarded `day_id` reaching this
|
||||
* upsert could silently write to the WRONG day (another trip's). Two
|
||||
* things prove this is safe here: (1) `upsertTrack`'s own signature is
|
||||
* `day_id: number`, never nullable — TypeScript refuses a `null`/
|
||||
* `undefined` call at compile time; (2) `RoadtripService.requireDayId`
|
||||
* (the caller) parses every `dayId` with `toRowId` BEFORE it reaches this
|
||||
* repository (RT8-GUARD-001 below, at the service level — a repository
|
||||
* unit test cannot express a `null` argument a typed signature rejects).
|
||||
*/
|
||||
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 { createDay, createPlace, createTrip, createUser } from '../../../helpers/factories';
|
||||
import { RoadtripDayTracks } from '../../../../src/db/entities/RoadtripDayTracks.entity';
|
||||
import type { RoadtripDayTracksRepository } from '../../../../src/db/repositories/RoadtripDayTracks.repository';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let tracks: RoadtripDayTracksRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
tracks = t.repo(RoadtripDayTracks);
|
||||
});
|
||||
beforeEach(() => { resetTestDb(testDb); t.clear(); });
|
||||
afterAll(async () => { await t.close(); testDb.close(); });
|
||||
|
||||
function fixture() {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const dayA = createDay(testDb, trip.id);
|
||||
const placeA = createPlace(testDb, trip.id, { name: 'Track A' });
|
||||
const placeB = createPlace(testDb, trip.id, { name: 'Track B' });
|
||||
return { trip, dayA, placeA, placeB };
|
||||
}
|
||||
|
||||
function rawRows(): { day_id: number; place_id: number; stray_km: number | null; created_at: string | null }[] {
|
||||
return testDb.prepare('SELECT day_id, place_id, stray_km, created_at FROM roadtrip_day_tracks ORDER BY day_id').all() as never[];
|
||||
}
|
||||
|
||||
describe('RoadtripDayTracksRepository', () => {
|
||||
it('RT7REPO-001: deleteForDay removes the one row for that day', async () => {
|
||||
const { dayA, placeA } = fixture();
|
||||
await tracks.upsertTrack(dayA.id, placeA.id, null);
|
||||
expect(rawRows()).toHaveLength(1);
|
||||
await tracks.deleteForDay(dayA.id);
|
||||
expect(rawRows()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('RT7REPO-002: deleteForDay on a day with no track is a silent no-op', async () => {
|
||||
const { dayA } = fixture();
|
||||
await expect(tracks.deleteForDay(dayA.id)).resolves.toBeUndefined();
|
||||
expect(rawRows()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('UPSERTTRACKREPO-001: a fresh day_id inserts one row', async () => {
|
||||
const { dayA, placeA } = fixture();
|
||||
await tracks.upsertTrack(dayA.id, placeA.id, 1.5);
|
||||
const rows = rawRows();
|
||||
expect(rows).toEqual([{ day_id: dayA.id, place_id: placeA.id, stray_km: 1.5, created_at: expect.any(String) }]);
|
||||
});
|
||||
|
||||
it('UPSERTTRACKREPO-002: re-upserting the SAME day_id updates in place — one row, the second call\'s place_id/stray_km, created_at untouched', async () => {
|
||||
const { dayA, placeA, placeB } = fixture();
|
||||
await tracks.upsertTrack(dayA.id, placeA.id, 1.5);
|
||||
const before = rawRows()[0]!;
|
||||
|
||||
await tracks.upsertTrack(dayA.id, placeB.id, 9.25);
|
||||
const after = rawRows();
|
||||
|
||||
// Exactly one row — if `onConflictFields: ['day']` resolved to anything
|
||||
// other than the physical `day_id` PK, the second call would either
|
||||
// throw ("ON CONFLICT clause does not match any PRIMARY KEY or UNIQUE
|
||||
// constraint") or raise a UNIQUE-constraint violation trying to insert
|
||||
// a second row with the same PK. Neither happens here — proof, not
|
||||
// assumption, per the Task 0 review carry.
|
||||
expect(after).toHaveLength(1);
|
||||
expect(after[0]).toEqual({ day_id: dayA.id, place_id: placeB.id, stray_km: 9.25, created_at: before.created_at });
|
||||
});
|
||||
|
||||
it('UPSERTTRACKREPO-003: a track for a different day never touches this one\'s row', async () => {
|
||||
const { trip, dayA, placeA } = fixture();
|
||||
const dayB = createDay(testDb, trip.id);
|
||||
await tracks.upsertTrack(dayA.id, placeA.id, null);
|
||||
await tracks.upsertTrack(dayB.id, placeA.id, null);
|
||||
expect(rawRows()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('UPSERTTRACKREPO-004: the rendered upsert SQL names the physical day_id column as its conflict target', async () => {
|
||||
const { dayA, placeA } = fixture();
|
||||
const connection = t.orm.em.getConnection();
|
||||
const spy = vi.spyOn(connection, 'execute');
|
||||
await tracks.upsertTrack(dayA.id, placeA.id, null);
|
||||
// Read `spy.mock.calls` BEFORE `mockRestore()` — vitest's `mockRestore`
|
||||
// does everything `mockReset` does (clearing recorded calls) in
|
||||
// addition to restoring the original implementation, so a `finally {
|
||||
// spy.mockRestore() }` ahead of this read empties `.calls` first.
|
||||
const calls = [...spy.mock.calls];
|
||||
spy.mockRestore();
|
||||
const upsertCall = calls.find((call) => typeof call[0] === 'string' && call[0].includes('roadtrip_day_tracks') && /insert/i.test(call[0]));
|
||||
expect(upsertCall).toBeDefined();
|
||||
const sql = String(upsertCall![0]);
|
||||
expect(sql).toMatch(/on conflict\s*\(\s*`?day_id`?\s*\)/i);
|
||||
});
|
||||
|
||||
it('RT12REPO-001: listForTrip reads every day-track of the trip, ordered by day, day_id/place_id as bare scalars', async () => {
|
||||
const { trip, dayA, placeA } = fixture();
|
||||
const dayB = createDay(testDb, trip.id);
|
||||
const placeB = createPlace(testDb, trip.id);
|
||||
await tracks.upsertTrack(dayB.id, placeB.id, 2);
|
||||
await tracks.upsertTrack(dayA.id, placeA.id, null);
|
||||
|
||||
const rows = await tracks.listForTrip(trip.id);
|
||||
expect(rows).toEqual([
|
||||
{ day_id: dayA.id, place_id: placeA.id, stray_km: null },
|
||||
{ day_id: dayB.id, place_id: placeB.id, stray_km: 2 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('RT12REPO-002: listForTrip never returns another trip\'s tracks', async () => {
|
||||
const { dayA, placeA } = fixture();
|
||||
const { user: otherUser } = createUser(testDb);
|
||||
const otherTrip = createTrip(testDb, otherUser.id);
|
||||
const otherDay = createDay(testDb, otherTrip.id);
|
||||
const otherPlace = createPlace(testDb, otherTrip.id);
|
||||
await tracks.upsertTrack(dayA.id, placeA.id, null);
|
||||
await tracks.upsertTrack(otherDay.id, otherPlace.id, null);
|
||||
|
||||
const rows = await tracks.listForTrip(otherTrip.id);
|
||||
expect(rows).toEqual([{ day_id: otherDay.id, place_id: otherPlace.id, stray_km: null }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* `RoadtripPreferencesRepository` (Plan 3d Task 1). RPF1 (`listForTrip`) and
|
||||
* RPF3 (`upsertValue`, `ON CONFLICT(trip_id, key) DO UPDATE SET value =
|
||||
* excluded.value`).
|
||||
*/
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
import { createTrip, createUser } from '../../../helpers/factories';
|
||||
import { RoadtripPreferences } from '../../../../src/db/entities/RoadtripPreferences.entity';
|
||||
import type { RoadtripPreferencesRepository } from '../../../../src/db/repositories/RoadtripPreferences.repository';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let repo: RoadtripPreferencesRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
repo = t.repo(RoadtripPreferences);
|
||||
});
|
||||
beforeEach(() => { resetTestDb(testDb); t.clear(); });
|
||||
afterAll(async () => { await t.close(); testDb.close(); });
|
||||
|
||||
describe('RoadtripPreferencesRepository', () => {
|
||||
it('RPF1REPO-001: listForTrip is empty for a trip with no saved preferences', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
expect(await repo.listForTrip(trip.id)).toEqual([]);
|
||||
});
|
||||
|
||||
it('UPSERTPREFREPO-001: upsertValue inserts a fresh (trip, key) pair', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
await repo.upsertValue(trip.id, 'roadtrip_range_km', '100');
|
||||
expect(await repo.listForTrip(trip.id)).toEqual([{ key: 'roadtrip_range_km', value: '100' }]);
|
||||
});
|
||||
|
||||
it('UPSERTPREFREPO-002: re-upserting the SAME (trip, key) replaces the value in place — one row', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
await repo.upsertValue(trip.id, 'roadtrip_range_km', '100');
|
||||
await repo.upsertValue(trip.id, 'roadtrip_range_km', '250');
|
||||
const rows = await repo.listForTrip(trip.id);
|
||||
expect(rows).toEqual([{ key: 'roadtrip_range_km', value: '250' }]);
|
||||
});
|
||||
|
||||
it('UPSERTPREFREPO-003: two different keys on the same trip coexist as two rows', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
await repo.upsertValue(trip.id, 'roadtrip_range_km', '100');
|
||||
await repo.upsertValue(trip.id, 'roadtrip_vehicle', '"electric"');
|
||||
const rows = await repo.listForTrip(trip.id);
|
||||
expect(rows.map((r) => r.key).sort()).toEqual(['roadtrip_range_km', 'roadtrip_vehicle']);
|
||||
});
|
||||
|
||||
it('UPSERTPREFREPO-004: the same key on two different trips is two independent rows', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const tripA = createTrip(testDb, user.id);
|
||||
const tripB = createTrip(testDb, user.id);
|
||||
await repo.upsertValue(tripA.id, 'roadtrip_range_km', '100');
|
||||
await repo.upsertValue(tripB.id, 'roadtrip_range_km', '999');
|
||||
expect(await repo.listForTrip(tripA.id)).toEqual([{ key: 'roadtrip_range_km', value: '100' }]);
|
||||
expect(await repo.listForTrip(tripB.id)).toEqual([{ key: 'roadtrip_range_km', value: '999' }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* `RoadtripViasRepository` (Plan 3d Task 1). RT2 (`listForDay`, the ONE copy
|
||||
* — `AccommodationsService`/`AssignmentsService` both consume it now), RT3
|
||||
* (`listForTrip`), RT4/RT10 (`nextSequence`), RT5/RT11 (`insertVia`), RT9
|
||||
* (`deleteLeg`), RT14 (`existsInDay`), RT15/RT16 (`moveCoordinates`/
|
||||
* `moveCoordinatesAndAnchor`), RT18 (`listAnchors`), RT19/RT23
|
||||
* (`deleteInDay`/`deleteInDayCounted`), RT20 (`setAnchor`), RT21
|
||||
* (`listLegs`), RT22 (`setSequence`), RT24 (`findById`), AS20
|
||||
* (`listForReanchor`).
|
||||
*/
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
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 { RoadtripVias } from '../../../../src/db/entities/RoadtripVias.entity';
|
||||
import type { RoadtripViasRepository } from '../../../../src/db/repositories/RoadtripVias.repository';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let vias: RoadtripViasRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
vias = t.repo(RoadtripVias);
|
||||
});
|
||||
beforeEach(() => { resetTestDb(testDb); t.clear(); });
|
||||
afterAll(async () => { await t.close(); testDb.close(); });
|
||||
|
||||
function fixture() {
|
||||
const { user } = createUser(testDb);
|
||||
const tripA = createTrip(testDb, user.id);
|
||||
const tripB = createTrip(testDb, user.id);
|
||||
const dayA1 = createDay(testDb, tripA.id);
|
||||
const dayA2 = createDay(testDb, tripA.id);
|
||||
const dayB1 = createDay(testDb, tripB.id);
|
||||
return { tripA, tripB, dayA1, dayA2, dayB1 };
|
||||
}
|
||||
|
||||
describe('RoadtripViasRepository', () => {
|
||||
it('RT5REPO-001: insertVia writes every column and returns the new id', async () => {
|
||||
const { dayA1 } = fixture();
|
||||
const id = await vias.insertVia({ day_id: dayA1.id, after_order_index: 0, sequence: 0, lat: 53.1, lng: 10.2 });
|
||||
const row = await vias.findById(id);
|
||||
expect(row).toEqual({ id, day_id: dayA1.id, after_order_index: 0, sequence: 0, lat: 53.1, lng: 10.2, created_at: expect.any(String) });
|
||||
});
|
||||
|
||||
it('RT24REPO-001: findById on a missing id is null', async () => {
|
||||
expect(await vias.findById(999999)).toBeNull();
|
||||
});
|
||||
|
||||
it('RT2REPO-001: listForDay orders by after_order_index, sequence, id and is scoped to the day', async () => {
|
||||
const { dayA1, dayA2 } = fixture();
|
||||
const b = await vias.insertVia({ day_id: dayA1.id, after_order_index: 1, sequence: 0, lat: 1, lng: 1 });
|
||||
const a1 = await vias.insertVia({ day_id: dayA1.id, after_order_index: 0, sequence: 1, lat: 1, lng: 1 });
|
||||
const a0 = await vias.insertVia({ day_id: dayA1.id, after_order_index: 0, sequence: 0, lat: 1, lng: 1 });
|
||||
await vias.insertVia({ day_id: dayA2.id, after_order_index: 0, sequence: 0, lat: 1, lng: 1 });
|
||||
|
||||
const rows = await vias.listForDay(dayA1.id);
|
||||
expect(rows.map((v) => v.id)).toEqual([a0, a1, b]);
|
||||
});
|
||||
|
||||
it('RT3REPO-001: listForTrip spans every day of the trip, ordered by day/after_order_index/sequence/id, and never crosses trips', async () => {
|
||||
const { tripA, tripB, dayA1, dayA2, dayB1 } = fixture();
|
||||
const v2 = await vias.insertVia({ day_id: dayA2.id, after_order_index: 0, sequence: 0, lat: 2, lng: 2 });
|
||||
const v1 = await vias.insertVia({ day_id: dayA1.id, after_order_index: 0, sequence: 0, lat: 1, lng: 1 });
|
||||
await vias.insertVia({ day_id: dayB1.id, after_order_index: 0, sequence: 0, lat: 3, lng: 3 });
|
||||
|
||||
const rows = await vias.listForTrip(tripA.id);
|
||||
expect(rows).toEqual([
|
||||
{ id: v1, day_id: dayA1.id, after_order_index: 0, sequence: 0, lat: 1, lng: 1, created_at: expect.any(String) },
|
||||
{ id: v2, day_id: dayA2.id, after_order_index: 0, sequence: 0, lat: 2, lng: 2, created_at: expect.any(String) },
|
||||
]);
|
||||
expect((await vias.listForTrip(tripB.id)).length).toBe(1);
|
||||
});
|
||||
|
||||
it('RT4REPO-001: nextSequence is 0 for an empty leg, and MAX+1 for a populated one', async () => {
|
||||
const { dayA1 } = fixture();
|
||||
expect(await vias.nextSequence(dayA1.id, 0)).toBe(0);
|
||||
await vias.insertVia({ day_id: dayA1.id, after_order_index: 0, sequence: 0, lat: 1, lng: 1 });
|
||||
await vias.insertVia({ day_id: dayA1.id, after_order_index: 0, sequence: 3, lat: 1, lng: 1 });
|
||||
expect(await vias.nextSequence(dayA1.id, 0)).toBe(4);
|
||||
// A different leg on the same day starts fresh.
|
||||
expect(await vias.nextSequence(dayA1.id, 1)).toBe(0);
|
||||
});
|
||||
|
||||
it('RT9REPO-001: deleteLeg removes only the named leg’s vias', async () => {
|
||||
const { dayA1 } = fixture();
|
||||
const keep = await vias.insertVia({ day_id: dayA1.id, after_order_index: 1, sequence: 0, lat: 1, lng: 1 });
|
||||
await vias.insertVia({ day_id: dayA1.id, after_order_index: 0, sequence: 0, lat: 1, lng: 1 });
|
||||
|
||||
await vias.deleteLeg(dayA1.id, 0);
|
||||
|
||||
const rows = await vias.listForDay(dayA1.id);
|
||||
expect(rows.map((v) => v.id)).toEqual([keep]);
|
||||
});
|
||||
|
||||
it('RT14REPO-001: existsInDay is true only for the exact (id, day) pair', async () => {
|
||||
const { dayA1, dayA2 } = fixture();
|
||||
const id = await vias.insertVia({ day_id: dayA1.id, after_order_index: 0, sequence: 0, lat: 1, lng: 1 });
|
||||
expect(await vias.existsInDay(id, dayA1.id)).toBe(true);
|
||||
expect(await vias.existsInDay(id, dayA2.id)).toBe(false);
|
||||
expect(await vias.existsInDay(999999, dayA1.id)).toBe(false);
|
||||
});
|
||||
|
||||
it('RT15REPO-001: moveCoordinates writes lat/lng only, unscoped by day (matches the legacy statement exactly)', async () => {
|
||||
const { dayA1, dayA2 } = fixture();
|
||||
const id = await vias.insertVia({ day_id: dayA1.id, after_order_index: 3, sequence: 0, lat: 1, lng: 1 });
|
||||
await vias.moveCoordinates(id, 9, 9);
|
||||
const row = await vias.findById(id);
|
||||
expect(row).toMatchObject({ lat: 9, lng: 9, after_order_index: 3, day_id: dayA1.id });
|
||||
expect(dayA2.id).not.toBe(dayA1.id);
|
||||
});
|
||||
|
||||
it('RT16REPO-001: moveCoordinatesAndAnchor writes lat/lng/after_order_index, unscoped by day', async () => {
|
||||
const { dayA1 } = fixture();
|
||||
const id = await vias.insertVia({ day_id: dayA1.id, after_order_index: 0, sequence: 0, lat: 1, lng: 1 });
|
||||
await vias.moveCoordinatesAndAnchor(id, 9, 9, 5);
|
||||
expect(await vias.findById(id)).toMatchObject({ lat: 9, lng: 9, after_order_index: 5 });
|
||||
});
|
||||
|
||||
it('RT18REPO-001: listAnchors returns id/after_order_index/sequence for the day only', async () => {
|
||||
const { dayA1, dayA2 } = fixture();
|
||||
const id = await vias.insertVia({ day_id: dayA1.id, after_order_index: 2, sequence: 1, lat: 1, lng: 1 });
|
||||
await vias.insertVia({ day_id: dayA2.id, after_order_index: 0, sequence: 0, lat: 1, lng: 1 });
|
||||
|
||||
const rows = await vias.listAnchors(dayA1.id);
|
||||
expect(rows).toEqual([{ id, after_order_index: 2, sequence: 1 }]);
|
||||
});
|
||||
|
||||
it('RT21REPO-001: listLegs returns id/after_order_index only, for the day', async () => {
|
||||
const { dayA1 } = fixture();
|
||||
const id = await vias.insertVia({ day_id: dayA1.id, after_order_index: 2, sequence: 1, lat: 1, lng: 1 });
|
||||
expect(await vias.listLegs(dayA1.id)).toEqual([{ id, after_order_index: 2 }]);
|
||||
});
|
||||
|
||||
it('RT19REPO-001/RT23REPO-001: deleteInDay is silent, deleteInDayCounted reports the row count (0 on a miss)', async () => {
|
||||
const { dayA1, dayA2 } = fixture();
|
||||
const id = await vias.insertVia({ day_id: dayA1.id, after_order_index: 0, sequence: 0, lat: 1, lng: 1 });
|
||||
|
||||
// A foreign day scope never deletes.
|
||||
expect(await vias.deleteInDayCounted(id, dayA2.id)).toBe(0);
|
||||
expect(await vias.findById(id)).not.toBeNull();
|
||||
|
||||
await expect(vias.deleteInDay(999999, dayA1.id)).resolves.toBeUndefined();
|
||||
|
||||
expect(await vias.deleteInDayCounted(id, dayA1.id)).toBe(1);
|
||||
expect(await vias.findById(id)).toBeNull();
|
||||
expect(await vias.deleteInDayCounted(id, dayA1.id)).toBe(0);
|
||||
});
|
||||
|
||||
it('RT20REPO-001: setAnchor writes after_order_index only, scoped to (id, day)', async () => {
|
||||
const { dayA1, dayA2 } = fixture();
|
||||
const id = await vias.insertVia({ day_id: dayA1.id, after_order_index: 0, sequence: 0, lat: 1, lng: 1 });
|
||||
await vias.setAnchor(id, dayA2.id, 9);
|
||||
expect((await vias.findById(id))?.after_order_index).toBe(0);
|
||||
await vias.setAnchor(id, dayA1.id, 9);
|
||||
expect((await vias.findById(id))?.after_order_index).toBe(9);
|
||||
});
|
||||
|
||||
it('RT22REPO-001: setSequence writes sequence only, scoped to (id, day)', async () => {
|
||||
const { dayA1 } = fixture();
|
||||
const id = await vias.insertVia({ day_id: dayA1.id, after_order_index: 0, sequence: 0, lat: 1, lng: 1 });
|
||||
await vias.setSequence(id, dayA1.id, 7);
|
||||
expect((await vias.findById(id))?.sequence).toBe(7);
|
||||
});
|
||||
|
||||
it('AS20REPO-001: listForReanchor returns id/after_order_index/lat/lng, the AnchoredVia shape', async () => {
|
||||
const { dayA1 } = fixture();
|
||||
const id = await vias.insertVia({ day_id: dayA1.id, after_order_index: 1, sequence: 0, lat: 12.5, lng: -3.2 });
|
||||
expect(await vias.listForReanchor(dayA1.id)).toEqual([{ id, after_order_index: 1, lat: 12.5, lng: -3.2 }]);
|
||||
});
|
||||
});
|
||||
@@ -58,7 +58,7 @@ import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repos
|
||||
import {
|
||||
createTestUnitOfWork, createTestAppSettingsRepo, createTestTagsRepo, createTestPlaceRatingsRepo,
|
||||
createTestAssignmentParticipantsRepo, createTestDayAssignmentsRepo, createTestDaysRepo, createTestPlacesRepo,
|
||||
createTestTripMembersRepo, createTestDatabaseService,
|
||||
createTestTripMembersRepo, createTestDatabaseService, createTestRoadtripViasRepo,
|
||||
} from '../../helpers/test-uow';
|
||||
|
||||
let svc: AssignmentsService;
|
||||
@@ -84,6 +84,7 @@ beforeAll(async () => {
|
||||
await createTestDaysRepo(dbs.connection),
|
||||
await createTestPlacesRepo(dbs.connection),
|
||||
await createTestTripMembersRepo(dbs.connection),
|
||||
await createTestRoadtripViasRepo(dbs.connection),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -42,11 +42,11 @@ describe('Open charging data', () => {
|
||||
expect(matchChargingLocation([station], 48, 11, 'Test')).toEqual(station);
|
||||
});
|
||||
it('checks trip/place scope and ignores non-charging places', async () => {
|
||||
const get = vi.fn().mockReturnValueOnce(null).mockReturnValueOnce({ name: 'Hotel', lat: 48, lng: 11, stop_type: 'hotel' });
|
||||
const service = new ChargingService({ get } as never);
|
||||
const findChargingProbe = vi.fn().mockResolvedValueOnce(undefined).mockResolvedValueOnce({ name: 'Hotel', lat: 48, lng: 11, stop_type: 'hotel' });
|
||||
const service = new ChargingService({ findChargingProbe } as never);
|
||||
await expect(service.read(1, 2)).rejects.toThrow();
|
||||
expect((await service.read(1, 2)).status).toBe('unknown');
|
||||
expect(get).toHaveBeenCalledWith(expect.stringContaining('trip_id = ?'), 2, 1);
|
||||
expect(findChargingProbe).toHaveBeenCalledWith(2, 1);
|
||||
});
|
||||
it('coalesces station requests and preserves availability if tariffs fail', async () => {
|
||||
const fetcher = vi.fn(async (url: string) => {
|
||||
@@ -55,7 +55,7 @@ describe('Open charging data', () => {
|
||||
return new Response('', { status: 503 });
|
||||
});
|
||||
vi.stubGlobal('fetch', fetcher);
|
||||
const service = new ChargingService({ get: () => ({ name: 'Test', lat: 48, lng: 11, stop_type: 'charging' }) } as never);
|
||||
const service = new ChargingService({ findChargingProbe: async () => ({ name: 'Test', lat: 48, lng: 11, stop_type: 'charging' }) } as never);
|
||||
const [first, second] = await Promise.all([service.read(1, 2), service.read(1, 2)]);
|
||||
expect(first).toEqual(second);
|
||||
expect(first.status).toBe('ok');
|
||||
@@ -94,7 +94,7 @@ describe('Open charging data before the stop exists', () => {
|
||||
it('answers for a coordinate and lets the saved stop reuse that answer', async () => {
|
||||
const fetcher = answers({ items: [tariff], total_count: 1 });
|
||||
vi.stubGlobal('fetch', fetcher);
|
||||
const service = new ChargingService({ get: () => ({ name: 'Test', lat: 48, lng: 11, stop_type: 'charging' }) } as never);
|
||||
const service = new ChargingService({ findChargingProbe: async () => ({ name: 'Test', lat: 48, lng: 11, stop_type: 'charging' }) } as never);
|
||||
|
||||
const ahead = await service.lookup(48, 11, 'Test');
|
||||
expect(ahead.status).toBe('ok');
|
||||
@@ -114,35 +114,35 @@ describe('Open charging data before the stop exists', () => {
|
||||
if (url.includes('/sources')) return new Response(JSON.stringify({ items: [source] }));
|
||||
return new Response(JSON.stringify({ items: [station, { ...station, id: 'other', operator: { name: 'Other' } }], total_count: 2 }));
|
||||
}));
|
||||
const info = await new ChargingService({ get: () => null } as never).lookup(48, 11, 'Charging');
|
||||
const info = await new ChargingService({ findChargingProbe: async () => undefined } as never).lookup(48, 11, 'Charging');
|
||||
expect(info.status).toBe('ambiguous');
|
||||
expect(info.available).toBeNull();
|
||||
});
|
||||
|
||||
it('turns an unreachable source into an empty answer, not a failed request', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response('', { status: 503 })));
|
||||
const info = await new ChargingService({ get: () => null } as never).lookup(48, 11, 'Test');
|
||||
const info = await new ChargingService({ findChargingProbe: async () => undefined } as never).lookup(48, 11, 'Test');
|
||||
expect(info).toEqual({ ...empty('unavailable'), checkedAt: info.checkedAt });
|
||||
});
|
||||
|
||||
it('does not go to the database for a station that is not in it', async () => {
|
||||
vi.stubGlobal('fetch', answers({ items: [], total_count: 0 }));
|
||||
const get = vi.fn();
|
||||
await new ChargingService({ get } as never).lookup(48, 11, 'Test');
|
||||
expect(get).not.toHaveBeenCalled();
|
||||
const findChargingProbe = vi.fn();
|
||||
await new ChargingService({ findChargingProbe } as never).lookup(48, 11, 'Test');
|
||||
expect(findChargingProbe).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('serves the route and the MCP tool from one contract and one access check', async () => {
|
||||
const charging = { read: vi.fn(), lookup: vi.fn(async () => empty('unknown')) };
|
||||
const db = { canAccessTrip: vi.fn(async () => false) };
|
||||
const tool = new ChargingMcp(charging as never, db as never, {} as never);
|
||||
const tripsRepo = { findAccessible: vi.fn(async () => false) };
|
||||
const tool = new ChargingMcp(charging as never, tripsRepo as never, {} as never);
|
||||
const input = { lat: 48.1, lng: 11.5, name: 'Ladepark Nord' };
|
||||
|
||||
// A trip the caller cannot reach is refused before anything is fetched, exactly as
|
||||
// TripAccessGuard refuses it on the route.
|
||||
expect((await tool.lookup({ tripId: 3, ...input }, { userId: 5 } as never)).isError).toBe(true);
|
||||
expect(charging.lookup).not.toHaveBeenCalled();
|
||||
db.canAccessTrip.mockResolvedValue(true);
|
||||
tripsRepo.findAccessible.mockResolvedValue(true);
|
||||
await tool.lookup({ tripId: 3, ...input }, { userId: 5 } as never);
|
||||
await new ChargingLookupController(charging as never).lookup(input as unknown as ChargingLookupDto);
|
||||
|
||||
|
||||
@@ -1,82 +1,125 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
/**
|
||||
* `DayBoundariesService`/`DayBoundariesController`/`DayBoundariesMcp` (Plan
|
||||
* 3d Task 1). Rewritten off the hand-DDL `DatabaseService`-shaped facade
|
||||
* (§15a/§15c test risk 2) onto real rows through `DayAssignmentsRepository`/
|
||||
* `RoadtripDayBoundariesRepository` — the real schema, not a 4-column
|
||||
* hand-written subset.
|
||||
*/
|
||||
import { afterAll, beforeAll, beforeEach, expect, it, vi } from 'vitest';
|
||||
import { HttpException } from '@nestjs/common';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { createDay, createDayAssignment, createPlace, createTrip, createUser } from '../../helpers/factories';
|
||||
import { DayBoundariesService } from '../../../src/nest/roadtrip/day-boundaries.service';
|
||||
import { DayBoundariesController } from '../../../src/nest/roadtrip/day-boundaries.controller';
|
||||
import { DayBoundariesMcp } from '../../../src/nest/roadtrip/day-boundaries.mcp';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { DayAssignments } from '../../../src/db/entities/DayAssignments.entity';
|
||||
import { RoadtripDayBoundaries } from '../../../src/db/entities/RoadtripDayBoundaries.entity';
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
|
||||
const open: Database.Database[] = [];
|
||||
afterEach(() => open.splice(0).forEach(db => db.close()));
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
beforeAll(async () => { t = await createTestOrm(testDb); });
|
||||
beforeEach(() => { resetTestDb(testDb); t.clear(); });
|
||||
afterAll(async () => { await t.close(); testDb.close(); });
|
||||
|
||||
function setup() {
|
||||
const raw = new Database(':memory:');
|
||||
open.push(raw);
|
||||
raw.pragma('foreign_keys = ON');
|
||||
raw.exec(`CREATE TABLE days (id INTEGER PRIMARY KEY, trip_id INTEGER);
|
||||
CREATE TABLE day_assignments (id INTEGER PRIMARY KEY, day_id INTEGER REFERENCES days(id) ON DELETE CASCADE);
|
||||
CREATE TABLE roadtrip_day_boundaries (trip_id INTEGER, day_number INTEGER, from_assignment_id INTEGER REFERENCES day_assignments(id) ON DELETE CASCADE,
|
||||
to_assignment_id INTEGER REFERENCES day_assignments(id) ON DELETE CASCADE, fraction REAL, PRIMARY KEY(trip_id, day_number));
|
||||
INSERT INTO days VALUES (1, 10), (2, 20);
|
||||
INSERT INTO day_assignments VALUES (11, 1), (12, 1), (21, 2);`);
|
||||
const db = {
|
||||
get: (sql: string, ...params: unknown[]) => raw.prepare(sql).get(...params),
|
||||
all: (sql: string, ...params: unknown[]) => raw.prepare(sql).all(...params),
|
||||
run: (sql: string, ...params: unknown[]) => raw.prepare(sql).run(...params),
|
||||
canAccessTrip: vi.fn(async () => true),
|
||||
};
|
||||
const service = new DayBoundariesService(db as unknown as DatabaseService);
|
||||
const { user } = createUser(testDb);
|
||||
const tripA = createTrip(testDb, user.id);
|
||||
const tripB = createTrip(testDb, user.id);
|
||||
const dayA = createDay(testDb, tripA.id);
|
||||
const dayB = createDay(testDb, tripB.id);
|
||||
const placeA = createPlace(testDb, tripA.id);
|
||||
const placeB = createPlace(testDb, tripB.id);
|
||||
const from = createDayAssignment(testDb, dayA.id, placeA.id);
|
||||
const to = createDayAssignment(testDb, dayA.id, placeA.id);
|
||||
const foreign = createDayAssignment(testDb, dayB.id, placeB.id);
|
||||
|
||||
const dayAssignmentsRepo = t.repo(DayAssignments);
|
||||
const boundariesRepo = t.repo(RoadtripDayBoundaries);
|
||||
const service = new DayBoundariesService(dayAssignmentsRepo, boundariesRepo);
|
||||
const realtime = { broadcast: vi.fn() };
|
||||
const auth = { isDemoUser: vi.fn(() => false) };
|
||||
const guards = { hasTripPermission: vi.fn(() => true) };
|
||||
const mcp = new DayBoundariesMcp(service, db as unknown as DatabaseService, auth as never, guards as never, realtime as never, {} as never);
|
||||
return { raw, service, controller: new DayBoundariesController(service, realtime as never), mcp, db, auth, guards, realtime };
|
||||
const tripsRepo = { findAccessible: vi.fn(async () => ({ id: tripA.id, user_id: user.id })) };
|
||||
const mcp = new DayBoundariesMcp(service, tripsRepo as never, auth as never, guards as never, realtime as never, {} as never);
|
||||
return {
|
||||
service,
|
||||
controller: new DayBoundariesController(service, realtime as never),
|
||||
mcp,
|
||||
tripsRepo,
|
||||
auth,
|
||||
guards,
|
||||
realtime,
|
||||
tripA,
|
||||
tripB,
|
||||
fromId: from.id,
|
||||
toId: to.id,
|
||||
foreignId: foreign.id,
|
||||
};
|
||||
}
|
||||
const boundary = { day_number: 1, from_assignment_id: 11, to_assignment_id: 12, fraction: 0.4 };
|
||||
|
||||
it('replaces one day only, persists place snapping and cascades deleted visits', async () => {
|
||||
const { service, raw } = setup();
|
||||
await service.save(10, boundary);
|
||||
await service.save(10, { ...boundary, day_number: 2, fraction: 0.8 });
|
||||
expect(await service.save(10, { ...boundary, to_assignment_id: null })).toEqual([
|
||||
const { service, tripA, tripB, fromId, toId } = setup();
|
||||
const boundary = { day_number: 1, from_assignment_id: fromId, to_assignment_id: toId, fraction: 0.4 };
|
||||
await service.save(tripA.id, boundary);
|
||||
await service.save(tripA.id, { ...boundary, day_number: 2, fraction: 0.8 });
|
||||
expect(await service.save(tripA.id, { ...boundary, to_assignment_id: null })).toEqual([
|
||||
{ ...boundary, to_assignment_id: null, fraction: 1 }, { ...boundary, day_number: 2, fraction: 0.8 },
|
||||
]);
|
||||
expect(await service.list(20)).toEqual([]);
|
||||
await service.remove(20, 1);
|
||||
expect(await service.list(10)).toHaveLength(2);
|
||||
raw.prepare('DELETE FROM day_assignments WHERE id = 12').run();
|
||||
expect(await service.list(10)).toEqual([{ ...boundary, to_assignment_id: null, fraction: 1 }]);
|
||||
expect(await service.list(tripB.id)).toEqual([]);
|
||||
await service.remove(tripB.id, 1);
|
||||
expect(await service.list(tripA.id)).toHaveLength(2);
|
||||
testDb.prepare('DELETE FROM day_assignments WHERE id = ?').run(toId);
|
||||
expect(await service.list(tripA.id)).toEqual([{ ...boundary, to_assignment_id: null, fraction: 1 }]);
|
||||
});
|
||||
|
||||
it('rejects either endpoint from a different trip without writing', async () => {
|
||||
const { service } = setup();
|
||||
await expect(service.save(10, { ...boundary, from_assignment_id: 21 })).rejects.toThrow(HttpException);
|
||||
await expect(service.save(10, { ...boundary, to_assignment_id: 21 })).rejects.toThrow(HttpException);
|
||||
expect(await service.list(10)).toEqual([]);
|
||||
it('rejects either endpoint from a different trip without writing (RB2)', async () => {
|
||||
const { service, tripA, fromId, foreignId } = setup();
|
||||
const boundary = { day_number: 1, from_assignment_id: fromId, to_assignment_id: foreignId, fraction: 0.4 };
|
||||
await expect(service.save(tripA.id, { ...boundary, from_assignment_id: foreignId })).rejects.toThrow(HttpException);
|
||||
await expect(service.save(tripA.id, boundary)).rejects.toThrow(HttpException);
|
||||
expect(await service.list(tripA.id)).toEqual([]);
|
||||
});
|
||||
|
||||
it('RB2 (`belongs`): a foreign `to_assignment_id` is refused with the exact legacy message', async () => {
|
||||
// The async-closure-truthiness-guards ratchet
|
||||
// (`tests/integration/async-closure-truthiness-guards.test.ts`, RB2-001)
|
||||
// drives the real route end to end and is mutation-proved there (Task 0's
|
||||
// report: dropping the `await` on `belongs` turns a 404 into a 200). This
|
||||
// unit case pins the exact error string at the service boundary.
|
||||
const { service, tripA, fromId, foreignId } = setup();
|
||||
await expect(
|
||||
service.save(tripA.id, { day_number: 1, from_assignment_id: fromId, to_assignment_id: foreignId, fraction: 0.4 }),
|
||||
).rejects.toMatchObject({ response: { error: 'Stop not found' }, status: 404 });
|
||||
});
|
||||
|
||||
it('REST changes broadcast the complete state and exclude the saving socket', async () => {
|
||||
const { controller, realtime } = setup();
|
||||
await controller.save('10', boundary, 'self');
|
||||
expect(realtime.broadcast).toHaveBeenCalledWith('10', 'roadtripBoundary:changed', { boundaries: [boundary] }, 'self');
|
||||
expect(await controller.remove('10', 1)).toEqual({ boundaries: [] });
|
||||
const { controller, realtime, tripA, fromId, toId } = setup();
|
||||
const boundary = { day_number: 1, from_assignment_id: fromId, to_assignment_id: toId, fraction: 0.4 };
|
||||
await controller.save(String(tripA.id), boundary, 'self');
|
||||
expect(realtime.broadcast).toHaveBeenCalledWith(String(tripA.id), 'roadtripBoundary:changed', { boundaries: [boundary] }, 'self');
|
||||
expect(await controller.remove(String(tripA.id), 1)).toEqual({ boundaries: [] });
|
||||
});
|
||||
|
||||
it('MCP checks demo, trip access and edit permission before saving', async () => {
|
||||
const s = setup(), ctx = { userId: 1 } as McpContext;
|
||||
const request = { tripId: 10, dayNumber: 1, boundary };
|
||||
const s = setup();
|
||||
const ctx = { userId: 1 } as McpContext;
|
||||
const boundary = { day_number: 1, from_assignment_id: s.fromId, to_assignment_id: s.toId, fraction: 0.4 };
|
||||
const request = { tripId: s.tripA.id, dayNumber: 1, boundary };
|
||||
s.auth.isDemoUser.mockReturnValue(true);
|
||||
await s.mcp.save(request, ctx);
|
||||
s.auth.isDemoUser.mockReturnValue(false);
|
||||
s.db.canAccessTrip.mockResolvedValue(false);
|
||||
s.tripsRepo.findAccessible.mockResolvedValue(undefined);
|
||||
await s.mcp.save(request, ctx);
|
||||
s.db.canAccessTrip.mockResolvedValue(true);
|
||||
s.tripsRepo.findAccessible.mockResolvedValue({ id: s.tripA.id, user_id: 1 });
|
||||
s.guards.hasTripPermission.mockReturnValue(false);
|
||||
await s.mcp.save(request, ctx);
|
||||
expect(await s.service.list(10)).toEqual([]);
|
||||
expect(await s.service.list(s.tripA.id)).toEqual([]);
|
||||
s.guards.hasTripPermission.mockReturnValue(true);
|
||||
await s.mcp.save(request, ctx);
|
||||
expect(await s.service.list(10)).toEqual([boundary]);
|
||||
expect(await s.service.list(s.tripA.id)).toEqual([boundary]);
|
||||
await s.mcp.save({ ...request, boundary: null }, ctx);
|
||||
expect(await s.service.list(10)).toEqual([]);
|
||||
expect(await s.service.list(s.tripA.id)).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -12,12 +12,21 @@ const routeTestDb = new Database(':memory:');
|
||||
|
||||
async function setup() {
|
||||
const maps = { geocodeQuery: vi.fn(), reverseGeocode: vi.fn().mockResolvedValue({ name: null, address: null }) };
|
||||
const db = { canAccessTrip: vi.fn(async () => ({ user_id: 7 })), get: () => ({ role: 'user' }) };
|
||||
const tripsRepo = { findAccessible: vi.fn(async () => ({ user_id: 7 })) };
|
||||
const usersRepo = { getRole: vi.fn(async () => 'user') };
|
||||
const places = { create: vi.fn((_trip: string, stop: { name: string }) => ({ id: stop.name })), broadcast: vi.fn() };
|
||||
const assignments = { dayExists: vi.fn(() => true), createAssignment: vi.fn((dayId: number, placeId: string) => ({ dayId, placeId })), broadcast: vi.fn(), reconcile: vi.fn() };
|
||||
const permissions = { checkPermission: vi.fn(() => true) };
|
||||
const service = new GoogleRouteService(maps as never, db as never, places as never, assignments as never, permissions as never, await createTestUnitOfWork(routeTestDb));
|
||||
return { service, maps, db, places, assignments, permissions };
|
||||
const service = new GoogleRouteService(
|
||||
maps as never,
|
||||
places as never,
|
||||
assignments as never,
|
||||
permissions as never,
|
||||
await createTestUnitOfWork(routeTestDb),
|
||||
tripsRepo as never,
|
||||
usersRepo as never,
|
||||
);
|
||||
return { service, maps, tripsRepo, usersRepo, places, assignments, permissions };
|
||||
}
|
||||
|
||||
const input = { dayId: 3, stops: [{ name: 'Munich', lat: 48, lng: 11 }, { name: 'Rome', lat: 41, lng: 12 }] };
|
||||
@@ -67,8 +76,8 @@ describe('Google route import', () => {
|
||||
});
|
||||
|
||||
it('checks membership, both editing permissions and the target day before writing', async () => {
|
||||
const { service, db, permissions, assignments, places } = await setup();
|
||||
db.canAccessTrip.mockResolvedValueOnce(null as never);
|
||||
const { service, tripsRepo, permissions, assignments, places } = await setup();
|
||||
tripsRepo.findAccessible.mockResolvedValueOnce(undefined as never);
|
||||
await expect(service.import(1, 7, input)).rejects.toThrow();
|
||||
permissions.checkPermission.mockReturnValueOnce(false);
|
||||
await expect(service.import(1, 7, input)).rejects.toThrow();
|
||||
|
||||
@@ -6,11 +6,10 @@
|
||||
* column the statement never selects would go unnoticed there. These run the statement.
|
||||
*/
|
||||
import { db } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { RoadtripPlanService } from '../../../src/nest/roadtrip/roadtrip-plan.service';
|
||||
import { createDay, createDayAssignment, createPlace, createTrip, createUser } from '../../helpers/factories';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { sharedTestOrm } from '../../helpers/test-uow';
|
||||
import { createTestTripsRepo, createTestDaysRepo, createTestDayAssignmentsRepo } from '../../helpers/test-uow';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
@@ -51,12 +50,14 @@ async function setup() {
|
||||
});
|
||||
db.prepare("UPDATE day_assignments SET assignment_time = '09:00' WHERE id = ?").run(visits[0].id);
|
||||
const plans = new RoadtripPlanService(
|
||||
new DatabaseService(db, (await sharedTestOrm(db)).em),
|
||||
{ getUserSettings: () => ({}) } as never,
|
||||
{ read: () => ({}) } as never,
|
||||
hourlyRouter() as never,
|
||||
{ listForTrip: () => [], tracksForTrip: () => [] } as never,
|
||||
{ list: () => [] } as never,
|
||||
await createTestTripsRepo(db),
|
||||
await createTestDaysRepo(db),
|
||||
await createTestDayAssignmentsRepo(db),
|
||||
);
|
||||
return { user, trip, visits, plans };
|
||||
}
|
||||
|
||||
@@ -35,13 +35,13 @@ function setup() {
|
||||
const realtime = { broadcast: vi.fn() };
|
||||
const tripSettings = new Map<number, Record<string, unknown>>([[10, { ...settings }]]);
|
||||
const preferenceDb = {
|
||||
all: (_sql: string, tripId: number) =>
|
||||
listForTrip: (tripId: number) =>
|
||||
Object.entries(tripSettings.get(tripId) ?? {}).map(([key, value]) => ({ key, value: JSON.stringify(value) })),
|
||||
run: vi.fn((_sql: string, tripId: number, key: string, value: string) =>
|
||||
upsertValue: vi.fn((tripId: number, key: string, value: string) =>
|
||||
tripSettings.set(tripId, { ...tripSettings.get(tripId), [key]: JSON.parse(value) }),
|
||||
),
|
||||
};
|
||||
const preferences = new RoadtripPreferencesService(preferenceDb as never, realtime as never, uowStub);
|
||||
const preferences = new RoadtripPreferencesService(realtime as never, uowStub, preferenceDb as never);
|
||||
const days = [{ id: 1, day_number: 1, title: null, date: '2026-09-11', default_transport_mode: 'driving' }];
|
||||
const visits = [1, 2, 3].map((id) => ({
|
||||
id,
|
||||
@@ -58,10 +58,9 @@ function setup() {
|
||||
stop_type: null,
|
||||
fill_percent: null,
|
||||
}));
|
||||
const db = {
|
||||
canAccessTrip: vi.fn(async () => true),
|
||||
all: vi.fn((sql: string) => (sql.includes('FROM day_assignments') ? visits : days)),
|
||||
};
|
||||
const tripsRepo = { findAccessible: vi.fn(async () => true) };
|
||||
const daysRepo = { listPlanDays: vi.fn(async () => days) };
|
||||
const dayAssignmentsRepo = { listRoadtripVisits: vi.fn(async () => visits) };
|
||||
const router = {
|
||||
profiles: () => ['driving'],
|
||||
route: vi.fn(async (_user: number, _trip: number, _day: number, points: { lat: number; lng: number }[]) => ({
|
||||
@@ -87,14 +86,16 @@ function setup() {
|
||||
const roadtrip = { listForTrip: vi.fn(() => []), tracksForTrip: vi.fn(() => []) };
|
||||
const boundaries = { list: vi.fn(() => []) };
|
||||
const plans = new RoadtripPlanService(
|
||||
db as never,
|
||||
store as never,
|
||||
preferences,
|
||||
router as never,
|
||||
roadtrip as never,
|
||||
boundaries as never,
|
||||
tripsRepo as never,
|
||||
daysRepo as never,
|
||||
dayAssignmentsRepo as never,
|
||||
);
|
||||
return { preferenceDb, preferences, store, realtime, db, plans, router, visits, days, boundaries };
|
||||
return { preferenceDb, preferences, store, realtime, tripsRepo, daysRepo, dayAssignmentsRepo, plans, router, visits, days, boundaries };
|
||||
}
|
||||
|
||||
describe('roadtrip preferences', () => {
|
||||
@@ -106,7 +107,7 @@ describe('roadtrip preferences', () => {
|
||||
it('validates the complete window before an atomic write and broadcasts to every member of its trip', async () => {
|
||||
const s = setup();
|
||||
await expect(s.preferences.update(10, { roadtrip_day_end: '06:00', roadtrip_range_km: 200 })).rejects.toThrow();
|
||||
expect(s.preferenceDb.run).not.toHaveBeenCalled();
|
||||
expect(s.preferenceDb.upsertValue).not.toHaveBeenCalled();
|
||||
await s.preferences.update(10, { roadtrip_day_start: '06:00', roadtrip_day_end: '09:00' });
|
||||
// The fourth argument is the socket that saved, so the tab that made the
|
||||
// change is left out of its own echo. Undefined here: no header was sent.
|
||||
@@ -133,12 +134,12 @@ describe('roadtrip preferences', () => {
|
||||
s.preferences,
|
||||
{ isDemoUser: () => true } as never,
|
||||
{} as never,
|
||||
s.db as never,
|
||||
s.tripsRepo as never,
|
||||
{} as never,
|
||||
);
|
||||
s.preferenceDb.run.mockClear();
|
||||
s.preferenceDb.upsertValue.mockClear();
|
||||
await mcp.update({ tripId: 10, settings: { roadtrip_range_km: 300 } }, ctx);
|
||||
expect(s.preferenceDb.run).not.toHaveBeenCalled();
|
||||
expect(s.preferenceDb.upsertValue).not.toHaveBeenCalled();
|
||||
});
|
||||
it('tells the assistant why a window was refused instead of the exception class name', async () => {
|
||||
// The service refuses an inverted window with the `{ error }` body the route
|
||||
@@ -148,7 +149,7 @@ describe('roadtrip preferences', () => {
|
||||
s.preferences,
|
||||
{ isDemoUser: () => false } as never,
|
||||
{} as never,
|
||||
s.db as never,
|
||||
s.tripsRepo as never,
|
||||
{ hasTripPermission: () => true } as never,
|
||||
);
|
||||
const res = await mcp.update({ tripId: 10, settings: { roadtrip_day_end: '06:00' } }, ctx);
|
||||
@@ -173,13 +174,14 @@ describe('browser-independent roadtrip calculation', () => {
|
||||
const s = setup();
|
||||
await s.plans.calculate(10, 5, { roadtrip_day_end: '20:00' });
|
||||
expect((await s.preferences.read(10)).roadtrip_day_end).toBe('10:00');
|
||||
expect(s.preferenceDb.run).not.toHaveBeenCalled();
|
||||
expect(s.preferenceDb.upsertValue).not.toHaveBeenCalled();
|
||||
});
|
||||
it('checks trip access before reading or routing', async () => {
|
||||
const s = setup();
|
||||
s.db.canAccessTrip.mockResolvedValue(false);
|
||||
s.tripsRepo.findAccessible.mockResolvedValue(false);
|
||||
await expect(s.plans.calculate(20, 5)).rejects.toThrow();
|
||||
expect(s.db.all).not.toHaveBeenCalled();
|
||||
expect(s.daysRepo.listPlanDays).not.toHaveBeenCalled();
|
||||
expect(s.dayAssignmentsRepo.listRoadtripVisits).not.toHaveBeenCalled();
|
||||
expect(s.router.route).not.toHaveBeenCalled();
|
||||
});
|
||||
it('tells the assistant why a read, a calculation or a corridor search was refused', async () => {
|
||||
@@ -189,11 +191,11 @@ describe('browser-independent roadtrip calculation', () => {
|
||||
const s = setup();
|
||||
const mcp = new RoadtripPlanningMcp(s.plans, {} as never, {} as never);
|
||||
const reason = (res: { content: { text: string }[]; isError?: boolean }) => [res.isError, res.content[0].text];
|
||||
s.db.canAccessTrip.mockResolvedValue(false);
|
||||
s.tripsRepo.findAccessible.mockResolvedValue(false);
|
||||
expect(reason(await mcp.context({ tripId: 20 }, ctx))).toEqual([true, 'Trip not found']);
|
||||
expect(reason(await mcp.calculate({ tripId: 20, includeGeometry: false }, ctx))).toEqual([true, 'Trip not found']);
|
||||
expect(reason(await mcp.corridor({ tripId: 20, dayNumber: 1, category: 'fuel', widthKm: 5, offset: 0 } as never, ctx))).toEqual([true, 'Trip not found']);
|
||||
s.db.canAccessTrip.mockResolvedValue(true);
|
||||
s.tripsRepo.findAccessible.mockResolvedValue(true);
|
||||
const window = await mcp.calculate({ tripId: 10, includeGeometry: false, settings: { roadtrip_day_start: '18:00', roadtrip_day_end: '08:00' } }, ctx);
|
||||
expect(reason(window)).toEqual([true, 'Day end must be later than day start.']);
|
||||
expect(s.router.route).not.toHaveBeenCalled();
|
||||
@@ -281,7 +283,7 @@ describe('Roadtrip MCP registration and search', () => {
|
||||
const addons = { isAddonEnabled: vi.fn(() => true) };
|
||||
const registry = createTestRegistry(
|
||||
[
|
||||
new RoadtripPreferencesMcp(s.preferences, {} as never, addons as never, s.db as never, {} as never),
|
||||
new RoadtripPreferencesMcp(s.preferences, {} as never, addons as never, s.tripsRepo as never, {} as never),
|
||||
new RoadtripPlanningMcp(s.plans, {} as never, addons as never),
|
||||
],
|
||||
{ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess },
|
||||
@@ -352,7 +354,7 @@ describe('Roadtrip MCP registration and search', () => {
|
||||
const guards = { hasTripPermission: vi.fn(() => false) };
|
||||
const mcp = new RoadtripMcp(
|
||||
service as never,
|
||||
{ canAccessTrip: () => true } as never,
|
||||
{ findAccessible: () => true } as never,
|
||||
guards as never,
|
||||
{ isDemoUser: () => false } as never,
|
||||
{} as never,
|
||||
@@ -374,9 +376,9 @@ describe('Roadtrip MCP registration and search', () => {
|
||||
describe('MCP trip preferences authorization', () => {
|
||||
it('reads shared preferences and refuses inaccessible trips', async () => {
|
||||
const s = setup();
|
||||
const tool = new RoadtripPreferencesMcp(s.preferences, { isDemoUser: () => false } as never, {} as never, s.db as never, { hasTripPermission: () => true } as never);
|
||||
const tool = new RoadtripPreferencesMcp(s.preferences, { isDemoUser: () => false } as never, {} as never, s.tripsRepo as never, { hasTripPermission: () => true } as never);
|
||||
expect(JSON.stringify(await tool.read({ tripId: 10 }, ctx))).toContain('100');
|
||||
s.db.canAccessTrip.mockResolvedValue(false);
|
||||
s.tripsRepo.findAccessible.mockResolvedValue(false);
|
||||
expect((await tool.read({ tripId: 10 }, ctx)).isError).toBe(true);
|
||||
expect((await tool.update({ tripId: 10, settings: {} }, ctx)).isError).toBe(true);
|
||||
});
|
||||
@@ -384,7 +386,7 @@ describe('MCP trip preferences authorization', () => {
|
||||
const s = setup();
|
||||
const auth = { isDemoUser: vi.fn(() => true) };
|
||||
const guards = { hasTripPermission: vi.fn(() => false) };
|
||||
const tool = new RoadtripPreferencesMcp(s.preferences, auth as never, {} as never, s.db as never, guards as never);
|
||||
const tool = new RoadtripPreferencesMcp(s.preferences, auth as never, {} as never, s.tripsRepo as never, guards as never);
|
||||
expect((await tool.update({ tripId: 10, settings: {} }, ctx)).isError).toBe(true);
|
||||
auth.isDemoUser.mockReturnValue(false);
|
||||
expect((await tool.update({ tripId: 10, settings: {} }, ctx)).isError).toBe(true);
|
||||
|
||||
@@ -9,14 +9,14 @@ import { DayBoundariesMcp } from '../../../src/nest/roadtrip/day-boundaries.mcp'
|
||||
const ctx = { userId: 5 } as McpContext;
|
||||
describe('roadtrip read tools', () => {
|
||||
it('checks trip access before querying charging and hazards', async () => {
|
||||
const db = { canAccessTrip: vi.fn(async () => false) };
|
||||
const tripsRepo = { findAccessible: vi.fn(async () => false) };
|
||||
const source = { read: vi.fn(async () => ({ sources: ['public'] })) };
|
||||
const charging = new ChargingMcp(source as never, db as never, {} as never);
|
||||
const hazards = new RoadtripHazardsMcp(source as never, db as never, {} as never);
|
||||
const charging = new ChargingMcp(source as never, tripsRepo as never, {} as never);
|
||||
const hazards = new RoadtripHazardsMcp(source as never, tripsRepo as never, {} as never);
|
||||
expect((await charging.read({ tripId: 10, placeId: 2 }, ctx)).isError).toBe(true);
|
||||
expect((await hazards.read({ tripId: 10 }, ctx)).isError).toBe(true);
|
||||
expect(source.read).not.toHaveBeenCalled();
|
||||
db.canAccessTrip.mockResolvedValue(true);
|
||||
tripsRepo.findAccessible.mockResolvedValue(true);
|
||||
expect(JSON.stringify(await charging.read({ tripId: 10, placeId: 2 }, ctx))).toContain('public');
|
||||
expect(source.read).toHaveBeenCalledWith(10, 2);
|
||||
expect(JSON.stringify(await hazards.read({ tripId: 10 }, ctx))).toContain('public');
|
||||
@@ -51,8 +51,8 @@ describe('roadtrip read tools', () => {
|
||||
const refuse = (error: string, status: number) => () => { throw new HttpException({ error }, status); };
|
||||
const text = (res: { content: { text: string }[]; isError?: boolean }) => [res.isError, res.content[0].text];
|
||||
|
||||
const db = { canAccessTrip: vi.fn(async () => true) };
|
||||
const charging = new ChargingMcp({ read: refuse('Place not found', 404) } as never, db as never, {} as never);
|
||||
const tripsRepo = { findAccessible: vi.fn(async () => true) };
|
||||
const charging = new ChargingMcp({ read: refuse('Place not found', 404) } as never, tripsRepo as never, {} as never);
|
||||
expect(text(await charging.read({ tripId: 10, placeId: 2 }, ctx))).toEqual([true, 'Place not found']);
|
||||
|
||||
const auth = { isDemoUser: vi.fn(async () => false) };
|
||||
@@ -63,7 +63,7 @@ describe('roadtrip read tools', () => {
|
||||
|
||||
const realtime = { broadcast: vi.fn() };
|
||||
const guards = { hasTripPermission: vi.fn(() => true) };
|
||||
const boundaries = new DayBoundariesMcp({ save: refuse('Stop not found', 404) } as never, db as never, auth as never, guards as never, realtime as never, {} as never);
|
||||
const boundaries = new DayBoundariesMcp({ save: refuse('Stop not found', 404) } as never, tripsRepo as never, auth as never, guards as never, realtime as never, {} as never);
|
||||
const boundary = { day_number: 1, from_assignment_id: 11, to_assignment_id: 12, fraction: 0.4 };
|
||||
expect(text(await boundaries.save({ tripId: 10, dayNumber: 1, boundary }, ctx))).toEqual([true, 'Stop not found']);
|
||||
expect(realtime.broadcast).not.toHaveBeenCalled();
|
||||
@@ -71,11 +71,11 @@ describe('roadtrip read tools', () => {
|
||||
|
||||
it('does not expose manual boundaries to nonmembers', async () => {
|
||||
const boundaries = { list: vi.fn(() => [{ day_number: 1 }]) };
|
||||
const db = { canAccessTrip: vi.fn(async () => false) };
|
||||
const tool = new DayBoundariesMcp(boundaries as never, db as never, {} as never, {} as never, {} as never, {} as never);
|
||||
const tripsRepo = { findAccessible: vi.fn(async () => false) };
|
||||
const tool = new DayBoundariesMcp(boundaries as never, tripsRepo as never, {} as never, {} as never, {} as never, {} as never);
|
||||
expect((await tool.list({ tripId: 10 }, ctx)).isError).toBe(true);
|
||||
expect(boundaries.list).not.toHaveBeenCalled();
|
||||
db.canAccessTrip.mockResolvedValue(true);
|
||||
tripsRepo.findAccessible.mockResolvedValue(true);
|
||||
expect(JSON.stringify(await tool.list({ tripId: 10 }, ctx))).toContain('day_number');
|
||||
expect(boundaries.list).toHaveBeenCalledWith(10);
|
||||
});
|
||||
|
||||
@@ -1,320 +1,306 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import Database from 'better-sqlite3';
|
||||
import { RoadtripService } from '../../../src/nest/roadtrip/roadtrip.service';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { createDay, createPlace, createTrip, createUser } from '../../helpers/factories';
|
||||
import { createTestUnitOfWork } from '../../helpers/test-uow';
|
||||
import { RoadtripService } from '../../../src/nest/roadtrip/roadtrip.service';
|
||||
import { Days } from '../../../src/db/entities/Days.entity';
|
||||
import { Places } from '../../../src/db/entities/Places.entity';
|
||||
import { RoadtripVias } from '../../../src/db/entities/RoadtripVias.entity';
|
||||
import { RoadtripDayTracks } from '../../../src/db/entities/RoadtripDayTracks.entity';
|
||||
|
||||
/**
|
||||
* Via points, against a real SQLite. The table is tiny and the interesting parts are the
|
||||
* ordering and the day scoping, both of which are SQL — mocking the DB would test the mock.
|
||||
* Via points and tracks, against real rows through
|
||||
* `RoadtripViasRepository`/`RoadtripDayTracksRepository`/`DaysRepository`/
|
||||
* `PlacesRepository` (Plan 3d Task 1) — moved off the hand-DDL, raw
|
||||
* `DatabaseService`-shaped facade (§15a/§15c test risk 2) onto real schema.
|
||||
*/
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
beforeAll(async () => { t = await createTestOrm(testDb); });
|
||||
beforeEach(() => { resetTestDb(testDb); t.clear(); });
|
||||
afterAll(async () => { await t.close(); testDb.close(); });
|
||||
|
||||
async function makeService() {
|
||||
const raw = new Database(':memory:');
|
||||
raw.exec(`
|
||||
CREATE TABLE days (id INTEGER PRIMARY KEY, trip_id INTEGER NOT NULL);
|
||||
CREATE TABLE roadtrip_vias (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
|
||||
after_order_index INTEGER NOT NULL,
|
||||
sequence INTEGER NOT NULL DEFAULT 0,
|
||||
lat REAL NOT NULL,
|
||||
lng REAL NOT NULL,
|
||||
created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE places (
|
||||
id INTEGER PRIMARY KEY,
|
||||
trip_id INTEGER NOT NULL,
|
||||
name TEXT,
|
||||
route_geometry TEXT
|
||||
);
|
||||
CREATE TABLE roadtrip_day_tracks (
|
||||
day_id INTEGER PRIMARY KEY REFERENCES days(id) ON DELETE CASCADE,
|
||||
place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
|
||||
stray_km REAL,
|
||||
created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
INSERT INTO days (id, trip_id) VALUES (1, 7), (2, 7), (3, 99);
|
||||
INSERT INTO places (id, trip_id, name, route_geometry) VALUES
|
||||
(10, 7, 'Atlantic Road', '[[52,13],[52,14]]'),
|
||||
(11, 7, 'A hotel', NULL),
|
||||
(12, 99, 'Somebody else\u2019s track', '[[40,2],[40,3]]');
|
||||
`);
|
||||
const db = {
|
||||
get: <T>(sql: string, ...params: unknown[]) => raw.prepare(sql).get(...params as never[]) as T | undefined,
|
||||
all: <T>(sql: string, ...params: unknown[]) => raw.prepare(sql).all(...params as never[]) as T[],
|
||||
run: (sql: string, ...params: unknown[]) => raw.prepare(sql).run(...params as never[]),
|
||||
};
|
||||
// The realtime side is exercised through the controller and the MCP layer; here the
|
||||
// service is under test for what it writes, so a broadcast that goes nowhere is right.
|
||||
return new RoadtripService(db as never, { broadcast: () => {} } as never, await createTestUnitOfWork(raw));
|
||||
return new RoadtripService(
|
||||
{ broadcast: () => {} } as never,
|
||||
await createTestUnitOfWork(testDb),
|
||||
t.repo(Days),
|
||||
t.repo(Places),
|
||||
t.repo(RoadtripVias),
|
||||
t.repo(RoadtripDayTracks),
|
||||
);
|
||||
}
|
||||
|
||||
function fixture() {
|
||||
const { user } = createUser(testDb);
|
||||
const tripA = createTrip(testDb, user.id);
|
||||
const tripB = createTrip(testDb, user.id);
|
||||
const dayA1 = createDay(testDb, tripA.id);
|
||||
const dayA2 = createDay(testDb, tripA.id);
|
||||
const dayB1 = createDay(testDb, tripB.id);
|
||||
const track = createPlace(testDb, tripA.id, { name: 'Atlantic Road' });
|
||||
const hotel = createPlace(testDb, tripA.id, { name: 'A hotel' });
|
||||
const otherTrack = createPlace(testDb, tripB.id, { name: 'Somebody else’s track' });
|
||||
testDb.prepare('UPDATE places SET route_geometry = ? WHERE id = ?').run('[[52,13],[52,14]]', track.id);
|
||||
testDb.prepare('UPDATE places SET route_geometry = ? WHERE id = ?').run('[[40,2],[40,3]]', otherTrack.id);
|
||||
return { tripA, tripB, dayA1, dayA2, dayB1, track, hotel, otherTrack };
|
||||
}
|
||||
|
||||
describe('RoadtripService', () => {
|
||||
let service: RoadtripService;
|
||||
beforeEach(async () => { service = await makeService(); });
|
||||
let f: ReturnType<typeof fixture>;
|
||||
beforeEach(async () => {
|
||||
service = await makeService();
|
||||
f = fixture();
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-001: a day of another trip is not this trip’s day', async () => {
|
||||
// The trip guard proves access to the trip; this is what stops a valid day id from
|
||||
// someone else’s trip being edited through one the caller can reach.
|
||||
expect((await service.dayExists(1, 7))).toBe(true);
|
||||
expect((await service.dayExists(3, 7))).toBe(false);
|
||||
expect(await service.dayExists(f.dayA1.id, f.tripA.id)).toBe(true);
|
||||
expect(await service.dayExists(f.dayB1.id, f.tripA.id)).toBe(false);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-002: vias appended after the same stop keep the order they were added in', async () => {
|
||||
const first = (await service.create(1, { after_order_index: 0, lat: 53, lng: 10 }));
|
||||
const second = (await service.create(1, { after_order_index: 0, lat: 53.5, lng: 10.5 }));
|
||||
const first = await service.create(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
const second = await service.create(f.dayA1.id, { after_order_index: 0, lat: 53.5, lng: 10.5 });
|
||||
|
||||
expect(first.sequence).toBe(0);
|
||||
expect(second.sequence).toBe(1);
|
||||
expect((await service.listForDay(1)).map(v => v.id)).toEqual([first.id, second.id]);
|
||||
expect((await service.listForDay(f.dayA1.id)).map(v => v.id)).toEqual([first.id, second.id]);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-003: the list is ordered by stop first, then by sequence', async () => {
|
||||
const late = (await service.create(1, { after_order_index: 2, lat: 51, lng: 12 }));
|
||||
const early = (await service.create(1, { after_order_index: 0, lat: 53, lng: 10 }));
|
||||
const late = await service.create(f.dayA1.id, { after_order_index: 2, lat: 51, lng: 12 });
|
||||
const early = await service.create(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
|
||||
expect((await service.listForDay(1)).map(v => v.id)).toEqual([early.id, late.id]);
|
||||
expect((await service.listForDay(f.dayA1.id)).map(v => v.id)).toEqual([early.id, late.id]);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-004: the trip listing spans its days and stops at the trip boundary', async () => {
|
||||
(await service.create(1, { after_order_index: 0, lat: 53, lng: 10 }));
|
||||
(await service.create(2, { after_order_index: 0, lat: 52, lng: 11 }));
|
||||
(await service.create(3, { after_order_index: 0, lat: 50, lng: 14 }));
|
||||
await service.create(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
await service.create(f.dayA2.id, { after_order_index: 0, lat: 52, lng: 11 });
|
||||
await service.create(f.dayB1.id, { after_order_index: 0, lat: 50, lng: 14 });
|
||||
|
||||
// Day 3 belongs to trip 99 and must not appear in trip 7.
|
||||
expect((await service.listForTrip(7)).map(v => v.day_id)).toEqual([1, 2]);
|
||||
// dayB1 belongs to tripB and must not appear in tripA's listing.
|
||||
expect((await service.listForTrip(f.tripA.id)).map(v => v.day_id).sort((a, b) => a - b)).toEqual(
|
||||
[f.dayA1.id, f.dayA2.id].sort((a, b) => a - b),
|
||||
);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-005: a move with no new anchor leaves the chain alone', async () => {
|
||||
// The drag stayed between the same two stops, so there is nothing to re-pin. The
|
||||
// sequence is never touched by a move either way: it orders the vias that share one
|
||||
// anchor, and dragging one does not reorder its neighbours.
|
||||
const via = (await service.create(1, { after_order_index: 1, lat: 53, lng: 10 }));
|
||||
const via = await service.create(f.dayA1.id, { after_order_index: 1, lat: 53, lng: 10 });
|
||||
|
||||
const moved = (await service.move(via.id, 1, 52.5, 11.5));
|
||||
const moved = await service.move(via.id, f.dayA1.id, 52.5, 11.5);
|
||||
|
||||
expect(moved).toMatchObject({ lat: 52.5, lng: 11.5, after_order_index: 1, sequence: via.sequence });
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-007: a via dragged past a stop is re-pinned to the leg it landed on', async () => {
|
||||
// The bug this exists for: a drag used to carry only the coordinates, so a via pulled
|
||||
// beyond the stop it used to precede kept claiming the earlier leg. The route then ran
|
||||
// out to the point and back before carrying on, which reads as the drag doing nothing.
|
||||
const via = (await service.create(1, { after_order_index: 0, lat: 53.87, lng: 10.7 }));
|
||||
const via = await service.create(f.dayA1.id, { after_order_index: 0, lat: 53.87, lng: 10.7 });
|
||||
|
||||
const moved = (await service.move(via.id, 1, 53.87, 11.53, 1));
|
||||
const moved = await service.move(via.id, f.dayA1.id, 53.87, 11.53, 1);
|
||||
|
||||
expect(moved).toMatchObject({ lat: 53.87, lng: 11.53, after_order_index: 1 });
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-008: a re-pin through the wrong day changes nothing at all', async () => {
|
||||
// The day check has to guard the anchor as well as the coordinates, or an id from
|
||||
// another day could be renumbered through a day the caller does happen to reach.
|
||||
const via = (await service.create(1, { after_order_index: 0, lat: 53, lng: 10 }));
|
||||
const via = await service.create(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
|
||||
expect((await service.move(via.id, 2, 51, 12, 3))).toBeNull();
|
||||
expect((await service.listForDay(1))[0]).toMatchObject({ lat: 53, lng: 10, after_order_index: 0 });
|
||||
expect(await service.move(via.id, f.dayA2.id, 51, 12, 3)).toBeNull();
|
||||
expect((await service.listForDay(f.dayA1.id))[0]).toMatchObject({ lat: 53, lng: 10, after_order_index: 0 });
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-006: a via cannot be moved or removed through the wrong day', async () => {
|
||||
const via = (await service.create(1, { after_order_index: 0, lat: 53, lng: 10 }));
|
||||
const via = await service.create(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
|
||||
expect((await service.move(via.id, 2, 0, 0))).toBeNull();
|
||||
expect((await service.remove(via.id, 2))).toBe(false);
|
||||
// Still where it was.
|
||||
expect((await service.listForDay(1))).toHaveLength(1);
|
||||
expect(await service.move(via.id, f.dayA2.id, 0, 0)).toBeNull();
|
||||
expect(await service.remove(via.id, f.dayA2.id)).toBe(false);
|
||||
expect(await service.listForDay(f.dayA1.id)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-008: re-anchoring moves the vias it names and leaves the rest alone', async () => {
|
||||
const a = (await service.create(1, { after_order_index: 0, lat: 53, lng: 10 }));
|
||||
const b = (await service.create(1, { after_order_index: 1, lat: 54, lng: 11 }));
|
||||
const c = (await service.create(1, { after_order_index: 2, lat: 55, lng: 12 }));
|
||||
it('ROADTRIP-SVC-008b: re-anchoring moves the vias it names and leaves the rest alone', async () => {
|
||||
const a = await service.create(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
const b = await service.create(f.dayA1.id, { after_order_index: 1, lat: 54, lng: 11 });
|
||||
const c = await service.create(f.dayA1.id, { after_order_index: 2, lat: 55, lng: 12 });
|
||||
|
||||
const after = (await service.reanchor(1, { vias: [{ id: b.id, after_order_index: 2 }, { id: c.id, after_order_index: 3 }] }));
|
||||
const after = await service.reanchor(f.dayA1.id, { vias: [{ id: b.id, after_order_index: 2 }, { id: c.id, after_order_index: 3 }] });
|
||||
|
||||
const byId = new Map(after.map(v => [v.id, v.after_order_index]));
|
||||
expect(byId.get(a.id)).toBe(0);
|
||||
expect(byId.get(b.id)).toBe(2);
|
||||
expect(byId.get(c.id)).toBe(3);
|
||||
// Where a via sits is untouched — only which leg it belongs to changed.
|
||||
expect(after.find(v => v.id === b.id)?.lat).toBe(54);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-009: re-anchoring deletes the vias whose leg stopped existing', async () => {
|
||||
const gone = (await service.create(1, { after_order_index: 0, lat: 53, lng: 10 }));
|
||||
const kept = (await service.create(1, { after_order_index: 2, lat: 54, lng: 11 }));
|
||||
const gone = await service.create(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
const kept = await service.create(f.dayA1.id, { after_order_index: 2, lat: 54, lng: 11 });
|
||||
|
||||
const after = (await service.reanchor(1, {
|
||||
const after = await service.reanchor(f.dayA1.id, {
|
||||
vias: [{ id: kept.id, after_order_index: 1 }],
|
||||
remove: [gone.id],
|
||||
}));
|
||||
});
|
||||
|
||||
expect(after.map(v => v.id)).toEqual([kept.id]);
|
||||
expect(after[0].after_order_index).toBe(1);
|
||||
expect(after[0]!.after_order_index).toBe(1);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-010: a via of another day cannot be renumbered through this one', async () => {
|
||||
// The batch is trusted to name ids, so `AND day_id = ?` is the only thing standing
|
||||
// between a day the caller can reach and every via of the trip.
|
||||
const other = (await service.create(2, { after_order_index: 0, lat: 53, lng: 10 }));
|
||||
const other = await service.create(f.dayA2.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
|
||||
(await service.reanchor(1, { vias: [{ id: other.id, after_order_index: 9 }], remove: [other.id] }));
|
||||
await service.reanchor(f.dayA1.id, { vias: [{ id: other.id, after_order_index: 9 }], remove: [other.id] });
|
||||
|
||||
const untouched = (await service.listForDay(2));
|
||||
const untouched = await service.listForDay(f.dayA2.id);
|
||||
expect(untouched.map(v => v.id)).toEqual([other.id]);
|
||||
expect(untouched[0].after_order_index).toBe(0);
|
||||
expect(untouched[0]!.after_order_index).toBe(0);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-011: an id that is gone does not fail the rest of the batch', async () => {
|
||||
// The caller computed the batch from a snapshot; a via somebody else deleted in the
|
||||
// meantime must not leave the remaining ones mis-pinned.
|
||||
const kept = (await service.create(1, { after_order_index: 0, lat: 53, lng: 10 }));
|
||||
const kept = await service.create(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
|
||||
const after = (await service.reanchor(1, {
|
||||
const after = await service.reanchor(f.dayA1.id, {
|
||||
vias: [{ id: 9999, after_order_index: 4 }, { id: kept.id, after_order_index: 1 }],
|
||||
}));
|
||||
});
|
||||
|
||||
expect(after.map(v => v.after_order_index)).toEqual([1]);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-016: merging two populated legs keeps the drive going one way', async () => {
|
||||
// The case none of the four above reach: they all re-anchor onto legs that
|
||||
// are empty. `sequence` is allocated per leg and starts at 0 in each, so
|
||||
// merging two populated legs put leg A's 0,1 beside leg B's 0,1 — and
|
||||
// everything that draws the route orders by sequence, so the drive ran A0,
|
||||
// B0, A1, B1: forward, back, and forward again. Persisted, surviving a
|
||||
// reload, and unrepairable except by deleting the vias.
|
||||
const a0 = (await service.create(1, { after_order_index: 1, lat: 50.0, lng: 10 }));
|
||||
const a1 = (await service.create(1, { after_order_index: 1, lat: 50.1, lng: 10 }));
|
||||
const b0 = (await service.create(1, { after_order_index: 2, lat: 50.2, lng: 10 }));
|
||||
const b1 = (await service.create(1, { after_order_index: 2, lat: 50.3, lng: 10 }));
|
||||
const a0 = await service.create(f.dayA1.id, { after_order_index: 1, lat: 50.0, lng: 10 });
|
||||
const a1 = await service.create(f.dayA1.id, { after_order_index: 1, lat: 50.1, lng: 10 });
|
||||
const b0 = await service.create(f.dayA1.id, { after_order_index: 2, lat: 50.2, lng: 10 });
|
||||
const b1 = await service.create(f.dayA1.id, { after_order_index: 2, lat: 50.3, lng: 10 });
|
||||
expect([a0.sequence, a1.sequence, b0.sequence, b1.sequence]).toEqual([0, 1, 0, 1]);
|
||||
|
||||
// The stop between the two legs is removed, so leg 2 merges into leg 1 —
|
||||
// exactly what reanchorAfterRemove computes on the client.
|
||||
const after = (await service.reanchor(1, {
|
||||
const after = await service.reanchor(f.dayA1.id, {
|
||||
vias: [{ id: b0.id, after_order_index: 1 }, { id: b1.id, after_order_index: 1 }],
|
||||
}));
|
||||
});
|
||||
|
||||
const onLeg = after.filter(v => v.after_order_index === 1).sort((x, y) => x.sequence - y.sequence);
|
||||
expect(onLeg.map(v => v.id)).toEqual([a0.id, a1.id, b0.id, b1.id]);
|
||||
// Strictly increasing across the whole leg, with no value used twice.
|
||||
expect(onLeg.map(v => v.sequence)).toEqual([0, 1, 2, 3]);
|
||||
// Which is the geographic order the day is actually driven in.
|
||||
expect(onLeg.map(v => v.lat)).toEqual([50.0, 50.1, 50.2, 50.3]);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-017: a leg nothing merged into keeps the order it had', async () => {
|
||||
const first = (await service.create(1, { after_order_index: 0, lat: 53, lng: 10 }));
|
||||
const second = (await service.create(1, { after_order_index: 0, lat: 54, lng: 11 }));
|
||||
const elsewhere = (await service.create(1, { after_order_index: 3, lat: 55, lng: 12 }));
|
||||
const first = await service.create(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
const second = await service.create(f.dayA1.id, { after_order_index: 0, lat: 54, lng: 11 });
|
||||
const elsewhere = await service.create(f.dayA1.id, { after_order_index: 3, lat: 55, lng: 12 });
|
||||
|
||||
const after = (await service.reanchor(1, { vias: [{ id: elsewhere.id, after_order_index: 2 }] }));
|
||||
const after = await service.reanchor(f.dayA1.id, { vias: [{ id: elsewhere.id, after_order_index: 2 }] });
|
||||
|
||||
const leg0 = after.filter(v => v.after_order_index === 0).sort((x, y) => x.sequence - y.sequence);
|
||||
expect(leg0.map(v => v.id)).toEqual([first.id, second.id]);
|
||||
expect(leg0.map(v => v.sequence)).toEqual([0, 1]);
|
||||
// And the one that moved is alone on its new leg, numbered from zero.
|
||||
expect(after.find(v => v.id === elsewhere.id)?.sequence).toBe(0);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-012: a chain lands in the order it was sent, per leg', async () => {
|
||||
const vias = (await service.createMany(1, { vias: [
|
||||
const vias = await service.createMany(f.dayA1.id, { vias: [
|
||||
{ after_order_index: 0, lat: 53.0, lng: 10.0 },
|
||||
{ after_order_index: 0, lat: 53.1, lng: 10.1 },
|
||||
{ after_order_index: 1, lat: 53.2, lng: 10.2 },
|
||||
] }));
|
||||
] });
|
||||
|
||||
expect(vias.map(v => [v.after_order_index, v.sequence])).toEqual([[0, 0], [0, 1], [1, 0]]);
|
||||
expect(vias.map(v => v.lat)).toEqual([53.0, 53.1, 53.2]);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-013: a chain appends to what a leg already has', async () => {
|
||||
(await service.create(1, { after_order_index: 0, lat: 53, lng: 10 }));
|
||||
const vias = (await service.createMany(1, { vias: [{ after_order_index: 0, lat: 54, lng: 11 }] }));
|
||||
await service.create(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
const vias = await service.createMany(f.dayA1.id, { vias: [{ after_order_index: 0, lat: 54, lng: 11 }] });
|
||||
|
||||
expect(vias.map(v => v.sequence)).toEqual([0, 1]);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-014: replace_legs clears only the legs it names', async () => {
|
||||
// The point of naming legs rather than taking a flag for the day: a hand-placed
|
||||
// detour on another leg is not something adopting a track on this one asked to lose.
|
||||
const keep = (await service.create(1, { after_order_index: 5, lat: 50, lng: 8 }));
|
||||
(await service.create(1, { after_order_index: 0, lat: 53, lng: 10 }));
|
||||
const keep = await service.create(f.dayA1.id, { after_order_index: 5, lat: 50, lng: 8 });
|
||||
await service.create(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
|
||||
const vias = (await service.createMany(1, {
|
||||
const vias = await service.createMany(f.dayA1.id, {
|
||||
vias: [{ after_order_index: 0, lat: 54, lng: 11 }],
|
||||
replace_legs: [0],
|
||||
}));
|
||||
});
|
||||
|
||||
expect(vias.map(v => v.id)).toEqual([vias[0].id, keep.id]);
|
||||
expect(vias.map(v => v.id)).toEqual([vias[0]!.id, keep.id]);
|
||||
expect(vias.find(v => v.after_order_index === 0)?.lat).toBe(54);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-015: clearing a leg without adding anything is a legal batch', async () => {
|
||||
(await service.create(1, { after_order_index: 0, lat: 53, lng: 10 }));
|
||||
await service.create(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
|
||||
expect((await service.createMany(1, { vias: [], replace_legs: [0] }))).toEqual([]);
|
||||
expect(await service.createMany(f.dayA1.id, { vias: [], replace_legs: [0] })).toEqual([]);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-016: a chain cannot be laid on a day it was not addressed to', async () => {
|
||||
(await service.createMany(2, { vias: [{ after_order_index: 0, lat: 53, lng: 10 }] }));
|
||||
it('ROADTRIP-SVC-016b: a chain cannot be laid on a day it was not addressed to', async () => {
|
||||
await service.createMany(f.dayA2.id, { vias: [{ after_order_index: 0, lat: 53, lng: 10 }] });
|
||||
|
||||
expect((await service.listForDay(1))).toEqual([]);
|
||||
expect((await service.listForDay(2))).toHaveLength(1);
|
||||
expect(await service.listForDay(f.dayA1.id)).toEqual([]);
|
||||
expect(await service.listForDay(f.dayA2.id)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-017: the chain and the track it came from land in one write', async () => {
|
||||
// Same transaction on purpose: a day saying it follows a road whose vias never
|
||||
// arrived is worse than a day saying nothing at all.
|
||||
(await service.createMany(1, {
|
||||
it('ROADTRIP-SVC-017b: the chain and the track it came from land in one write', async () => {
|
||||
await service.createMany(f.dayA1.id, {
|
||||
vias: [{ after_order_index: 0, lat: 53, lng: 10 }],
|
||||
track: { place_id: 10, stray_km: 0.8 },
|
||||
}));
|
||||
track: { place_id: f.track.id, stray_km: 0.8 },
|
||||
});
|
||||
|
||||
expect((await service.tracksForTrip(7))).toEqual([{ day_id: 1, place_id: 10, stray_km: 0.8 }]);
|
||||
expect(await service.tracksForTrip(f.tripA.id)).toEqual([{ day_id: f.dayA1.id, place_id: f.track.id, stray_km: 0.8 }]);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-018: laying a second track on a day replaces the first, never doubles it', async () => {
|
||||
(await service.createMany(1, { vias: [], track: { place_id: 10, stray_km: 2 } }));
|
||||
(await service.createMany(1, { vias: [], track: { place_id: 12, stray_km: null } }));
|
||||
await service.createMany(f.dayA1.id, { vias: [], track: { place_id: f.track.id, stray_km: 2 } });
|
||||
await service.createMany(f.dayA1.id, { vias: [], track: { place_id: f.hotel.id, stray_km: null } });
|
||||
|
||||
expect((await service.tracksForTrip(7))).toEqual([{ day_id: 1, place_id: 12, stray_km: null }]);
|
||||
expect(await service.tracksForTrip(f.tripA.id)).toEqual([{ day_id: f.dayA1.id, place_id: f.hotel.id, stray_km: null }]);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-019: three states, not two \u2014 absent keeps, null clears', async () => {
|
||||
(await service.createMany(1, { vias: [], track: { place_id: 10, stray_km: 1 } }));
|
||||
it('ROADTRIP-SVC-019: three states, not two — absent keeps, null clears', async () => {
|
||||
await service.createMany(f.dayA1.id, { vias: [], track: { place_id: f.track.id, stray_km: 1 } });
|
||||
|
||||
// Absent: a hand-dragged via on the same day must not wipe the road it follows.
|
||||
(await service.createMany(1, { vias: [{ after_order_index: 0, lat: 53, lng: 10 }] }));
|
||||
expect((await service.tracksForTrip(7))).toHaveLength(1);
|
||||
await service.createMany(f.dayA1.id, { vias: [{ after_order_index: 0, lat: 53, lng: 10 }] });
|
||||
expect(await service.tracksForTrip(f.tripA.id)).toHaveLength(1);
|
||||
|
||||
(await service.createMany(1, { vias: [], replace_legs: [0], track: null }));
|
||||
expect((await service.tracksForTrip(7))).toEqual([]);
|
||||
await service.createMany(f.dayA1.id, { vias: [], replace_legs: [0], track: null });
|
||||
expect(await service.tracksForTrip(f.tripA.id)).toEqual([]);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-020: the tracks of one trip are not the tracks of another', async () => {
|
||||
(await service.createMany(1, { vias: [], track: { place_id: 10, stray_km: null } }));
|
||||
(await service.createMany(3, { vias: [], track: { place_id: 12, stray_km: null } }));
|
||||
await service.createMany(f.dayA1.id, { vias: [], track: { place_id: f.track.id, stray_km: null } });
|
||||
await service.createMany(f.dayB1.id, { vias: [], track: { place_id: f.otherTrack.id, stray_km: null } });
|
||||
|
||||
expect((await service.tracksForTrip(7)).map(t => t.day_id)).toEqual([1]);
|
||||
expect((await service.tracksForTrip(99)).map(t => t.day_id)).toEqual([3]);
|
||||
expect((await service.tracksForTrip(f.tripA.id)).map(tr => tr.day_id)).toEqual([f.dayA1.id]);
|
||||
expect((await service.tracksForTrip(f.tripB.id)).map(tr => tr.day_id)).toEqual([f.dayB1.id]);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-021: only a track of this trip can become a day\u2019s label', async () => {
|
||||
// Permission is not enough on its own: without this a place id from another trip
|
||||
// would become this day\u2019s label, and an ordinary place would become a label that
|
||||
// can never be drawn.
|
||||
expect((await service.trackExists(10, 7))).toBe(true);
|
||||
expect((await service.trackExists(11, 7))).toBe(false);
|
||||
expect((await service.trackExists(12, 7))).toBe(false);
|
||||
expect((await service.trackExists(999, 7))).toBe(false);
|
||||
it('ROADTRIP-SVC-021: only a track of this trip can become a day’s label', async () => {
|
||||
expect(await service.trackExists(f.track.id, f.tripA.id)).toBe(true);
|
||||
expect(await service.trackExists(f.hotel.id, f.tripA.id)).toBe(false);
|
||||
expect(await service.trackExists(f.otherTrack.id, f.tripA.id)).toBe(false);
|
||||
expect(await service.trackExists(999999, f.tripA.id)).toBe(false);
|
||||
});
|
||||
|
||||
it('ROADTRIP-SVC-007: removing one reports whether there was anything to remove', async () => {
|
||||
const via = (await service.create(1, { after_order_index: 0, lat: 53, lng: 10 }));
|
||||
it('ROADTRIP-SVC-007b: removing one reports whether there was anything to remove', async () => {
|
||||
const via = await service.create(f.dayA1.id, { after_order_index: 0, lat: 53, lng: 10 });
|
||||
|
||||
expect((await service.remove(via.id, 1))).toBe(true);
|
||||
expect((await service.remove(via.id, 1))).toBe(false);
|
||||
expect((await service.listForDay(1))).toEqual([]);
|
||||
expect(await service.remove(via.id, f.dayA1.id)).toBe(true);
|
||||
expect(await service.remove(via.id, f.dayA1.id)).toBe(false);
|
||||
expect(await service.listForDay(f.dayA1.id)).toEqual([]);
|
||||
});
|
||||
|
||||
it('RT8-GUARD-001: a non-canonical dayId is refused before any write — `createMany` never reaches the track upsert with an invalid day', async () => {
|
||||
// The Task 0 review carry (RT8): `RoadtripDayTracksRepository.upsertTrack`'s
|
||||
// `day_id` is that table's PRIMARY KEY column, and SQLite silently accepts
|
||||
// `INSERT … VALUES (NULL, …)` on an INTEGER PK by auto-assigning a rowid —
|
||||
// possibly colliding with a real, unrelated day. `requireDayId` (the
|
||||
// service's own gate, `toRowId`-based) refuses `'abc'`/`'3 '`/`'0x10'`
|
||||
// BEFORE the transaction opens, so `upsertTrack` can never be reached with
|
||||
// anything but a real, parsed integer.
|
||||
for (const badDayId of ['abc', '3 ', '0x10', '', '1.5']) {
|
||||
await expect(service.createMany(badDayId, { vias: [], track: { place_id: f.track.id, stray_km: null } }))
|
||||
.rejects.toMatchObject({ response: { error: 'Day not found' }, status: 404 });
|
||||
}
|
||||
expect(await service.tracksForTrip(f.tripA.id)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user