test(server): seed the atlas, settings, budget and notification specs through the factories

Eleven more suites (atlas and settings e2e, the bucket list, shadow pick
and Dawarich suggestion repositories, the budget and collab MCP tools,
notification preferences, VAPID keys, school holidays and tours) write
and read their rows through the ORM factories. Time-relative fixtures
that leaned on SQLite's date('now', ...) build the same text in JS with
dbNow(), and helpers that returned undefined for a missing row keep doing
so where an assertion depends on it. The legacy statements the parity
cases compare against stay raw, marked as oracles.
This commit is contained in:
Maurice
2026-10-08 15:59:17 +02:00
parent e2ce2ad05c
commit 49ba73fcae
11 changed files with 472 additions and 386 deletions
@@ -4,6 +4,7 @@ import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { createUser } from '../../../helpers/factories';
import { BucketList } from '../../../../src/db/entities/BucketList.entity';
import { insertRow, insertRows } from '../../../helpers/factories/rows';
import type { BucketListRepository } from '../../../../src/db/repositories/BucketList.repository';
const testDb = createSnapshotTestDb();
@@ -21,13 +22,13 @@ describe('BucketListRepository.listForPublicApi (Plan 4 Task 1, public-api.servi
it('BUCKETREPO-001: name/lat/lng/country_code/notes/target_date only, ordered by created_at DESC then id DESC, scoped to the caller', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb, { username: 'other' });
const insert = testDb.prepare(
'INSERT INTO bucket_list (user_id, name, lat, lng, country_code, notes, target_date, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
);
insert.run(user.id, 'Older', 1, 2, 'JP', 'note', null, '2026-01-01T00:00:00.000Z');
insert.run(user.id, 'Newer', null, null, null, null, '2027-03-01', '2026-02-01T00:00:00.000Z');
insert.run(other.id, 'Not mine', 9, 9, null, null, null, '2026-03-01T00:00:00.000Z');
await insertRows(t, BucketList, [
{ user: user.id, name: 'Older', lat: 1, lng: 2, country_code: 'JP', notes: 'note', target_date: null, created_at: '2026-01-01T00:00:00.000Z' },
{ user: user.id, name: 'Newer', lat: null, lng: null, country_code: null, notes: null, target_date: '2027-03-01', created_at: '2026-02-01T00:00:00.000Z' },
{ user: other.id, name: 'Not mine', lat: 9, lng: 9, country_code: null, notes: null, target_date: null, created_at: '2026-03-01T00:00:00.000Z' },
]);
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = testDb.prepare(
'SELECT name, lat, lng, country_code, notes, target_date FROM bucket_list WHERE user_id = ? ORDER BY created_at DESC, id DESC',
).all(user.id);
@@ -39,11 +40,8 @@ describe('BucketListRepository.listForPublicApi (Plan 4 Task 1, public-api.servi
it('BUCKETREPO-002: same-instant rows tiebreak on id DESC (the second ORDER BY key)', async () => {
const { user } = createUser(testDb);
const insert = testDb.prepare(
'INSERT INTO bucket_list (user_id, name, created_at) VALUES (?, ?, ?)',
);
insert.run(user.id, 'First inserted', '2026-01-01T00:00:00.000Z');
insert.run(user.id, 'Second inserted', '2026-01-01T00:00:00.000Z');
await insertRow(t, BucketList, { user: user.id, name: 'First inserted', created_at: '2026-01-01T00:00:00.000Z' });
await insertRow(t, BucketList, { user: user.id, name: 'Second inserted', created_at: '2026-01-01T00:00:00.000Z' });
const rows = await bucketList.listForPublicApi(user.id);
expect(rows.map((r) => r.name)).toEqual(['Second inserted', 'First inserted']);
@@ -66,19 +64,27 @@ describe('BucketListRepository.listForUser (AT30) — SELECT * ordered by create
it('BUCKETREPO-004: matches the legacy row exactly, every nullable column both NULL and SET', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb, { username: 'other' });
const sparse = testDb.prepare(
'INSERT INTO bucket_list (user_id, name, created_at) VALUES (?, ?, ?)',
).run(user.id, 'Sparse', '2026-01-01T00:00:00.000Z');
const full = testDb.prepare(
'INSERT INTO bucket_list (user_id, name, lat, lng, country_code, notes, target_date, visited_at, visited_source, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
).run(user.id, 'Full', 10.5, 20.5, 'JP', 'note', '2027-01-01', '2026-06-01', 'manual', '2026-02-01T00:00:00.000Z');
testDb.prepare('INSERT INTO bucket_list (user_id, name) VALUES (?, ?)').run(other.id, 'Not mine');
const sparse = await insertRow(t, BucketList, { user: user.id, name: 'Sparse', created_at: '2026-01-01T00:00:00.000Z' });
const full = await insertRow(t, BucketList, {
user: user.id,
name: 'Full',
lat: 10.5,
lng: 20.5,
country_code: 'JP',
notes: 'note',
target_date: '2027-01-01',
visited_at: '2026-06-01',
visited_source: 'manual',
created_at: '2026-02-01T00:00:00.000Z',
});
await insertRow(t, BucketList, { user: other.id, name: 'Not mine' });
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = testDb.prepare('SELECT * FROM bucket_list WHERE user_id = ? ORDER BY created_at DESC').all(user.id);
const rows = await bucketList.listForUser(user.id);
expect(rows).toEqual(legacy);
expect(rows.map((r) => r.id)).toEqual([Number(full.lastInsertRowid), Number(sparse.lastInsertRowid)]);
expect(rows.map((r) => r.id)).toEqual([full, sparse]);
});
it('BUCKETREPO-005: empty array for a user with nothing on their list', async () => {
@@ -90,9 +96,9 @@ describe('BucketListRepository.listForUser (AT30) — SELECT * ordered by create
describe('BucketListRepository.findById (AT33) — SELECT * WHERE id = ?, NOT user-scoped', () => {
it('BUCKETREPO-006: matches the legacy row, regardless of owner', async () => {
const { user } = createUser(testDb);
const inserted = testDb.prepare('INSERT INTO bucket_list (user_id, name) VALUES (?, ?)').run(user.id, 'Item');
const id = Number(inserted.lastInsertRowid);
const id = await insertRow(t, BucketList, { user: user.id, name: 'Item' });
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = testDb.prepare('SELECT * FROM bucket_list WHERE id = ?').get(id);
expect(await bucketList.findById(id)).toEqual(legacy);
});
@@ -105,9 +111,9 @@ describe('BucketListRepository.findById (AT33) — SELECT * WHERE id = ?, NOT us
describe('BucketListRepository.findForUser (AT34/AT36/AT37) — SELECT * WHERE id = ? AND user_id = ?', () => {
it('BUCKETREPO-008: matches the legacy row for the owning user', async () => {
const { user } = createUser(testDb);
const inserted = testDb.prepare('INSERT INTO bucket_list (user_id, name) VALUES (?, ?)').run(user.id, 'Item');
const id = Number(inserted.lastInsertRowid);
const id = await insertRow(t, BucketList, { user: user.id, name: 'Item' });
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = testDb.prepare('SELECT * FROM bucket_list WHERE id = ? AND user_id = ?').get(id, user.id);
expect(await bucketList.findForUser(id, user.id)).toEqual(legacy);
});
@@ -115,8 +121,7 @@ describe('BucketListRepository.findForUser (AT34/AT36/AT37) — SELECT * WHERE i
it('BUCKETREPO-009: undefined for a foreign owner — the guard never leaks another user\'s item', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb, { username: 'other' });
const inserted = testDb.prepare('INSERT INTO bucket_list (user_id, name) VALUES (?, ?)').run(user.id, 'Item');
const id = Number(inserted.lastInsertRowid);
const id = await insertRow(t, BucketList, { user: user.id, name: 'Item' });
expect(await bucketList.findForUser(id, other.id)).toBeUndefined();
});
@@ -4,6 +4,11 @@ import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { createUser, createTrip } from '../../../helpers/factories';
import { DawarichVisitSuggestions } from '../../../../src/db/entities/DawarichVisitSuggestions.entity';
import { Journeys } from '../../../../src/db/entities/Journeys.entity';
import { JourneyEntries } from '../../../../src/db/entities/JourneyEntries.entity';
import { deleteRows, findRow, findRows, insertRow, updateRows } from '../../../helpers/factories/rows';
import { makePlace } from '../../../helpers/factories/places';
import { makeBucketListItem } from '../../../helpers/factories/atlas';
import type { DawarichVisitSuggestionsRepository } from '../../../../src/db/repositories/DawarichVisitSuggestions.repository';
const testDb = createSnapshotTestDb();
@@ -26,7 +31,7 @@ afterAll(async () => {
let _seq = 0;
function seed(
async function seed(
userId: number,
over: Partial<{
source_visit_id: string;
@@ -52,68 +57,65 @@ function seed(
accepted_hash: string | null;
source_missing_at: string | null;
}> = {},
): number {
): Promise<number> {
_seq++;
const result = testDb
.prepare(
`INSERT INTO dawarich_visit_suggestions
(user_id, source_visit_id, trip_id, name, lat, lng, started_at, ended_at, duration_minutes,
local_date, source_status, confidence, confidence_band, country_code, state, target,
accepted_place_id, accepted_journal_entry_id, accepted_bucket_list_item_id,
matched_bucket_list_item_id, source_hash, accepted_hash, source_missing_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
userId,
over.source_visit_id ?? `visit-${_seq}`,
over.trip_id ?? null,
over.name ?? 'Cafe Central',
over.lat === undefined ? 48.2092 : over.lat,
over.lng === undefined ? 16.3658 : over.lng,
over.started_at ?? '2026-09-01T09:30:00Z',
over.ended_at ?? '2026-09-01T11:45:00Z',
over.duration_minutes ?? 135,
over.local_date ?? '2026-09-01',
over.source_status ?? 'suggested',
over.confidence ?? 0.7,
over.confidence_band ?? 'high',
over.country_code ?? 'AT',
over.state ?? 'new',
over.target ?? null,
over.accepted_place_id ?? null,
over.accepted_journal_entry_id ?? null,
over.accepted_bucket_list_item_id ?? null,
over.matched_bucket_list_item_id ?? null,
over.source_hash ?? `hash-${_seq}`,
over.accepted_hash ?? null,
over.source_missing_at ?? null,
);
return Number(result.lastInsertRowid);
return insertRow(t, DawarichVisitSuggestions, {
user: userId,
source_visit_id: over.source_visit_id ?? `visit-${_seq}`,
trip: over.trip_id ?? null,
name: over.name ?? 'Cafe Central',
lat: over.lat === undefined ? 48.2092 : over.lat,
lng: over.lng === undefined ? 16.3658 : over.lng,
started_at: over.started_at ?? '2026-09-01T09:30:00Z',
ended_at: over.ended_at ?? '2026-09-01T11:45:00Z',
duration_minutes: over.duration_minutes ?? 135,
local_date: over.local_date ?? '2026-09-01',
source_status: over.source_status ?? 'suggested',
confidence: over.confidence ?? 0.7,
confidence_band: over.confidence_band ?? 'high',
country_code: over.country_code ?? 'AT',
state: over.state ?? 'new',
target: over.target ?? null,
acceptedPlace: over.accepted_place_id ?? null,
accepted_journal_entry_id: over.accepted_journal_entry_id ?? null,
acceptedBucketListItem: over.accepted_bucket_list_item_id ?? null,
matchedBucketListItem: over.matched_bucket_list_item_id ?? null,
source_hash: over.source_hash ?? `hash-${_seq}`,
accepted_hash: over.accepted_hash ?? null,
source_missing_at: over.source_missing_at ?? null,
});
}
function rawRow(id: number): Record<string, unknown> {
return testDb.prepare('SELECT * FROM dawarich_visit_suggestions WHERE id = ?').get(id) as Record<string, unknown>;
function storedRow(id: number) {
return findRow(t, DawarichVisitSuggestions, { id });
}
function seedPlace(tripId: number): number {
const category = testDb.prepare('SELECT id FROM categories LIMIT 1').get() as { id: number } | undefined;
const result = testDb.prepare('INSERT INTO places (trip_id, name, category_id) VALUES (?, ?, ?)').run(tripId, 'A place', category?.id ?? null);
return Number(result.lastInsertRowid);
/** The stored row; fails the case when it is gone. */
async function rawRow(id: number) {
const row = await storedRow(id);
if (!row) throw new Error(`no suggestion ${id}`);
return row;
}
function seedJourneyEntry(userId: number): number {
const journeyId = Number(
testDb.prepare("INSERT INTO journeys (user_id, title, status, created_at, updated_at) VALUES (?, 'Trip diary', 'active', 0, 0)").run(userId).lastInsertRowid,
);
return Number(
testDb
.prepare("INSERT INTO journey_entries (journey_id, author_id, type, title, entry_date, created_at, updated_at) VALUES (?, ?, 'entry', 'Cafe', '2026-09-01', 0, 0)")
.run(journeyId, userId).lastInsertRowid,
);
async function seedPlace(tripId: number): Promise<number> {
return (await makePlace(t, tripId, { name: 'A place', lat: null, lng: null })).id;
}
function seedBucketItem(userId: number): number {
return Number(testDb.prepare('INSERT INTO bucket_list (user_id, name) VALUES (?, ?)').run(userId, 'Wish').lastInsertRowid);
async function seedJourneyEntry(userId: number): Promise<number> {
const journeyId = await insertRow(t, Journeys, { user: userId, title: 'Trip diary', status: 'active', created_at: 0, updated_at: 0 });
return insertRow(t, JourneyEntries, {
journey: journeyId,
author: userId,
type: 'entry',
title: 'Cafe',
entry_date: '2026-09-01',
created_at: 0,
updated_at: 0,
});
}
async function seedBucketItem(userId: number): Promise<number> {
return (await makeBucketListItem(t, userId, { name: 'Wish' })).id;
}
describe('DawarichVisitSuggestionsRepository', () => {
@@ -121,11 +123,12 @@ describe('DawarichVisitSuggestionsRepository', () => {
it('DVSREPO-001: a fully-seeded row (with a trip and a matched wish) joins trip_title/matched_bucket_name and every scalar column, matching a legacy raw join', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Vienna' });
const wish = seedBucketItem(user.id);
const id = seed(user.id, { trip_id: trip.id, matched_bucket_list_item_id: wish, name: 'Cafe Central' });
const wish = await seedBucketItem(user.id);
const id = await seed(user.id, { trip_id: trip.id, matched_bucket_list_item_id: wish, name: 'Cafe Central' });
const rows = await suggestions.list(user.id, {});
const legacy = testDb
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
.prepare(
`SELECT s.*, t.title AS trip_title, b.name AS matched_bucket_name
FROM dawarich_visit_suggestions s
@@ -145,21 +148,21 @@ describe('DawarichVisitSuggestionsRepository', () => {
it('DVSREPO-002: scoped by user_id — a stranger\'s row never appears', async () => {
const { user } = createUser(testDb);
const { user: stranger } = createUser(testDb);
seed(stranger.id);
await seed(stranger.id);
expect(await suggestions.list(user.id, {})).toEqual([]);
});
it('DVSREPO-003: filters by tripId and state, ordered started_at DESC, id DESC', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const older = seed(user.id, { trip_id: trip.id, started_at: '2026-09-01T00:00:00Z' });
const newer = seed(user.id, { trip_id: trip.id, started_at: '2026-09-02T00:00:00Z' });
seed(user.id, { started_at: '2026-09-03T00:00:00Z' }); // no trip
const older = await seed(user.id, { trip_id: trip.id, started_at: '2026-09-01T00:00:00Z' });
const newer = await seed(user.id, { trip_id: trip.id, started_at: '2026-09-02T00:00:00Z' });
await seed(user.id, { started_at: '2026-09-03T00:00:00Z' }); // no trip
const byTrip = await suggestions.list(user.id, { tripId: trip.id });
expect(byTrip.map((r) => r.id)).toEqual([newer, older]);
seed(user.id, { trip_id: trip.id, state: 'dismissed' });
await seed(user.id, { trip_id: trip.id, state: 'dismissed' });
const byState = await suggestions.list(user.id, { state: 'dismissed' });
expect(byState).toHaveLength(1);
expect(byState[0].state).toBe('dismissed');
@@ -168,7 +171,7 @@ describe('DawarichVisitSuggestionsRepository', () => {
it('DVSREPO-004: getOne is the single-row variant, still user-scoped', async () => {
const { user } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const id = seed(user.id);
const id = await seed(user.id);
expect(await suggestions.getOne(stranger.id, id)).toBeNull();
expect((await suggestions.getOne(user.id, id))?.id).toBe(id);
});
@@ -177,54 +180,54 @@ describe('DawarichVisitSuggestionsRepository', () => {
describe('reopenOrphaned (DWS2)', () => {
it('DVSREPO-010: place target with a NULL accepted_place_id is reopened', async () => {
const { user } = createUser(testDb);
const id = seed(user.id, { state: 'accepted', target: 'place', accepted_place_id: null });
const id = await seed(user.id, { state: 'accepted', target: 'place', accepted_place_id: null });
await suggestions.reopenOrphaned(user.id);
const row = rawRow(id);
const row = await rawRow(id);
expect(row.state).toBe('new');
expect(row.target).toBeNull();
});
it('DVSREPO-011: bucket_list target with a NULL accepted_bucket_list_item_id is reopened', async () => {
const { user } = createUser(testDb);
const id = seed(user.id, { state: 'accepted', target: 'bucket_list', accepted_bucket_list_item_id: null });
const id = await seed(user.id, { state: 'accepted', target: 'bucket_list', accepted_bucket_list_item_id: null });
await suggestions.reopenOrphaned(user.id);
expect(rawRow(id).state).toBe('new');
expect((await rawRow(id)).state).toBe('new');
});
it('DVSREPO-012: journal target whose entry no longer exists (cross-domain NOT EXISTS against journey_entries) is reopened', async () => {
const { user } = createUser(testDb);
const entryId = seedJourneyEntry(user.id);
const id = seed(user.id, { state: 'accepted', target: 'journal', accepted_journal_entry_id: entryId });
const entryId = await seedJourneyEntry(user.id);
const id = await seed(user.id, { state: 'accepted', target: 'journal', accepted_journal_entry_id: entryId });
// Still exists: not reopened.
await suggestions.reopenOrphaned(user.id);
expect(rawRow(id).state).toBe('accepted');
expect((await rawRow(id)).state).toBe('accepted');
testDb.prepare('DELETE FROM journey_entries WHERE id = ?').run(entryId);
await deleteRows(t, JourneyEntries, { id: entryId });
await suggestions.reopenOrphaned(user.id);
expect(rawRow(id).state).toBe('new');
expect(rawRow(id).accepted_journal_entry_id).toBeNull();
expect((await rawRow(id)).state).toBe('new');
expect((await rawRow(id)).accepted_journal_entry_id).toBeNull();
});
it('DVSREPO-013: journal target with a NULL accepted_journal_entry_id is reopened without needing a journey_entries lookup at all', async () => {
const { user } = createUser(testDb);
const id = seed(user.id, { state: 'accepted', target: 'journal', accepted_journal_entry_id: null });
const id = await seed(user.id, { state: 'accepted', target: 'journal', accepted_journal_entry_id: null });
await suggestions.reopenOrphaned(user.id);
expect(rawRow(id).state).toBe('new');
expect((await rawRow(id)).state).toBe('new');
});
it('DVSREPO-014: an intact acceptance (place still exists) is left alone; another user\'s orphan is untouched', async () => {
const { user } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const placeId = seedPlace(trip.id);
const intact = seed(user.id, { state: 'accepted', target: 'place', accepted_place_id: placeId });
const theirs = seed(stranger.id, { state: 'accepted', target: 'place', accepted_place_id: null });
const placeId = await seedPlace(trip.id);
const intact = await seed(user.id, { state: 'accepted', target: 'place', accepted_place_id: placeId });
const theirs = await seed(stranger.id, { state: 'accepted', target: 'place', accepted_place_id: null });
await suggestions.reopenOrphaned(user.id);
expect(rawRow(intact).state).toBe('accepted');
expect(rawRow(theirs).state).toBe('accepted');
expect((await rawRow(intact)).state).toBe('accepted');
expect((await rawRow(theirs)).state).toBe('accepted');
});
});
@@ -232,8 +235,8 @@ describe('DawarichVisitSuggestionsRepository', () => {
it('DVSREPO-020: every scalar column round-trips, matching a legacy SELECT *', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const wish = seedBucketItem(user.id);
const id = seed(user.id, {
const wish = await seedBucketItem(user.id);
const id = await seed(user.id, {
trip_id: trip.id,
matched_bucket_list_item_id: wish,
accepted_bucket_list_item_id: wish,
@@ -243,7 +246,8 @@ describe('DawarichVisitSuggestionsRepository', () => {
});
const row = await suggestions.findForUser(id, user.id);
expect(row).toEqual(rawRow(id));
// test-sql-allow: the row as SELECT * returns it is the oracle the repository read is held to.
expect(row).toEqual(testDb.prepare('SELECT * FROM dawarich_visit_suggestions WHERE id = ?').get(id));
// The persist(false) shadow FKs specifically — the trap this Kysely
// full-row read exists to avoid.
expect(row!.trip_id).toBe(trip.id);
@@ -254,7 +258,7 @@ describe('DawarichVisitSuggestionsRepository', () => {
it('DVSREPO-021: findForUser is scoped by id AND user_id; findByUserAndVisit by user_id AND source_visit_id', async () => {
const { user } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const id = seed(stranger.id, { source_visit_id: 'abc' });
const id = await seed(stranger.id, { source_visit_id: 'abc' });
expect(await suggestions.findForUser(id, user.id)).toBeNull();
expect(await suggestions.findByUserAndVisit(user.id, 'abc')).toBeNull();
expect((await suggestions.findByUserAndVisit(stranger.id, 'abc'))?.id).toBe(id);
@@ -283,13 +287,13 @@ describe('DawarichVisitSuggestionsRepository', () => {
first_seen_at: '2026-01-01T00:00:00Z',
last_seen_at: '2026-01-01T00:00:00Z',
});
expect(rawRow(id)).toMatchObject({ state: 'new', name: 'Stop', country_code: 'DE', source_hash: 'h1' });
expect(await rawRow(id)).toMatchObject({ state: 'new', name: 'Stop', country_code: 'DE', source_hash: 'h1' });
});
it('DVSREPO-031: updateNewVisit overwrites the full row and clears source_missing_at', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const id = seed(user.id, { source_missing_at: '2026-01-01T00:00:00Z', name: 'Old name' });
const id = await seed(user.id, { source_missing_at: '2026-01-01T00:00:00Z', name: 'Old name' });
await suggestions.updateNewVisit(id, {
name: 'New name',
@@ -308,17 +312,17 @@ describe('DawarichVisitSuggestionsRepository', () => {
last_seen_at: '2026-02-01T00:00:00Z',
});
const row = rawRow(id);
const row = await rawRow(id);
expect(row).toMatchObject({ name: 'New name', source_missing_at: null, trip_id: trip.id, source_hash: 'h2' });
});
it('DVSREPO-032: refreshHash touches only source_hash/source_missing_at/last_seen_at — the user-visible fields survive', async () => {
const { user } = createUser(testDb);
const id = seed(user.id, { name: 'Kept name', state: 'accepted', source_missing_at: '2026-01-01T00:00:00Z' });
const id = await seed(user.id, { name: 'Kept name', state: 'accepted', source_missing_at: '2026-01-01T00:00:00Z' });
await suggestions.refreshHash(id, 'h3', '2026-03-01T00:00:00Z');
expect(rawRow(id)).toMatchObject({ name: 'Kept name', state: 'accepted', source_hash: 'h3', source_missing_at: null, last_seen_at: '2026-03-01T00:00:00Z' });
expect(await rawRow(id)).toMatchObject({ name: 'Kept name', state: 'accepted', source_hash: 'h3', source_missing_at: null, last_seen_at: '2026-03-01T00:00:00Z' });
});
});
@@ -326,8 +330,8 @@ describe('DawarichVisitSuggestionsRepository', () => {
it('DVSREPO-040: candidates are scoped by user/trip and local_date bounds', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const inWindow = seed(user.id, { trip_id: trip.id, local_date: '2026-05-05' });
seed(user.id, { trip_id: trip.id, local_date: '2019-01-01' });
const inWindow = await seed(user.id, { trip_id: trip.id, local_date: '2026-05-05' });
await seed(user.id, { trip_id: trip.id, local_date: '2019-01-01' });
const candidates = await suggestions.listCandidatesForWindow(user.id, trip.id, '2026-05-01', '2026-05-10');
expect(candidates.map((c) => c.id)).toEqual([inWindow]);
@@ -335,20 +339,20 @@ describe('DawarichVisitSuggestionsRepository', () => {
it('DVSREPO-041: deleteById removes exactly the named row', async () => {
const { user } = createUser(testDb);
const id = seed(user.id);
const id = await seed(user.id);
await suggestions.deleteById(id);
expect(rawRow(id)).toBeUndefined();
expect(await storedRow(id)).toBeNull();
});
it('DVSREPO-042: stampMissingIfUnset preserves the FIRST-missing timestamp (COALESCE, not overwrite)', async () => {
const { user } = createUser(testDb);
const id = seed(user.id, { source_missing_at: '2026-01-01T00:00:00Z' });
const id = await seed(user.id, { source_missing_at: '2026-01-01T00:00:00Z' });
await suggestions.stampMissingIfUnset(id, '2026-06-01T00:00:00Z');
expect(rawRow(id).source_missing_at).toBe('2026-01-01T00:00:00Z');
expect((await rawRow(id)).source_missing_at).toBe('2026-01-01T00:00:00Z');
const id2 = seed(user.id, { source_missing_at: null });
const id2 = await seed(user.id, { source_missing_at: null });
await suggestions.stampMissingIfUnset(id2, '2026-06-01T00:00:00Z');
expect(rawRow(id2).source_missing_at).toBe('2026-06-01T00:00:00Z');
expect((await rawRow(id2)).source_missing_at).toBe('2026-06-01T00:00:00Z');
});
});
@@ -356,16 +360,16 @@ describe('DawarichVisitSuggestionsRepository', () => {
it('DVSREPO-050: accepted_hash tracks CURRENT source_hash at UPDATE time, not a value bound earlier', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const placeId = seedPlace(trip.id);
const id = seed(user.id, { source_hash: 'hash-original' });
const placeId = await seedPlace(trip.id);
const id = await seed(user.id, { source_hash: 'hash-original' });
// A concurrent write lands between "the caller decided to accept" and
// the markAccepted call itself.
testDb.prepare('UPDATE dawarich_visit_suggestions SET source_hash = ? WHERE id = ?').run('hash-concurrent', id);
await updateRows(t, DawarichVisitSuggestions, { id }, { source_hash: 'hash-concurrent' });
await suggestions.markAccepted(id, { target: 'place', placeId, journalEntryId: null, bucketItemId: null });
const row = rawRow(id);
const row = await rawRow(id);
expect(row.source_hash).toBe('hash-concurrent');
expect(row.accepted_hash).toBe('hash-concurrent');
expect(row.state).toBe('accepted');
@@ -376,9 +380,9 @@ describe('DawarichVisitSuggestionsRepository', () => {
describe('listHoldersOfWish/clearWishHolders/assignWishHolder (DSY11/12/13)', () => {
it('DVSREPO-060: listHoldersOfWish excludes the caller\'s own source_visit_id', async () => {
const { user } = createUser(testDb);
const wish = seedBucketItem(user.id);
const holder = seed(user.id, { source_visit_id: 'holder', matched_bucket_list_item_id: wish });
seed(user.id, { source_visit_id: 'self', matched_bucket_list_item_id: wish });
const wish = await seedBucketItem(user.id);
const holder = await seed(user.id, { source_visit_id: 'holder', matched_bucket_list_item_id: wish });
await seed(user.id, { source_visit_id: 'self', matched_bucket_list_item_id: wish });
const holders = await suggestions.listHoldersOfWish(user.id, wish, 'self');
expect(holders.map((h) => h.id)).toEqual([holder]);
@@ -387,32 +391,30 @@ describe('DawarichVisitSuggestionsRepository', () => {
it('DVSREPO-061: clear-then-assign leaves exactly one holder, scoped to the caller', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const wish = seedBucketItem(user.id);
seed(user.id, { source_visit_id: 'a', matched_bucket_list_item_id: wish });
seed(user.id, { source_visit_id: 'b', matched_bucket_list_item_id: wish });
const winnerId = seed(user.id, { source_visit_id: 'c', matched_bucket_list_item_id: null });
const otherHolder = seed(other.id, { source_visit_id: 'a', matched_bucket_list_item_id: wish });
const wish = await seedBucketItem(user.id);
await seed(user.id, { source_visit_id: 'a', matched_bucket_list_item_id: wish });
await seed(user.id, { source_visit_id: 'b', matched_bucket_list_item_id: wish });
const winnerId = await seed(user.id, { source_visit_id: 'c', matched_bucket_list_item_id: null });
const otherHolder = await seed(other.id, { source_visit_id: 'a', matched_bucket_list_item_id: wish });
await suggestions.clearWishHolders(user.id, wish);
await suggestions.assignWishHolder(user.id, 'c', wish);
const all = testDb
.prepare('SELECT id, matched_bucket_list_item_id FROM dawarich_visit_suggestions WHERE matched_bucket_list_item_id = ? AND user_id = ?')
.all(wish, user.id) as { id: number; matched_bucket_list_item_id: number }[];
const all = await findRows(t, DawarichVisitSuggestions, { matchedBucketListItem: wish, user: user.id });
expect(all.map((r) => r.id)).toEqual([winnerId]);
// clearWishHolders is scoped by user_id — another user's row with the
// SAME wish id (a coincidence, wishes aren't globally unique ids across
// users here) is untouched.
expect(rawRow(otherHolder).matched_bucket_list_item_id).toBe(wish);
expect((await rawRow(otherHolder)).matched_bucket_list_item_id).toBe(wish);
});
});
describe('matchedStayStart (DWS14)', () => {
it('DVSREPO-070: the most recent started_at among the user\'s stays matched to that wish', async () => {
const { user } = createUser(testDb);
const wish = seedBucketItem(user.id);
seed(user.id, { matched_bucket_list_item_id: wish, started_at: '2026-01-01T00:00:00Z' });
seed(user.id, { matched_bucket_list_item_id: wish, started_at: '2026-06-01T00:00:00Z' });
const wish = await seedBucketItem(user.id);
await seed(user.id, { matched_bucket_list_item_id: wish, started_at: '2026-01-01T00:00:00Z' });
await seed(user.id, { matched_bucket_list_item_id: wish, started_at: '2026-06-01T00:00:00Z' });
expect(await suggestions.matchedStayStart(user.id, wish)).toBe('2026-06-01T00:00:00Z');
expect(await suggestions.matchedStayStart(user.id, 999999)).toBeNull();
@@ -8,6 +8,8 @@ import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { PlaceShadowPicks } from '../../../../src/db/entities/PlaceShadowPicks.entity';
import { findRow, findRows, updateRows } from '../../../helpers/factories/rows';
import { dbNow } from '../../../../src/db/types';
import type { PlaceShadowPicksRepository, NewPlaceShadowPickRow } from '../../../../src/db/repositories/PlaceShadowPicks.repository';
const testDb = createSnapshotTestDb();
@@ -38,15 +40,23 @@ function row(overrides: Partial<NewPlaceShadowPickRow> = {}): NewPlaceShadowPick
};
}
function rawRow(id: number): unknown {
return testDb.prepare('SELECT * FROM place_shadow_picks WHERE id = ?').get(id);
function rawRow(id: number) {
return findRow(t, PlaceShadowPicks, { id });
}
/** Every stored pick, oldest first. */
function storedPicks() {
return findRows(t, PlaceShadowPicks, {}, { id: 'asc' });
}
/** `created_at` as `datetime('now', '-N seconds')` would write it. */
const secondsAgo = (seconds: number): string => dbNow(new Date(Date.now() - seconds * 1000));
describe('PlaceShadowPicksRepository.insertPick', () => {
it('PSPICKREPO-001: inserts exactly the given columns, nullable ones included', async () => {
await picks.insertPick(row());
const stored = testDb.prepare('SELECT * FROM place_shadow_picks').get() as { id: number };
expect(rawRow(stored.id)).toMatchObject({ query: 'louvre', source: 'nominatim', live_rank: 0, live_count: 5, lang: null });
const [stored] = await storedPicks();
expect(await rawRow(stored.id)).toMatchObject({ query: 'louvre', source: 'nominatim', live_rank: 0, live_count: 5, lang: null });
});
});
@@ -63,7 +73,7 @@ describe('PlaceShadowPicksRepository.page', () => {
it('PSPICKREPO-003: after excludes everything at or below that id', async () => {
await picks.insertPick(row({ query: 'a' }));
const firstId = (testDb.prepare('SELECT id FROM place_shadow_picks').get() as { id: number }).id;
const firstId = (await storedPicks())[0].id;
await picks.insertPick(row({ query: 'b' }));
const page = await picks.page(firstId, 5);
expect(page.map((r) => r.query)).toEqual(['b']);
@@ -78,8 +88,9 @@ describe('PlaceShadowPicksRepository.totals / countBySource / countByLiveRank',
it('PSPICKREPO-005: totals reports COUNT/MIN/MAX across every row', async () => {
await picks.insertPick(row());
await picks.insertPick(row());
testDb.prepare("UPDATE place_shadow_picks SET created_at = '2026-01-01 00:00:00' WHERE id = (SELECT MIN(id) FROM place_shadow_picks)").run();
testDb.prepare("UPDATE place_shadow_picks SET created_at = '2026-06-01 00:00:00' WHERE id = (SELECT MAX(id) FROM place_shadow_picks)").run();
const stored = await storedPicks();
await updateRows(t, PlaceShadowPicks, { id: stored[0].id }, { created_at: '2026-01-01 00:00:00' });
await updateRows(t, PlaceShadowPicks, { id: stored[stored.length - 1].id }, { created_at: '2026-06-01 00:00:00' });
const totals = await picks.totals();
expect(totals).toEqual({ total: 2, oldest: '2026-01-01 00:00:00', newest: '2026-06-01 00:00:00' });
});
@@ -108,6 +119,7 @@ describe('PlaceShadowPicksRepository.totals / countBySource / countByLiveRank',
}
const rows = await picks.countBySource();
const legacy = testDb
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
.prepare('SELECT source, COUNT(*) AS count FROM place_shadow_picks GROUP BY source ORDER BY count DESC')
.all();
expect(rows).toEqual(legacy);
@@ -141,20 +153,20 @@ describe('PlaceShadowPicksRepository.deleteAll / purgeOlderThan', () => {
it('PSPICKREPO-009: purgeOlderThan removes exactly the rows older than the cutoff, proving the deleted set on a seeded table', async () => {
await picks.insertPick(row({ query: 'old' }));
await picks.insertPick(row({ query: 'new' }));
const [oldRow, newRow] = testDb.prepare('SELECT id, query FROM place_shadow_picks ORDER BY id ASC').all() as { id: number; query: string }[];
testDb.prepare("UPDATE place_shadow_picks SET created_at = datetime('now', '-200 days') WHERE id = ?").run(oldRow.id);
testDb.prepare("UPDATE place_shadow_picks SET created_at = datetime('now', '-1 days') WHERE id = ?").run(newRow.id);
const [oldRow, newRow] = await storedPicks();
await updateRows(t, PlaceShadowPicks, { id: oldRow.id }, { created_at: secondsAgo(200 * 86_400) });
await updateRows(t, PlaceShadowPicks, { id: newRow.id }, { created_at: secondsAgo(86_400) });
const removed = await picks.purgeOlderThan(180);
expect(removed).toBe(1);
const survivors = testDb.prepare('SELECT query FROM place_shadow_picks').all() as { query: string }[];
const survivors = await storedPicks();
expect(survivors.map((r) => r.query)).toEqual(['new']);
});
it('PSPICKREPO-010: purgeOlderThan(0) removes rows created before right now, leaving nothing newer than the boundary', async () => {
await picks.insertPick(row());
const { id } = testDb.prepare('SELECT id FROM place_shadow_picks').get() as { id: number };
testDb.prepare("UPDATE place_shadow_picks SET created_at = datetime('now', '-1 seconds') WHERE id = ?").run(id);
const [{ id }] = await storedPicks();
await updateRows(t, PlaceShadowPicks, { id }, { created_at: secondsAgo(1) });
expect(await picks.purgeOlderThan(0)).toBe(1);
});
});