merge dev into feat/postgres-support

This commit is contained in:
Maurice
2026-11-17 11:10:01 +01:00
3032 changed files with 153102 additions and 20800 deletions
@@ -0,0 +1,49 @@
/**
* `Migration20200101046370_a_deleted_chat_message_keeps_no_text`: a message deleted
* before the release loses its text; a live message keeps its own.
*/
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
import { describe, expect, it } from 'vitest';
const TARGET = 'Migration20200101046370_a_deleted_chat_message_keeps_no_text';
async function ormBeforeTarget(): Promise<MikroORM> {
const orm = await createMigrationOrm();
const names = await pendingNames(orm);
const index = names.indexOf(TARGET);
expect(index).toBeGreaterThan(0);
await migrateTo(orm, names[index - 1]);
return orm;
}
describe('a deleted chat message keeps no text', () => {
it('CHAT-DELETED-TEXT-001: blanks the text of deleted messages and leaves live ones alone', async () => {
const orm = await ormBeforeTarget();
try {
await rawExec(
orm,
"INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')",
);
await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'Kyoto')");
await rawExec(
orm,
"INSERT INTO collab_messages (id, trip_id, user_id, text, deleted) VALUES (1, 10, 1, 'meet at 8', 0), (2, 10, 1, 'my door code is 4711', 1)",
);
await migrateTo(orm, TARGET);
const rows = await rawQuery<{ id: number; text: string; deleted: number }>(
orm,
'SELECT id, text, deleted FROM collab_messages ORDER BY id',
);
expect(rows).toEqual([
{ id: 1, text: 'meet at 8', deleted: 0 },
{ id: 2, text: '', deleted: 1 },
]);
} finally {
await orm.close(true);
}
}, 30000);
});
+5 -3
View File
@@ -57,14 +57,16 @@ describe('ALL_ENTITIES', () => {
* + trek_photo_signals, what a photo's pixels say, for picking photos for a book
* + journey_book_revisions, the books a whole-book design replaced, for its undo
* + trip_member_removals, who another member took off a trip, so its invite link refuses them
* + assistant_attachments, the files attached in the trip chat, kept with their conversation)
* + assistant_attachments, the files attached in the trip chat, kept with their conversation
* + mail_ingest_addresses, _prefs, _cursor, _messages and _candidates, the forwarded
* booking mails, the bookings read from them and the switches and addresses behind them)
* is registered, and no two share a class name (a silent duplicate would
* shadow one of them in `orm.getMetadata()`, exactly the kind of drift
* `entity-schema-parity.test.ts` can't see — it iterates the metadata map,
* which de-duplicates by class name).
*/
it('ENT-003: exactly 167 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(167);
it('ENT-003: exactly 173 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(173);
const names = ALL_ENTITIES.map((s) => s.meta.className);
expect(new Set(names).size).toBe(names.length);
});
@@ -61,7 +61,12 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
// (an attached file is only ever written whole, by the turn it was attached in).
// + storage_reclaim_marks: category, key, first_seen_at, size (a mark is only ever written whole, by the reclaim pass).
// + storage_release_queue: category, key, due_at (a queued release is only ever written whole, by the release queue).
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 611;
// + flight_live_states: callsign, service_date, origin, destination (a flight's state is always found and
// written by its key).
// + mail_ingest_addresses: id, token_hash, token_enc, user_id; mail_ingest_prefs: id, user_id; mail_ingest_cursor:
// id, transport, mailbox; mail_ingest_messages: id, transport, dedupe_hash, user_id, size; mail_ingest_candidates:
// id, message_id, user_id (each row is written whole by the mail import, which always knows all of them).
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 632;
describe('entity class fields never carry a NaN initialiser (task-4-review-shape.md, Important 1)', () => {
it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 133 entities', () => {
@@ -0,0 +1,147 @@
/**
* `Migration20200101046380_ireland_gained_its_counties` (#2922): the Atlas ships
* Ireland's 26 counties instead of its four provinces. Cached place regions are
* cleared, hand-marked provinces stay, county names under stale codes take the county
* code, and a hidden province hides its counties.
*/
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
import { afterEach, describe, expect, it } from 'vitest';
const TARGET = 'Migration20200101046380_ireland_gained_its_counties';
const LEINSTER = [
'IE-CW',
'IE-D',
'IE-KE',
'IE-KK',
'IE-LD',
'IE-LH',
'IE-LS',
'IE-MH',
'IE-OY',
'IE-WH',
'IE-WW',
'IE-WX',
];
let orm: MikroORM;
async function ormBeforeTarget(): Promise<MikroORM> {
const o = await createMigrationOrm();
const names = await pendingNames(o);
const index = names.indexOf(TARGET);
expect(index).toBeGreaterThan(0);
await migrateTo(o, names[index - 1]);
return o;
}
async function seedUsers(): Promise<void> {
await rawExec(
orm,
`INSERT INTO users (id, username, email, password_hash) VALUES (1, 'one', 'one@test', 'x'), (2, 'two', 'two@test', 'x')`,
);
}
const visited = (userId: number) =>
rawQuery<{ region_code: string; region_name: string; country_code: string }>(
orm,
'SELECT region_code, region_name, country_code FROM visited_regions WHERE user_id = ? ORDER BY region_code',
[userId],
);
const hidden = async (userId: number) =>
(
await rawQuery<{ region_code: string }>(
orm,
'SELECT region_code FROM hidden_regions WHERE user_id = ? ORDER BY region_code',
[userId],
)
).map((r) => r.region_code);
afterEach(async () => {
await orm?.close(true);
});
describe('Ireland gained its counties', () => {
it('IE-COUNTIES-001: clears the cached Irish place regions and leaves other countries cached', async () => {
orm = await ormBeforeTarget();
await seedUsers();
await rawExec(orm, `INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'Isles')`);
await rawExec(
orm,
`INSERT INTO places (id, trip_id, name, lat, lng) VALUES (1, 1, 'Dublin', 53.34, -6.25), (2, 1, 'Belfast', 54.6, -5.93)`,
);
await rawExec(
orm,
`INSERT INTO place_regions (place_id, country_code, region_code, region_name) VALUES
(1, 'IE', 'IE-L', 'Leinster'), (2, 'GB', 'GB-BELFAST', 'Belfast')`,
);
await migrateTo(orm, TARGET);
expect(await rawQuery(orm, 'SELECT place_id, region_code FROM place_regions ORDER BY place_id')).toEqual([
{ place_id: 2, region_code: 'GB-BELFAST' },
]);
});
it('IE-COUNTIES-002: keeps a marked province and a marked county, and moves a county name onto its code', async () => {
orm = await ormBeforeTarget();
await seedUsers();
await rawExec(
orm,
`INSERT INTO visited_regions (user_id, region_code, region_name, country_code) VALUES
(1, 'IE-L', 'Leinster', 'IE'),
(1, 'IE-KY', 'Kerry', 'IE'),
(1, 'IE-COR', 'County Cork', 'IE'),
(1, 'IE-GALWAY', 'Co. Galway', 'ie'),
(1, 'FR-IDF', 'Ile-de-France', 'FR')`,
);
await migrateTo(orm, TARGET);
expect(await visited(1)).toEqual([
{ region_code: 'FR-IDF', region_name: 'Ile-de-France', country_code: 'FR' },
{ region_code: 'IE-CO', region_name: 'Cork', country_code: 'IE' },
{ region_code: 'IE-G', region_name: 'Galway', country_code: 'ie' },
{ region_code: 'IE-KY', region_name: 'Kerry', country_code: 'IE' },
{ region_code: 'IE-L', region_name: 'Leinster', country_code: 'IE' },
]);
});
it('IE-COUNTIES-003: drops a stale row whose county the user already holds, never touching another user', async () => {
orm = await ormBeforeTarget();
await seedUsers();
await rawExec(
orm,
`INSERT INTO visited_regions (user_id, region_code, region_name, country_code) VALUES
(1, 'IE-D', 'Dublin', 'IE'),
(1, 'IE-DUB', 'County Dublin', 'IE'),
(1, 'IE-DN', 'dublin', 'IE'),
(2, 'IE-DUB', 'County Dublin', 'IE')`,
);
await migrateTo(orm, TARGET);
expect(await visited(1)).toEqual([{ region_code: 'IE-D', region_name: 'Dublin', country_code: 'IE' }]);
expect(await visited(2)).toEqual([{ region_code: 'IE-D', region_name: 'Dublin', country_code: 'IE' }]);
});
it('IE-COUNTIES-004: a hidden province hides each of its counties, once, and stays hidden itself', async () => {
orm = await ormBeforeTarget();
await seedUsers();
await rawExec(
orm,
`INSERT INTO hidden_regions (user_id, region_code, country_code) VALUES
(1, 'IE-L', 'IE'),
(1, 'IE-D', 'IE'),
(2, 'IE-U', 'IE'),
(2, 'FR-IDF', 'FR')`,
);
await migrateTo(orm, TARGET);
expect(await hidden(1)).toEqual([...LEINSTER, 'IE-L'].sort());
expect(await hidden(2)).toEqual(['FR-IDF', 'IE-CN', 'IE-DL', 'IE-MN', 'IE-U']);
});
});
@@ -104,6 +104,14 @@ const UNNUMBERED = [
'Migration20200101046340_a_released_object_outlasts_every_undo_before_it_goes',
'Migration20200101046350_a_place_lies_on_the_real_world',
'Migration20200101046360_a_new_install_starts_with_more_addons_on',
'Migration20200101046370_a_deleted_chat_message_keeps_no_text',
'Migration20200101046380_ireland_gained_its_counties',
'Migration20200101046390_a_trip_can_keep_its_costs_as_totals_only',
'Migration20200101046400_a_booked_flight_shows_where_it_is',
'Migration20200101046410_a_forwarded_booking_mail_lands_in_its_trip',
'Migration20200101046420_a_visit_keeps_its_own_stay',
'Migration20200101046430_a_paused_mail_import_can_tell_its_address_holders',
'Migration20200101046440_a_trip_owns_its_tags',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -0,0 +1,63 @@
/**
* `Migration20200101046430_a_paused_mail_import_can_tell_its_address_holders`:
* `mail_ingest_cursor` is rebuilt so the pause notice job can keep its row
* (`transport = 'notice'`), without losing a reader's position or lease; an
* unknown transport is still refused and a reader stays unique per mailbox.
*/
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
import { describe, expect, it } from 'vitest';
const TARGET = 'Migration20200101046430_a_paused_mail_import_can_tell_its_address_holders';
async function ormBeforeTarget(): Promise<MikroORM> {
const orm = await createMigrationOrm();
const names = await pendingNames(orm);
const index = names.indexOf(TARGET);
expect(index).toBeGreaterThan(0);
await migrateTo(orm, names[index - 1]);
return orm;
}
describe('Mail ingest cursor notice migration', () => {
it('MICURMIG-001: keeps every reader as it was and lets the notice job take its row', async () => {
const orm = await ormBeforeTarget();
try {
await rawExec(
orm,
`INSERT INTO mail_ingest_cursor
(id, transport, mailbox, uid_validity, last_uid, last_ok_at, last_error, lease_owner, lease_until)
VALUES (4, 'imap', 'INBOX', 7, 42, '2026-11-01 10:00:00', 'timeout', 'a', '2026-11-01 10:05:00')`,
);
await expect(
rawExec(orm, "INSERT INTO mail_ingest_cursor (transport, mailbox) VALUES ('notice', 'paused')"),
).rejects.toThrow(/CHECK/);
await migrateTo(orm, TARGET);
expect(await rawQuery(orm, 'SELECT * FROM mail_ingest_cursor')).toEqual([
{
id: 4,
transport: 'imap',
mailbox: 'INBOX',
uid_validity: 7,
last_uid: 42,
last_ok_at: '2026-11-01 10:00:00',
last_error: 'timeout',
lease_owner: 'a',
lease_until: '2026-11-01 10:05:00',
},
]);
await rawExec(orm, "INSERT INTO mail_ingest_cursor (transport, mailbox) VALUES ('notice', 'paused')");
await expect(
rawExec(orm, "INSERT INTO mail_ingest_cursor (transport, mailbox) VALUES ('notice', 'paused')"),
).rejects.toThrow(/UNIQUE/);
await expect(
rawExec(orm, "INSERT INTO mail_ingest_cursor (transport, mailbox) VALUES ('webhook', '')"),
).rejects.toThrow(/CHECK/);
} finally {
await orm.close(true);
}
}, 30000);
});
@@ -119,6 +119,13 @@ describe('migrate-encryption.ts app_settings parity', () => {
}
});
// A forwarding address shows its token through token_enc; a stored mail is sealed in raw_eml_enc.
it('ROTPAR-016: rotates the address tokens and stored mails of the mail import', () => {
const section = script.slice(script.indexOf('--- mail_ingest:'), script.indexOf('--- addons:'));
expect(section).toContain("['mail_ingest_addresses', 'token_enc']");
expect(section).toContain("['mail_ingest_messages', 'raw_eml_enc']");
});
it('ROTPAR-004: rotates every storage.backends secret field for s3', () => {
const fields = storageSecretFields('s3');
expect(fields.length).toBeGreaterThan(0);
@@ -0,0 +1,150 @@
/**
* `CollectionsRepository`: the order of a list's places and the pages
* list_collection_places reads it in (#2647). getCollection (listPlaceRows)
* and a page order the same way, sort_order, then created_at, then id, so two
* places saved in the same second keep one order; a page filters by status,
* label or "no label" and goes on after a position, not an offset.
* COLL-REPO-001 to COLL-REPO-005.
*/
import { CollectionLabels } from '../../../../src/db/entities/CollectionLabels.entity';
import type { CollectionPlaces } from '../../../../src/db/entities/CollectionPlaces.entity';
import { Collections } from '../../../../src/db/entities/Collections.entity';
import type {
CollectionPlacePageRow,
CollectionsRepository,
} from '../../../../src/db/repositories/Collections.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { labelCollectionPlace, makeCollection, makeCollectionPlace } from '../../../helpers/factories/collections';
import { createRow } from '../../../helpers/factories/rows';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import type { EntityData } from '@mikro-orm/core';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: CollectionsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(Collections);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
const SAME_SECOND = '2026-05-01 10:00:00';
/**
* A list of five places: two saved in the same second at position 0, one saved
* earlier at position 0, one at position 1 and one whose position was never
* written (it reads as 0, after the earlier one by its created_at).
*/
async function seedList() {
const { user } = await makeUser(t);
const list = await makeCollection(t, user.id, { name: 'Paris' });
const place = (name: string, overrides: EntityData<CollectionPlaces>) =>
makeCollectionPlace(t, list.id, user.id, { name, ...overrides });
const later = await place('Later', { sort_order: 1, created_at: '2026-04-01 09:00:00' });
const tieA = await place('Tie A', { sort_order: 0, created_at: SAME_SECOND, status: 'want' });
const tieB = await place('Tie B', { sort_order: 0, created_at: SAME_SECOND });
const early = await place('Early', { sort_order: 0, created_at: '2026-03-01 08:00:00', status: 'want' });
const unplaced = await place('Unplaced', { sort_order: null, created_at: '2026-03-15 08:00:00' });
return { user, list, ids: { later: later.id, tieA: tieA.id, tieB: tieB.id, early: early.id, unplaced: unplaced.id } };
}
const names = (rows: Array<Pick<CollectionPlacePageRow, 'name'>>) => rows.map((row) => row.name);
describe('CollectionsRepository: the order of a list', () => {
it('COLL-REPO-001: getCollection orders by position, then saving time, then id', async () => {
const { list } = await seedList();
const rows = await repo.listPlaceRows(list.id);
expect(names(rows)).toEqual(['Early', 'Unplaced', 'Tie A', 'Tie B', 'Later']);
});
});
describe('CollectionsRepository: a page of a list (#2647)', () => {
it('COLL-REPO-002: a page holds the list in that same order and goes on after the position it names', async () => {
const { list, ids } = await seedList();
const first = await repo.listPlacePage(list.id, {}, null, 3);
expect(names(first)).toEqual(['Early', 'Unplaced', 'Tie A']);
// The position a page goes on from: the missing sort_order reads as 0.
expect(first[1]).toMatchObject({ id: ids.unplaced, sort_key: 0, created_key: '2026-03-15 08:00:00' });
const tieA = first[2];
const rest = await repo.listPlacePage(
list.id,
{},
{ sortOrder: tieA.sort_key, createdAt: tieA.created_key, id: tieA.id },
3,
);
expect(names(rest)).toEqual(['Tie B', 'Later']);
expect(await repo.countPlacePage(list.id, {})).toBe(5);
});
it('COLL-REPO-003: a page carries the fields an agent names a place by', async () => {
const { user } = await makeUser(t);
const list = await makeCollection(t, user.id);
await makeCollectionPlace(t, list.id, user.id, {
name: 'Septime',
address: '80 Rue de Charonne',
google_place_id: 'ChIJseptime',
website: 'https://septime-charonne.fr',
phone: '+33 1 43 67 38 29',
});
const [row] = await repo.listPlacePage(list.id, {}, null, 10);
expect(row).toMatchObject({
name: 'Septime',
status: 'idea',
address: '80 Rue de Charonne',
lat: 48.8566,
lng: 2.3522,
google_place_id: 'ChIJseptime',
website: 'https://septime-charonne.fr',
phone: '+33 1 43 67 38 29',
});
});
it('COLL-REPO-004: filters by status and by label, and counts what the filter matches', async () => {
const { list, ids } = await seedList();
const label = await createRow(t, CollectionLabels, { collection: list.id, name: 'Food' });
await labelCollectionPlace(t, ids.tieB, label.id);
await labelCollectionPlace(t, ids.later, label.id);
expect(names(await repo.listPlacePage(list.id, { status: 'want' }, null, 10))).toEqual(['Early', 'Tie A']);
expect(await repo.countPlacePage(list.id, { status: 'want' })).toBe(2);
expect(names(await repo.listPlacePage(list.id, { labelId: label.id }, null, 10))).toEqual(['Tie B', 'Later']);
expect(await repo.countPlacePage(list.id, { labelId: label.id })).toBe(2);
expect(names(await repo.listPlacePage(list.id, { unlabeled: true }, null, 10))).toEqual([
'Early',
'Unplaced',
'Tie A',
]);
expect(await repo.countPlacePage(list.id, { unlabeled: true, status: 'want' })).toBe(2);
});
it('COLL-REPO-005: a place labelled after its page was read does not move the next page of unlabelled ones', async () => {
const { list, ids } = await seedList();
const label = await createRow(t, CollectionLabels, { collection: list.id, name: 'Done' });
const first = await repo.listPlacePage(list.id, { unlabeled: true }, null, 2);
expect(names(first)).toEqual(['Early', 'Unplaced']);
await labelCollectionPlace(t, ids.early, label.id);
await labelCollectionPlace(t, ids.unplaced, label.id);
const last = first[1];
const next = await repo.listPlacePage(
list.id,
{ unlabeled: true },
{ sortOrder: last.sort_key, createdAt: last.created_key, id: last.id },
2,
);
expect(names(next)).toEqual(['Tie A', 'Tie B']);
});
});
@@ -1047,6 +1047,31 @@ describe('DayAssignmentsRepository.insertAssignmentCopy (TP49)', () => {
accommodation_id: null,
});
});
it("ASSIGNREPO-048: carries the visit's own stay_minutes, null when none is given (#3092)", async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const copy = {
day_id: day.id,
place_id: place.id,
order_index: 0,
notes: null,
reservation_status: null,
reservation_notes: null,
reservation_datetime: null,
assignment_time: null,
assignment_end_time: null,
end_day: 0,
};
const withStay = await assignments.insertAssignmentCopy({ ...copy, stay_minutes: 90 });
const without = await assignments.insertAssignmentCopy(copy);
expect(await assignmentCols(withStay, 'stay_minutes')).toEqual({ stay_minutes: 90 });
expect(await assignmentCols(without, 'stay_minutes')).toEqual({ stay_minutes: null });
});
});
describe('DayAssignmentsRepository.setAccommodation (TP57)', () => {
@@ -1079,7 +1104,7 @@ const LEGACY_LIST_ROADTRIP_VISITS = `
SELECT a.id, a.day_id, a.order_index, a.place_id, p.name, p.lat, p.lng,
COALESCE(a.assignment_time, p.place_time) AS time,
COALESCE(a.assignment_end_time, p.end_time) AS end_time,
p.duration_minutes, a.end_day,
COALESCE(a.stay_minutes, p.duration_minutes) AS duration_minutes, a.end_day,
a.leg_transport_mode, a.incoming_leg_transport_mode, p.stop_type, p.fill_percent,
a.accommodation_id, stay.id AS stay_id, stay.check_in, stay.check_out, checkout.day_number AS checkout_day
FROM day_assignments a
@@ -1171,6 +1196,26 @@ describe('DayAssignmentsRepository.listRoadtripVisits (RPL2, roadtrip-plan.servi
});
});
it('ASSIGNREPO-036: two visits of one place keep their own stay, an unset one reads the place (#3092)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id, { name: 'Viewpoint' });
await updateRows(t, Places, { id: place.id }, { duration_minutes: 45 });
const stopped = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
const passed = createDayAssignment(testDb, day.id, place.id, { order_index: 1 });
await withRequestContext(t.orm, () => assignments.setStayMinutes(passed.id, 0));
const visits = await assignments.listRoadtripVisits(trip.id);
expect(visits.map((v) => [v.id, v.duration_minutes])).toEqual([
[stopped.id, 45],
[passed.id, 0],
]);
expect(await assignmentCols(stopped.id, 'stay_minutes')).toEqual({ stay_minutes: null });
expect((await findRow(t, Places, { id: place.id }))?.duration_minutes).toBe(45);
});
it('ASSIGNREPO-033: empty array for a trip with no assignments', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
@@ -0,0 +1,207 @@
/**
* FlightLiveStatesRepository: the stored state of a flight per callsign and
* day, and the reads of flight bookings, endpoints, days and travellers the
* live flight status builds its legs from. FLREPO-001 to FLREPO-007.
*/
import { FlightLiveStates } from '../../../../src/db/entities/FlightLiveStates.entity';
import type {
FlightLiveStatesRepository,
FlightLiveStateWrite,
} from '../../../../src/db/repositories/FlightLiveStates.repository';
import type { DbTimestamp } from '../../../../src/db/types';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import {
addReservationTraveler,
makeReservation,
makeReservationEndpoint,
} from '../../../helpers/factories/reservations';
import { findRows } from '../../../helpers/factories/rows';
import { addTripMember, makeDay, makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: FlightLiveStatesRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(FlightLiveStates);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
function state(overrides: Partial<FlightLiveStateWrite> = {}): FlightLiveStateWrite {
return {
callsign: 'DLH716',
service_date: '2026-07-01',
origin: 'FRA',
destination: 'HND',
phase: 'airborne',
departed_at: '2026-07-01 11:52:00' as DbTimestamp,
landed_at: null,
lat: 55.1,
lng: 60.2,
altitude_ft: 36000,
ground_speed_kt: 480,
track_deg: 51,
vertical_rate_fpm: 0,
on_ground: 0,
registration: 'D-AIXA',
aircraft_type: 'A359',
source: 'adsb.lol',
first_seen_at: '2026-07-01 11:40:00' as DbTimestamp,
last_seen_at: '2026-07-01 14:00:00' as DbTimestamp,
fetched_at: '2026-07-01 14:00:01' as DbTimestamp,
next_poll_at: '2026-07-01 14:03:01' as DbTimestamp,
fail_count: 0,
departed_notified: 1,
landed_notified: 0,
delay_notified: 0,
...overrides,
};
}
describe('FlightLiveStatesRepository: states', () => {
it('FLREPO-001: writes a whole state and replaces it under the same key', async () => {
await repo.saveState(state());
await repo.saveState(state({ phase: 'landed', landed_at: '2026-07-01 23:10:00' as DbTimestamp, lat: 35.5 }));
await repo.saveState(state({ service_date: '2026-07-02', phase: 'scheduled' }));
await repo.saveState(state({ callsign: 'BAW12' }));
const rows = await repo.findForCallsigns(['DLH716']);
expect(rows.map((r) => [r.service_date, r.phase, r.landed_at, r.lat]).sort()).toEqual([
['2026-07-01', 'landed', '2026-07-01 23:10:00', 35.5],
['2026-07-02', 'scheduled', null, 55.1],
]);
expect(rows.find((r) => r.service_date === '2026-07-01')).toMatchObject({
registration: 'D-AIXA',
departed_notified: 1,
next_poll_at: '2026-07-01 14:03:01',
});
expect(await repo.findForCallsigns([])).toEqual([]);
});
it('FLREPO-001b: two sectors of one flight number on one day are two states', async () => {
await repo.saveState(state({ callsign: 'DLH754', origin: 'FRA', destination: 'BOM' }));
await repo.saveState(state({ callsign: 'DLH754', origin: 'BOM', destination: 'SIN', phase: 'scheduled' }));
const rows = await repo.findForCallsigns(['DLH754']);
expect(rows.map((r) => [r.origin, r.destination, r.phase]).sort()).toEqual([
['BOM', 'SIN', 'scheduled'],
['FRA', 'BOM', 'airborne'],
]);
});
it('FLREPO-002: drops the states of flights that departed before a day', async () => {
await repo.saveState(state({ service_date: '2026-05-30' }));
await repo.saveState(state({ service_date: '2026-06-01' }));
expect(await repo.deleteBefore('2026-06-01')).toBe(1);
expect((await findRows(t, FlightLiveStates)).map((r) => r.service_date)).toEqual(['2026-06-01']);
});
});
describe('FlightLiveStatesRepository: bookings', () => {
it('FLREPO-003: the flight bookings of one trip with the trip title, nothing of other types or trips', async () => {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id, { title: 'Japan' });
const other = await makeTrip(t, user.id);
const flight = await makeReservation(t, trip.id, {
title: 'FRA to HND',
type: 'flight',
metadata: '{"flight_number":"LH 716"}',
reservation_time: '2026-07-01T13:40',
});
await makeReservation(t, trip.id, { title: 'Hotel', type: 'hotel' });
await makeReservation(t, other.id, { title: 'Elsewhere', type: 'flight' });
expect(await repo.listFlightBookingsForTrip(trip.id)).toEqual([
{
id: flight.id,
trip_id: trip.id,
trip_title: 'Japan',
metadata: '{"flight_number":"LH 716"}',
day_id: null,
end_day_id: null,
reservation_time: '2026-07-01T13:40',
reservation_end_time: null,
},
]);
});
it('FLREPO-004: the poll candidates skip archived trips and trips whose dates lie outside the span', async () => {
const { user } = await makeUser(t);
const current = await makeTrip(t, user.id, { start_date: '2026-06-28', end_date: '2026-07-05' });
const undated = await makeTrip(t, user.id);
const past = await makeTrip(t, user.id, { start_date: '2026-05-01', end_date: '2026-05-03' });
const future = await makeTrip(t, user.id, { start_date: '2026-09-01', end_date: '2026-09-03' });
const archived = await makeTrip(t, user.id, { start_date: '2026-06-28', end_date: '2026-07-05', is_archived: 1 });
await [current, undated, past, future, archived].reduce(async (previous, trip) => {
await previous;
await makeReservation(t, trip.id, { title: 'Flight', type: 'flight' });
}, Promise.resolve());
const rows = await repo.listFlightBookingsBetween('2026-06-29', '2026-07-03');
expect(rows.map((r) => r.trip_id).sort((a, b) => a - b)).toEqual([current.id, undated.id].sort((a, b) => a - b));
});
it('FLREPO-005: the endpoints of the bookings in their order, and none for no bookings', async () => {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id);
const flight = await makeReservation(t, trip.id, { title: 'Flight', type: 'flight' });
await makeReservationEndpoint(t, flight.id, { role: 'to', sequence: 1, code: 'HND', name: 'Haneda (HND)' });
await makeReservationEndpoint(t, flight.id, {
role: 'from',
sequence: 0,
code: 'FRA',
name: 'Frankfurt (FRA)',
timezone: 'Europe/Berlin',
local_date: '2026-07-01',
local_time: '13:40',
});
const endpoints = await repo.listEndpoints([flight.id]);
expect(endpoints.map((e) => [e.sequence, e.code])).toEqual([
[0, 'FRA'],
[1, 'HND'],
]);
expect(endpoints[0]).toMatchObject({
reservation_id: flight.id,
role: 'from',
timezone: 'Europe/Berlin',
local_date: '2026-07-01',
local_time: '13:40',
});
expect(await repo.listEndpoints([])).toEqual([]);
});
it('FLREPO-006: the dates of trip days, leaving out a day without one', async () => {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id);
const dated = await makeDay(t, trip.id, { day_number: 1, date: '2026-07-01' });
const undated = await makeDay(t, trip.id, { day_number: 2, date: null });
expect(await repo.listDayDates([dated.id, undated.id])).toEqual([{ id: dated.id, date: '2026-07-01' }]);
expect(await repo.listDayDates([])).toEqual([]);
});
it('FLREPO-007: the travellers put on a booking who still belong to the trip, never a removed member', async () => {
const { user } = await makeUser(t);
const { user: friend } = await makeUser(t);
const { user: removed } = await makeUser(t);
const trip = await makeTrip(t, user.id);
await addTripMember(t, trip.id, friend.id);
const flight = await makeReservation(t, trip.id, { title: 'Flight', type: 'flight' });
expect(await repo.listTravelerIds(flight.id)).toEqual([]);
await addReservationTraveler(t, flight.id, friend.id);
await addReservationTraveler(t, flight.id, user.id);
// On the traveller list from before, but no longer on the trip.
await addReservationTraveler(t, flight.id, removed.id);
expect(await repo.listTravelerIds(flight.id)).toEqual([user.id, friend.id].sort((a, b) => a - b));
});
});
@@ -0,0 +1,110 @@
/**
* The forwarding addresses through their repository: a person's own address
* and a trip's are told apart, renewing revokes instead of deleting so the old
* token is still recognised, a mail notes the address it came in on, and the
* people who hold a live address are named for the pause notice.
*/
import { MailIngestAddresses } from '../../../../src/db/entities/MailIngestAddresses.entity';
import type { MailIngestAddressesRepository } from '../../../../src/db/repositories/MailIngestAddresses.repository';
import { dbNow } from '../../../../src/db/types';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let addresses: MailIngestAddressesRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
addresses = t.repo(MailIngestAddresses);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
const AT = dbNow(new Date('2026-11-01T10:00:00Z'));
const LATER = dbNow(new Date('2026-11-02T10:00:00Z'));
describe('MailIngestAddressesRepository', () => {
it('keeps a person’s own address apart from a trip’s', async () => {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id);
const own = await addresses.insertAddress({
userId: user.id,
tripId: null,
tokenHash: 'h-own',
tokenEnc: 'e-own',
createdAt: AT,
});
const forTrip = await addresses.insertAddress({
userId: user.id,
tripId: trip.id,
tokenHash: 'h-trip',
tokenEnc: 'e-trip',
createdAt: AT,
});
expect((await addresses.findLive(user.id, null))?.id).toBe(own);
expect((await addresses.findLive(user.id, trip.id))?.id).toBe(forTrip);
expect(await addresses.findById(forTrip)).toMatchObject({ trip_id: trip.id, token_enc: 'e-trip' });
expect(await addresses.findById(forTrip + 100)).toBeNull();
});
it('revokes the live address of one scope only, and still finds a revoked token', async () => {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id);
const own = await addresses.insertAddress({
userId: user.id,
tripId: null,
tokenHash: 'a',
tokenEnc: 'x',
createdAt: AT,
});
await addresses.insertAddress({ userId: user.id, tripId: trip.id, tokenHash: 'b', tokenEnc: 'y', createdAt: AT });
expect(await addresses.revokeLive(user.id, null, LATER)).toBe(1);
expect(await addresses.findLive(user.id, null)).toBeNull();
expect(await addresses.findLive(user.id, trip.id)).not.toBeNull();
expect(await addresses.findByTokenHash('a')).toMatchObject({ id: own, revoked_at: LATER });
expect(await addresses.findByTokenHash('none')).toBeNull();
expect(await addresses.revokeLive(user.id, trip.id, LATER)).toBe(1);
expect(await addresses.findLive(user.id, trip.id)).toBeNull();
});
it('notes when a mail came in', async () => {
const { user } = await makeUser(t);
const id = await addresses.insertAddress({
userId: user.id,
tripId: null,
tokenHash: 'c',
tokenEnc: 'z',
createdAt: AT,
});
await addresses.touchUsed(id, LATER);
expect((await addresses.findById(id))?.last_used_at).toBe(LATER);
});
it('names each person who holds an address that is not revoked, once', async () => {
const { user: mia } = await makeUser(t);
const { user: noah } = await makeUser(t);
const trip = await makeTrip(t, mia.id);
await addresses.insertAddress({ userId: mia.id, tripId: null, tokenHash: 'm1', tokenEnc: 'e', createdAt: AT });
await addresses.insertAddress({ userId: mia.id, tripId: trip.id, tokenHash: 'm2', tokenEnc: 'e', createdAt: AT });
await addresses.insertAddress({ userId: noah.id, tripId: null, tokenHash: 'n1', tokenEnc: 'e', createdAt: AT });
expect(await addresses.listHolders()).toEqual([mia.id, noah.id].sort((a, b) => a - b));
await addresses.revokeLive(noah.id, null, LATER);
expect(await addresses.listHolders()).toEqual([mia.id]);
});
});
@@ -0,0 +1,392 @@
/**
* The bookings read from mails through their repository, and what it reads
* of the trips they may go to: a decision lands once, an undone booking is
* remembered per trip, and only the person's open trips are weighed.
*/
import { MailIngestAddresses } from '../../../../src/db/entities/MailIngestAddresses.entity';
import { MailIngestCandidates } from '../../../../src/db/entities/MailIngestCandidates.entity';
import { MailIngestMessages } from '../../../../src/db/entities/MailIngestMessages.entity';
import type { MailIngestAddressesRepository } from '../../../../src/db/repositories/MailIngestAddresses.repository';
import type {
MailIngestCandidateInsert,
MailIngestCandidatesRepository,
} from '../../../../src/db/repositories/MailIngestCandidates.repository';
import type { MailIngestMessagesRepository } from '../../../../src/db/repositories/MailIngestMessages.repository';
import { dbNow } from '../../../../src/db/types';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { addBudgetItemPayer, makeBudgetItem } from '../../../helpers/factories/budget';
import { makeDayAssignment } from '../../../helpers/factories/itinerary';
import { makePlace } from '../../../helpers/factories/places';
import { makeReservation } from '../../../helpers/factories/reservations';
import { addTripMember, makeTrip, readTripDays } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let candidates: MailIngestCandidatesRepository;
let messages: MailIngestMessagesRepository;
let addresses: MailIngestAddressesRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
candidates = t.repo(MailIngestCandidates);
messages = t.repo(MailIngestMessages);
addresses = t.repo(MailIngestAddresses);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
const at = (iso: string) => dbNow(new Date(iso));
const DAY1 = at('2026-11-01T10:00:00Z');
async function mailOf(userId: number): Promise<number> {
const addressId = await addresses.insertAddress({
userId,
tripId: null,
tokenHash: `h${userId}`,
tokenEnc: 'e',
createdAt: DAY1,
});
const id = await messages.insertIfNew({
transport: 'upload',
messageIdHdr: null,
dedupeHash: `d${userId}`,
addressId,
userId,
tripId: null,
size: 1,
rawEnc: 'enc',
receivedAt: DAY1,
});
if (id === null) throw new Error('the mail was stored already');
return id;
}
function entry(messageId: number, userId: number, over: Partial<MailIngestCandidateInsert> = {}) {
return candidates.insertCandidate({
messageId,
userId,
position: 0,
itemJson: '{}',
source: 'ai',
checksJson: '{}',
uncertainFields: '[]',
matchJson: null,
suggestedTripId: null,
dedupeKey: null,
contentHash: 'c1',
resolution: 'pending',
reason: 'trip_ambiguous',
createdAt: DAY1,
...over,
});
}
describe('MailIngestCandidatesRepository: the entries', () => {
it('lists a mail’s entries in order and counts the waiting ones', async () => {
const { user } = await makeUser(t);
const mail = await mailOf(user.id);
const second = await entry(mail, user.id, { position: 1 });
const first = await entry(mail, user.id, { position: 0, resolution: 'duplicate', reason: null });
expect((await candidates.listForMessage(mail)).map((row) => row.id)).toEqual([first, second]);
expect(await candidates.countPending(user.id)).toBe(1);
expect(await candidates.findById(second)).toMatchObject({ source: 'ai', reason: 'trip_ambiguous' });
expect(await candidates.findById(second + 10)).toBeNull();
});
it('decides an entry once, and records its documents afterwards', async () => {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id);
const mail = await mailOf(user.id);
const id = await entry(mail, user.id);
const patch = {
resolution: 'applied',
reason: null,
resolvedTripId: trip.id,
createdIdsJson: '{"reservation_ids":[1]}',
resolvedBy: user.id,
resolvedAt: DAY1,
undoUntil: at('2026-11-08T10:00:00Z'),
};
expect(await candidates.resolve(id, ['pending'], patch)).toBe(true);
expect(await candidates.resolve(id, ['pending'], patch)).toBe(false);
await candidates.setAttachments(id, '{"reservation_ids":[1],"file_ids":[2]}', null);
expect(await candidates.findById(id)).toMatchObject({
resolution: 'applied',
resolved_trip_id: trip.id,
created_ids_json: '{"reservation_ids":[1],"file_ids":[2]}',
attach_error: null,
});
});
it('decides an added entry only while it still holds the trip and ids it was read with', async () => {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id);
const other = await makeTrip(t, user.id);
const mail = await mailOf(user.id);
const id = await entry(mail, user.id);
const added = {
resolution: 'applied',
reason: null,
resolvedTripId: trip.id,
createdIdsJson: '{"reservation_ids":[1]}',
resolvedBy: user.id,
resolvedAt: DAY1,
undoUntil: at('2026-11-08T10:00:00Z'),
};
expect(await candidates.resolve(id, ['pending'], added)).toBe(true);
const undone = { ...added, resolution: 'undone', undoUntil: null };
expect(
await candidates.resolve(id, ['applied'], undone, { tripId: other.id, createdIdsJson: added.createdIdsJson }),
).toBe(false);
expect(await candidates.resolve(id, ['applied'], undone, { tripId: trip.id, createdIdsJson: '{"x":1}' })).toBe(
false,
);
expect(await candidates.resolve(id, ['applied'], undone, { tripId: trip.id, createdIdsJson: null })).toBe(false);
expect(await candidates.findById(id)).toMatchObject({ resolution: 'applied' });
expect(
await candidates.resolve(id, ['applied'], undone, { tripId: trip.id, createdIdsJson: added.createdIdsJson }),
).toBe(true);
expect(await candidates.findById(id)).toMatchObject({ resolution: 'undone', resolved_trip_id: trip.id });
});
it('writes an entry decided as it is written with its trip, ids and undo window', async () => {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id);
const until = at('2026-11-08T10:00:00Z');
const id = await entry(await mailOf(user.id), user.id, {
resolution: 'auto_applied',
reason: null,
resolvedTripId: trip.id,
createdIdsJson: '{"reservation_ids":[3]}',
resolvedAt: DAY1,
undoUntil: until,
});
expect(await candidates.findById(id)).toMatchObject({
resolved_trip_id: trip.id,
created_ids_json: '{"reservation_ids":[3]}',
resolved_at: DAY1,
undo_until: until,
});
});
it('remembers a booking undone in a trip by its content', async () => {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id);
const id = await entry(await mailOf(user.id), user.id, { contentHash: 'same' });
expect(await candidates.wasUndoneInTrip(trip.id, 'same')).toBe(false);
await candidates.resolve(id, ['pending'], {
resolution: 'undone',
reason: null,
resolvedTripId: trip.id,
createdIdsJson: null,
resolvedBy: user.id,
resolvedAt: DAY1,
undoUntil: null,
});
expect(await candidates.wasUndoneInTrip(trip.id, 'same')).toBe(true);
expect(await candidates.wasUndoneInTrip(trip.id, 'other')).toBe(false);
});
it('deletes decided entries past the cutoff and keeps the waiting ones', async () => {
const { user } = await makeUser(t);
const mail = await mailOf(user.id);
const waiting = await entry(mail, user.id);
const decided = await entry(mail, user.id, { position: 1 });
await candidates.resolve(decided, ['pending'], {
resolution: 'discarded',
reason: null,
resolvedTripId: null,
createdIdsJson: null,
resolvedBy: user.id,
resolvedAt: at('2026-07-01T10:00:00Z'),
undoUntil: null,
});
expect(await candidates.deleteResolvedBefore(at('2026-08-01T00:00:00Z'))).toBe(1);
expect(await candidates.findById(waiting)).not.toBeNull();
expect(await candidates.findById(decided)).toBeNull();
});
});
describe('MailIngestCandidatesRepository: what it reads of the trips', () => {
it('lists the person’s open trips, owned or joined, newest start first', async () => {
const { user } = await makeUser(t);
const { user: other } = await makeUser(t);
const owned = await makeTrip(t, user.id, { start_date: '2027-03-01', end_date: '2027-03-03', currency: 'JPY' });
const joined = await makeTrip(t, other.id, { start_date: '2027-05-01', end_date: '2027-05-02' });
await addTripMember(t, joined.id, user.id);
const undated = await makeTrip(t, user.id);
await makeTrip(t, user.id, { start_date: '2026-01-01', end_date: '2026-01-02' });
await makeTrip(t, user.id, { start_date: '2027-06-01', end_date: '2027-06-02', is_archived: 1 });
await makeTrip(t, other.id, { start_date: '2027-07-01', end_date: '2027-07-02' });
const trips = await candidates.listOpenTrips(user.id, '2026-10-01', 20);
expect(trips.map((trip) => trip.id).sort()).toEqual([owned.id, joined.id, undated.id].sort());
expect(trips.find((trip) => trip.id === owned.id)).toMatchObject({ user_id: user.id, currency: 'JPY' });
expect(await candidates.listOpenTrips(user.id, '2026-10-01', 1)).toHaveLength(1);
});
it('finds one open trip of the person whatever its dates, and none of a stranger', async () => {
const { user } = await makeUser(t);
const { user: other } = await makeUser(t);
const ended = await makeTrip(t, user.id, { start_date: '2025-01-01', end_date: '2025-01-02' });
const archived = await makeTrip(t, user.id, { is_archived: 1 });
const foreign = await makeTrip(t, other.id);
expect(await candidates.findOpenTrip(user.id, ended.id)).toMatchObject({ id: ended.id, user_id: user.id });
expect(await candidates.findOpenTrip(user.id, archived.id)).toBeNull();
expect(await candidates.findOpenTrip(user.id, foreign.id)).toBeNull();
await addTripMember(t, foreign.id, user.id);
expect(await candidates.findOpenTrip(user.id, foreign.id)).toMatchObject({ id: foreign.id });
});
it('reads the dated days and the placed places of trips', async () => {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id, { start_date: '2027-03-01', end_date: '2027-03-02' });
await makePlace(t, trip.id, { name: 'Hotel Sakura', address: 'Tokyo', lat: 35.68, lng: 139.76 });
await makePlace(t, trip.id, { name: 'Somewhere', lat: null, lng: null });
const days = await candidates.listDatedDays([trip.id]);
expect(days.map(({ trip_id, date }) => [trip_id, date])).toEqual([
[trip.id, '2027-03-01'],
[trip.id, '2027-03-02'],
]);
expect(days.every((day) => day.id > 0)).toBe(true);
expect(await candidates.listDatedDays([])).toEqual([]);
expect(await candidates.listPlacesWithPosition([trip.id])).toEqual([
{ trip_id: trip.id, name: 'Hotel Sakura', address: 'Tokyo', lat: 35.68, lng: 139.76 },
]);
expect(await candidates.listPlacesWithPosition([])).toEqual([]);
});
it('reads the person a mail is for', async () => {
const { user } = await makeUser(t, { username: 'mia', email: 'mia@example.com' });
expect(await candidates.findPerson(user.id)).toEqual({
id: user.id,
username: 'mia',
email: 'mia@example.com',
role: 'user',
});
expect(await candidates.findPerson(user.id + 100)).toBeNull();
});
it('finds a booking an import stored under a key, and one that looks the same', async () => {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id);
await makeReservation(t, trip.id, {
type: 'flight',
reservation_time: '2027-03-01T10:00',
confirmation_number: 'ABC123',
external_source: 'mail',
external_id: 'ABC123|flight|2027-03-01|hnd-itm',
});
const key = 'ABC123|flight|2027-03-01|hnd-itm';
expect(await candidates.tripHasExternal(trip.id, ['import', 'mail'], key)).toBe(true);
expect(await candidates.tripHasExternal(trip.id, ['import'], key)).toBe(false);
const none = { type: 'flight', startFrom: null, startTo: null, confirmation: null };
expect(await candidates.tripHasSimilar(trip.id, none)).toBe(false);
expect(await candidates.tripHasSimilar(trip.id, { ...none, confirmation: 'ABC123' })).toBe(true);
expect(
await candidates.tripHasSimilar(trip.id, { ...none, startFrom: '2027-03-01T09:30', startTo: '2027-03-01T10:30' }),
).toBe(true);
expect(
await candidates.tripHasSimilar(trip.id, {
...none,
type: 'train',
startFrom: '2027-03-01T09:30',
startTo: '2027-03-01T10:30',
}),
).toBe(false);
});
it('tells a place something still names from one nothing does', async () => {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id, { start_date: '2027-03-01', end_date: '2027-03-01' });
const [day] = await readTripDays(t, trip.id);
const free = await makePlace(t, trip.id);
const booked = await makePlace(t, trip.id);
const planned = await makePlace(t, trip.id);
await makeReservation(t, trip.id, { place: booked.id });
await makeDayAssignment(t, day.id, planned.id);
expect(await candidates.placeInUse(free.id)).toBe(false);
expect(await candidates.placeInUse(booked.id)).toBe(true);
expect(await candidates.placeInUse(planned.id)).toBe(true);
});
it('counts the payers of costs', async () => {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id);
const paid = await makeBudgetItem(t, trip.id);
const open = await makeBudgetItem(t, trip.id);
await addBudgetItemPayer(t, paid.id, user.id, 100);
expect(await candidates.countPayers([paid.id, open.id])).toBe(1);
expect(await candidates.countPayers([open.id])).toBe(0);
expect(await candidates.countPayers([])).toBe(0);
});
});
describe('MailIngestCandidatesRepository: the inbox and its counts', () => {
it('pages a person’s open or decided entries, newest first', async () => {
const { user } = await makeUser(t);
const { user: other } = await makeUser(t);
const mail = await mailOf(user.id);
const oldest = await entry(mail, user.id);
const middle = await entry(mail, user.id, { position: 1 });
const newest = await entry(mail, user.id, { position: 2 });
const decided = await entry(mail, user.id, { position: 3, resolution: 'discarded', reason: null });
await entry(await mailOf(other.id), other.id);
const open = await candidates.listForUser(user.id, true, null, 2);
expect(open.map((row) => row.id)).toEqual([newest, middle]);
expect((await candidates.listForUser(user.id, true, middle, 10)).map((row) => row.id)).toEqual([oldest]);
expect((await candidates.listForUser(user.id, false, null, 10)).map((row) => row.id)).toEqual([decided]);
});
it('names only the trips the reader owns or joined', async () => {
const { user } = await makeUser(t);
const { user: other } = await makeUser(t);
const owned = await makeTrip(t, user.id, { title: 'Japan', start_date: '2027-03-01', end_date: '2027-03-03' });
const joined = await makeTrip(t, other.id, { title: 'Lisbon' });
await addTripMember(t, joined.id, user.id);
const foreign = await makeTrip(t, other.id, { title: 'Secret' });
const refs = await candidates.listTripRefs(user.id, [owned.id, joined.id, foreign.id]);
expect(refs.sort((a, b) => a.id - b.id)).toEqual([
{ id: owned.id, title: 'Japan', start_date: '2027-03-01', end_date: '2027-03-03' },
{ id: joined.id, title: 'Lisbon', start_date: null, end_date: null },
]);
expect(await candidates.listTripRefs(user.id, [])).toEqual([]);
});
it('counts the entries made since a time by outcome, and the waiting ones per person', async () => {
const { user } = await makeUser(t);
const { user: other } = await makeUser(t);
const mail = await mailOf(user.id);
await entry(mail, user.id);
await entry(mail, user.id, { position: 1 });
await entry(mail, user.id, { position: 2, resolution: 'auto_applied', reason: null });
await entry(mail, user.id, { position: 3, resolution: 'undone', createdAt: at('2026-10-01T10:00:00Z') });
await entry(await mailOf(other.id), other.id);
const tally = await candidates.tallyResolutionsSince(at('2026-10-15T00:00:00Z'));
expect(tally.sort((a, b) => a.resolution.localeCompare(b.resolution))).toEqual([
{ resolution: 'auto_applied', n: 1 },
{ resolution: 'pending', n: 3 },
]);
expect(await candidates.pendingPerUser()).toEqual([2, 1]);
});
});
@@ -0,0 +1,74 @@
/**
* The readers' cursor: one holder of a lease at a time, a lease that ran out
* is taken over, and a run's position and error are kept for the admin.
*/
import { MailIngestCursor } from '../../../../src/db/entities/MailIngestCursor.entity';
import type { MailIngestCursorRepository } from '../../../../src/db/repositories/MailIngestCursor.repository';
import { dbNow } from '../../../../src/db/types';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let cursor: MailIngestCursorRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
cursor = t.repo(MailIngestCursor);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
const T0 = dbNow(new Date('2026-11-01T10:00:00Z'));
const T1 = dbNow(new Date('2026-11-01T10:05:00Z'));
const T2 = dbNow(new Date('2026-11-01T10:10:00Z'));
describe('MailIngestCursorRepository', () => {
it('gives the lease to one owner until it runs out or is given back', async () => {
expect(await cursor.acquireLease('pipeline', '', 'a', T1, T0)).toBe(true);
expect(await cursor.acquireLease('pipeline', '', 'b', T1, T0)).toBe(false);
// The holder renews its own lease.
expect(await cursor.acquireLease('pipeline', '', 'a', T2, T0)).toBe(true);
// Run out: another takes it.
expect(await cursor.acquireLease('pipeline', '', 'b', T2, dbNow(new Date('2026-11-01T10:11:00Z')))).toBe(true);
await cursor.releaseLease('pipeline', '', 'a');
expect(await cursor.findCursor('pipeline', '')).toMatchObject({ lease_owner: 'b' });
await cursor.releaseLease('pipeline', '', 'b');
expect(await cursor.findCursor('pipeline', '')).toMatchObject({ lease_owner: null, lease_until: null });
});
it('keeps the position of a good run and the error of a bad one', async () => {
await cursor.acquireLease('imap', 'INBOX', 'a', T1, T0);
await cursor.recordOk('imap', 'INBOX', T0, { uidValidity: 7, lastUid: 42 });
await cursor.recordError('imap', 'INBOX', 'x'.repeat(600));
let row = await cursor.findCursor('imap', 'INBOX');
expect(row).toMatchObject({ uid_validity: 7, last_uid: 42, last_ok_at: T0 });
expect(row?.last_error).toHaveLength(500);
await cursor.recordOk('imap', 'INBOX', T1);
row = await cursor.findCursor('imap', 'INBOX');
expect(row).toMatchObject({ uid_validity: 7, last_uid: 42, last_ok_at: T1, last_error: null });
await cursor.forgetOk('imap', 'INBOX');
expect(await cursor.findCursor('imap', 'INBOX')).toMatchObject({ uid_validity: 7, last_ok_at: null });
expect(await cursor.findCursor('cloud', '')).toBeNull();
});
it('keeps the pause notice as a reader of its own, as the schema allows', async () => {
// The pause job takes this lease before it tells anyone; the insert behind
// it once failed the transport CHECK, so nobody was ever told.
expect(await cursor.acquireLease('notice', 'paused', 'a', T1, T0)).toBe(true);
await cursor.recordOk('notice', 'paused', T0);
expect(await cursor.findCursor('notice', 'paused')).toMatchObject({ last_ok_at: T0, lease_owner: 'a' });
});
});
@@ -0,0 +1,224 @@
/**
* Forwarded mails through their repository: a mail delivered twice is stored
* once, a due mail is claimed by one run, a run whose claim ran out hands the
* mail on, and the retention keeps a mail while its inbox entry waits.
*/
import { MailIngestAddresses } from '../../../../src/db/entities/MailIngestAddresses.entity';
import { MailIngestCandidates } from '../../../../src/db/entities/MailIngestCandidates.entity';
import { MailIngestMessages } from '../../../../src/db/entities/MailIngestMessages.entity';
import type { MailIngestAddressesRepository } from '../../../../src/db/repositories/MailIngestAddresses.repository';
import type { MailIngestCandidatesRepository } from '../../../../src/db/repositories/MailIngestCandidates.repository';
import type {
MailIngestMessageOutcome,
MailIngestMessagesRepository,
} from '../../../../src/db/repositories/MailIngestMessages.repository';
import { dbNow } from '../../../../src/db/types';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let messages: MailIngestMessagesRepository;
let addresses: MailIngestAddressesRepository;
let candidates: MailIngestCandidatesRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
messages = t.repo(MailIngestMessages);
addresses = t.repo(MailIngestAddresses);
candidates = t.repo(MailIngestCandidates);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
const at = (iso: string) => dbNow(new Date(iso));
const DAY1 = at('2026-11-01T10:00:00Z');
async function inbox() {
const { user } = await makeUser(t);
const addressId = await addresses.insertAddress({
userId: user.id,
tripId: null,
tokenHash: `h${user.id}`,
tokenEnc: 'e',
createdAt: DAY1,
});
return { userId: user.id, addressId };
}
/** Stores a mail and answers its id; a second store of the same hash fails the test. */
async function store(box: { userId: number; addressId: number }, hash: string, receivedAt = DAY1): Promise<number> {
const id = await insert(box, hash, receivedAt);
if (id === null) throw new Error(`mail ${hash} was stored already`);
return id;
}
function insert(box: { userId: number; addressId: number }, hash: string, receivedAt = DAY1) {
return messages.insertIfNew({
transport: 'upload',
messageIdHdr: `<${hash}@x>`,
dedupeHash: hash,
addressId: box.addressId,
userId: box.userId,
tripId: null,
size: 10,
rawEnc: 'enc',
receivedAt,
});
}
const DONE: MailIngestMessageOutcome = {
status: 'processed',
reason: null,
subject: 'Booking',
fromAddr: 'a@b.c',
fromVerified: true,
authResults: 'dkim=pass',
hints: '[]',
attachments: '[]',
forwardingCode: null,
aiUsed: true,
processedAt: DAY1,
};
describe('MailIngestMessagesRepository', () => {
it('stores a mail once and finds it by its hash', async () => {
const box = await inbox();
const id = await store(box, 'm1');
expect(await insert(box, 'm1')).toBeNull();
expect(await messages.findIdByDedupeHash('m1')).toBe(id);
expect(await messages.findIdByDedupeHash('m2')).toBeNull();
expect(await messages.findById(id)).toMatchObject({ status: 'queued', attempts: 0, raw_eml_enc: 'enc' });
expect(await messages.findById(id + 1)).toBeNull();
});
it('counts the mails of an address and the AI-read mails of a person since a time', async () => {
const box = await inbox();
const first = await store(box, 'c1', at('2026-10-31T10:00:00Z'));
await store(box, 'c2', DAY1);
expect(await messages.countForAddressSince(box.addressId, at('2026-11-01T00:00:00Z'))).toBe(1);
await messages.finish(first, DONE);
expect(await messages.countAiReadSince(box.userId, at('2026-10-31T00:00:00Z'))).toBe(1);
expect(await messages.countAiReadSince(box.userId, at('2026-11-01T00:00:00Z'))).toBe(0);
});
it('lists mails without their content, and counts everyone’s by status, reason and AI', async () => {
const box = await inbox();
const read = await store(box, 'h1');
const dropped = await store(box, 'h2');
await store(box, 'h3', at('2026-10-01T10:00:00Z'));
await messages.finish(read, DONE);
await messages.finish(dropped, { ...DONE, status: 'discarded', reason: 'newsletter', aiUsed: false });
const heads = await messages.listHeads([read, dropped]);
expect(heads.map((head) => head.id).sort()).toEqual([read, dropped].sort());
expect(heads[0]).not.toHaveProperty('raw_eml_enc');
expect(heads[0]).not.toHaveProperty('auth_results');
expect(await messages.listHeads([])).toEqual([]);
const tally = await messages.tallySince(at('2026-10-15T00:00:00Z'));
expect(tally.sort((a, b) => a.status.localeCompare(b.status))).toEqual([
{ status: 'discarded', reason: 'newsletter', n: 1 },
{ status: 'processed', reason: null, n: 1 },
]);
expect(await messages.countAllAiReadSince(at('2026-10-15T00:00:00Z'))).toBe(1);
});
it('claims a due mail for one run and lets a claim that ran out go to the next', async () => {
const box = await inbox();
const id = await store(box, 'd1');
await store(box, 'd2', at('2026-11-05T10:00:00Z'));
const now = at('2026-11-01T11:00:00Z');
const lease = at('2026-11-01T11:10:00Z');
expect(await messages.claimDue(now, lease, 3)).toEqual([id]);
expect(await messages.claimDue(now, lease, 3)).toEqual([]);
const later = at('2026-11-01T11:20:00Z');
expect(await messages.claimDue(later, at('2026-11-01T11:30:00Z'), 3)).toEqual([id]);
expect(await messages.findById(id)).toMatchObject({ status: 'processing', attempts: 2 });
await messages.retryLater(id, at('2026-11-01T12:00:00Z'));
expect(await messages.claimDue(later, lease, 3)).toEqual([]);
expect(await messages.claimDue(at('2026-11-01T12:00:00Z'), lease, 3)).toEqual([id]);
await messages.finish(id, DONE);
expect(await messages.findById(id)).toMatchObject({
status: 'processed',
ai_used: 1,
from_verified: 1,
lease_until: null,
});
});
it('purges a mail once it is done and nothing waits on it, and always after the hard limit', async () => {
const box = await inbox();
const waiting = await store(box, 'p1');
const settled = await store(box, 'p2');
const old = await store(box, 'p3', at('2026-09-01T10:00:00Z'));
await messages.finish(waiting, DONE);
await messages.finish(settled, DONE);
await candidates.insertCandidate({
messageId: waiting,
userId: box.userId,
position: 0,
itemJson: null,
source: null,
checksJson: null,
uncertainFields: null,
matchJson: null,
suggestedTripId: null,
dedupeKey: null,
contentHash: null,
resolution: 'pending',
reason: 'no_trip_in_range',
createdAt: DAY1,
});
const purgedAt = at('2026-11-20T10:00:00Z');
expect(await messages.purgeRaw(at('2026-11-10T10:00:00Z'), at('2026-10-01T10:00:00Z'), purgedAt)).toBe(2);
expect(await messages.findById(waiting)).toMatchObject({ raw_eml_enc: 'enc', raw_purged_at: null });
expect(await messages.findById(settled)).toMatchObject({ raw_eml_enc: null, raw_purged_at: purgedAt });
expect(await messages.findById(old)).toMatchObject({ raw_eml_enc: null });
});
it('deletes settled mails without entries, and keeps queued ones and those with entries', async () => {
const box = await inbox();
const queued = await store(box, 'x1', at('2026-08-01T10:00:00Z'));
const bare = await store(box, 'x2', at('2026-08-01T10:00:00Z'));
const withEntry = await store(box, 'x3', at('2026-08-01T10:00:00Z'));
await messages.finish(bare, { ...DONE, status: 'discarded' });
await messages.finish(withEntry, DONE);
await candidates.insertCandidate({
messageId: withEntry,
userId: box.userId,
position: 0,
itemJson: null,
source: null,
checksJson: null,
uncertainFields: null,
matchJson: null,
suggestedTripId: null,
dedupeKey: null,
contentHash: null,
resolution: 'discarded',
reason: null,
createdAt: DAY1,
});
expect(await messages.deleteSettledBefore(at('2026-09-01T00:00:00Z'))).toBe(1);
expect(await messages.findById(bare)).toBeNull();
expect(await messages.findById(queued)).not.toBeNull();
expect(await messages.findById(withEntry)).not.toBeNull();
});
});
@@ -0,0 +1,48 @@
/**
* A person's switches for the mail import: no row until something changes,
* and a write names only the switches it changes.
*/
import { MailIngestPrefs } from '../../../../src/db/entities/MailIngestPrefs.entity';
import type { MailIngestPrefsRepository } from '../../../../src/db/repositories/MailIngestPrefs.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let prefs: MailIngestPrefsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
prefs = t.repo(MailIngestPrefs);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
describe('MailIngestPrefsRepository', () => {
it('has no row until a switch changes, then the defaults for the others', async () => {
const { user } = await makeUser(t);
expect(await prefs.findForUser(user.id)).toBeNull();
await prefs.upsertForUser(user.id, { auto_add: 0 });
expect(await prefs.findForUser(user.id)).toMatchObject({ enabled: 1, ai_enabled: 1, auto_add: 0 });
await prefs.upsertForUser(user.id, { ai_enabled: 0 });
expect(await prefs.findForUser(user.id)).toMatchObject({ enabled: 1, ai_enabled: 0, auto_add: 0 });
});
it('writes nothing for an empty change', async () => {
const { user } = await makeUser(t);
await prefs.upsertForUser(user.id, {});
expect(await prefs.findForUser(user.id)).toBeNull();
});
});
@@ -112,3 +112,22 @@ describe('PackingItemsRepository — share.service.ts SH13 read', () => {
expect(await packingItemsRepo.listPublicForShare(trip.id)).toEqual([]);
});
});
describe('PackingItemsRepository — clearOwner (#3098)', () => {
it('drops the owner of one item, keeps its tier and leaves the other items alone', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const item = createPackingItem(testDb, trip.id, { name: 'Stove' });
const other = createPackingItem(testDb, trip.id, { name: 'Pot' });
await updateRows(t, PackingItems, { id: item.id }, { is_private: 0, owner: owner.id, updated_at: null });
await updateRows(t, PackingItems, { id: other.id }, { is_private: 0, owner: owner.id });
await packingItemsRepo.clearOwner(item.id);
const row = await packingItemsRepo.findById(item.id);
expect(row?.owner_id).toBeNull();
expect(row?.is_private).toBe(0);
expect(row?.updated_at).not.toBeNull();
expect((await packingItemsRepo.findById(other.id))?.owner_id).toBe(owner.id);
});
});
@@ -166,11 +166,26 @@ describe('PlaceRegionsRepository.listStartedTripPlaceCountriesForUser (AT44)', (
const today = '2026-01-01';
const expected = [
{ id: cached.id, lat: 48.85, lng: 2.35, address: null, country_code: 'FR' },
{ id: uncached.id, lat: 41.9022, lng: 12.4539, address: null, country_code: null },
{ id: cached.id, lat: 48.85, lng: 2.35, address: null, country_code: 'FR', trip_last_date: '2020-01-10' },
{ id: uncached.id, lat: 41.9022, lng: 12.4539, address: null, country_code: null, trip_last_date: '2020-01-10' },
];
expect(await repo.listStartedTripPlaceCountriesForUser(owner.id, today)).toEqual(expected);
expect(await repo.listStartedTripPlaceCountriesForUser(member.id, today)).toEqual(expected);
expect(await repo.listStartedTripPlaceCountriesForUser(stranger.id, today)).toEqual([]);
});
it('PLACEREGREPO-010: dates each place by its own trip, the start standing in for a missing end (#2648)', async () => {
const { user } = createUser(testDb);
const ended = createTrip(testDb, user.id, { start_date: '2020-01-01', end_date: '2020-01-10' });
const openEnded = createTrip(testDb, user.id, { start_date: '2021-07-01' });
const first = createPlace(testDb, ended.id);
const second = createPlace(testDb, openEnded.id);
const rows = await repo.listStartedTripPlaceCountriesForUser(user.id, '2026-01-01');
expect(rows.map((row) => [row.id, row.trip_last_date])).toEqual([
[first.id, '2020-01-10'],
[second.id, '2021-07-01'],
]);
});
});
@@ -525,7 +525,8 @@ describe('ReservationsRepository — AC37/AC40 (listIdMetadataByStay/listIdsBySt
describe('ReservationsRepository — Task 2 reads (listForTrip / findWithJoins / findInTrip / listResyncCandidates / listForRestamp)', () => {
const legacyJoinedSql = `
SELECT r.*, d.day_number as day_number, p.name as place_name, ap.place_id as accommodation_place_id,
acc_p.name as accommodation_name, ap.start_day_id as accommodation_start_day_id, ap.end_day_id as accommodation_end_day_id
acc_p.name as accommodation_name, ap.start_day_id as accommodation_start_day_id, ap.end_day_id as accommodation_end_day_id,
ap.check_in as accommodation_check_in, ap.check_in_end as accommodation_check_in_end, ap.check_out as accommodation_check_out
FROM reservations r
LEFT JOIN days d ON d.id = r.day_id
LEFT JOIN places p ON p.id = r.place_id
@@ -562,10 +563,10 @@ describe('ReservationsRepository — Task 2 reads (listForTrip / findWithJoins /
});
it('RR1 findWithJoins — matches the legacy joined statement for one row, place/accommodation columns populated', async () => {
const { hotel, stay, hotelPlace } = await seed();
const { trip, hotel, stay, hotelPlace } = await seed();
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = testDb.prepare(`${legacyJoinedSql} WHERE r.id = ?`).get(hotel.id);
const typed = await reservationsRepo.findWithJoins(hotel.id);
const typed = await reservationsRepo.findWithJoins(hotel.id, trip.id);
expect(typed).toEqual(legacy);
expect(typed).toMatchObject({
accommodation_place_id: hotelPlace.id,
@@ -574,6 +575,14 @@ describe('ReservationsRepository — Task 2 reads (listForTrip / findWithJoins /
});
});
it('RR1 findWithJoins — a booking of another trip reads as missing', async () => {
const { trip, hotel } = await seed();
const { user } = createUser(testDb);
const other = createTrip(testDb, user.id);
expect(await reservationsRepo.findWithJoins(hotel.id, other.id)).toBeUndefined();
expect(await reservationsRepo.findWithJoins(hotel.id, String(trip.id))).toMatchObject({ id: hotel.id });
});
it('RS35 findInTrip — matches the legacy statement, scoped by trip', async () => {
const { trip, dinner } = await seed();
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
@@ -1032,3 +1041,102 @@ describe('ReservationsRepository — confirmIfPending', () => {
expect((await findRow(await orm(), Reservations, { id: cancelled.id }))?.status).toBe('cancelled');
});
});
describe('ReservationsRepository — findPassContext', () => {
it('RES-PASS-001: reads the trip title and the place of the booking, else of its stay, within the trip only', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Japan 2027', start_date: '2027-04-01', end_date: '2027-04-06' });
const day1 = createDay(testDb, trip.id, { date: '2027-04-01' });
const day2 = createDay(testDb, trip.id, { date: '2027-04-02' });
const restaurant = createPlace(testDb, trip.id, { name: 'Gion Karyo', lat: 35.0, lng: 135.77 });
const hotel = createPlace(testDb, trip.id, { name: 'Hotel Granvia Kyoto', lat: 34.985, lng: 135.758 });
const stay = createDayAccommodation(testDb, trip.id, hotel.id, day1.id, day2.id);
const dinner = createReservation(testDb, trip.id, { title: 'Dinner', type: 'restaurant' });
await setReservation(dinner.id, { place: restaurant.id });
const room = createReservation(testDb, trip.id, { title: 'Room', type: 'hotel' });
await setReservation(room.id, { accommodation_id: String(stay.id) });
const bare = createReservation(testDb, trip.id, { title: 'Museum', type: 'event' });
expect(await reservationsRepo.findPassContext(dinner.id, trip.id)).toEqual({
trip_title: 'Japan 2027',
place_lat: 35.0,
place_lng: 135.77,
place_name: 'Gion Karyo',
});
expect(await reservationsRepo.findPassContext(room.id, trip.id)).toMatchObject({
place_lat: 34.985,
place_name: 'Hotel Granvia Kyoto',
});
expect(await reservationsRepo.findPassContext(bare.id, trip.id)).toEqual({
trip_title: 'Japan 2027',
place_lat: null,
place_lng: null,
place_name: null,
});
const other = createTrip(testDb, user.id, { title: 'Elsewhere' });
expect(await reservationsRepo.findPassContext(dinner.id, other.id)).toBeUndefined();
});
});
describe('ReservationsRepository — the origin of an imported booking', () => {
const baseRow = (tripId: number) => ({
trip_id: tripId,
day_id: null,
end_day_id: null,
place_id: null,
assignment_id: null,
title: 'LH 716',
reservation_time: null,
reservation_end_time: null,
location: null,
confirmation_number: 'ABC123',
notes: null,
url: null,
status: 'pending',
type: 'flight',
accommodation_id: null,
metadata: null,
needs_review: 0,
});
it('RES-ORIGIN-001: a hand-made booking keeps the column defaults, no origin and sync on', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const id = await reservationsRepo.insertReservation(baseRow(trip.id));
// test-sql-allow: reads back the raw columns the insert left to their defaults.
const row = testDb
.prepare('SELECT external_source, external_id, sync_enabled FROM reservations WHERE id = ?')
.get(id);
expect(row).toEqual({ external_source: null, external_id: null, sync_enabled: 1 });
});
it('RES-ORIGIN-002: an imported booking records its origin and is found by it in its own trip only', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const id = await reservationsRepo.insertReservation({
...baseRow(trip.id),
external_source: 'import',
external_id: 'ABC123|flight|2026-09-01|FRA-NRT',
sync_enabled: 0,
});
// test-sql-allow: reads back the raw origin columns the insert named.
const row = testDb
.prepare('SELECT external_source, external_id, sync_enabled FROM reservations WHERE id = ?')
.get(id);
expect(row).toEqual({
external_source: 'import',
external_id: 'ABC123|flight|2026-09-01|FRA-NRT',
sync_enabled: 0,
});
expect(await reservationsRepo.findIdByExternal(trip.id, 'import', 'ABC123|flight|2026-09-01|FRA-NRT')).toBe(id);
expect(
await reservationsRepo.findIdByExternal(other.id, 'import', 'ABC123|flight|2026-09-01|FRA-NRT'),
).toBeUndefined();
expect(
await reservationsRepo.findIdByExternal(trip.id, 'mail', 'ABC123|flight|2026-09-01|FRA-NRT'),
).toBeUndefined();
});
});
@@ -5,7 +5,7 @@ import { withRequestContext } from '../../../../src/nest/database/request-contex
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createPlace, createTag, createTrip, createUser } from '../../../helpers/factories';
import { tagPlace } from '../../../helpers/factories/places';
import { makeTag, tagPlace } from '../../../helpers/factories/places';
import { findRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
@@ -380,7 +380,76 @@ describe('TagsRepository', () => {
// Plan 3c Task 4 — findByIds (PL2) and the place_tags pivot writes (PL5/PL12/PL13).
// ---------------------------------------------------------------------------
describe('TagsRepository: the tags a trip owns', () => {
it('TRIPTAGREPO-001: listByTrip returns the rows of that trip by name, whoever created them, as SELECT * rows', async () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb, { username: 'trip_member' });
const trip = createTrip(testDb, owner.id);
const other = createTrip(testDb, owner.id);
const zone = await makeTag(t, owner.id, { trip: trip.id, name: 'Zone' });
const activity = await makeTag(t, member.id, { trip: trip.id, name: 'Activity' });
await makeTag(t, owner.id, { trip: other.id, name: 'Elsewhere' });
createTag(testDb, owner.id, { name: 'personal' });
const rows = await tags.listByTrip(trip.id);
expect(rows).toStrictEqual([rawTag(activity.id), rawTag(zone.id)]);
expect(rows.map((row) => row.trip_id)).toEqual([trip.id, trip.id]);
expect(await tags.listByTrip(999999)).toEqual([]);
});
it('TRIPTAGREPO-002: findByIdAndTrip finds a tag of that trip, and neither a personal tag nor another trip’s', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const ofTrip = await makeTag(t, user.id, { trip: trip.id, name: 'Monument' });
const ofOther = await makeTag(t, user.id, { trip: other.id, name: 'Elsewhere' });
const personal = createTag(testDb, user.id, { name: 'personal' });
expect(await tags.findByIdAndTrip(ofTrip.id, trip.id)).toStrictEqual(rawTag(ofTrip.id));
expect(await tags.findByIdAndTrip(ofOther.id, trip.id)).toBeNull();
expect(await tags.findByIdAndTrip(personal.id, trip.id)).toBeNull();
expect(await tags.findByIdAndTrip(999999, trip.id)).toBeNull();
});
it('TRIPTAGREPO-003: createTag files the row under the trip it is given, and under none when it is given none', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const ofTrip = await tags.createTag({ user_id: user.id, trip_id: trip.id, name: 'Monument', color: '#ff0000' });
const personal = await tags.createTag({ user_id: user.id, name: 'Monument', color: null });
expect(ofTrip).toStrictEqual(rawTag(ofTrip.id));
expect(ofTrip).toMatchObject({ user_id: user.id, trip_id: trip.id, name: 'Monument', color: '#ff0000' });
expect(personal).toMatchObject({ user_id: user.id, trip_id: null, color: null });
});
it('TRIPTAGREPO-004: a personal tag still reads through listByUser and findByIdAndUser with a null trip', async () => {
const { user } = createUser(testDb);
const personal = createTag(testDb, user.id, { name: 'personal' });
expect((await tags.listByUser(user.id)).map((row) => row.trip_id)).toEqual([null]);
expect((await tags.findByIdAndUser(personal.id, user.id))?.trip_id).toBeNull();
});
});
describe('TagsRepository.findByIds (PL2)', () => {
it('FINDBYIDSREPO-002: says which trip each tag belongs to, null for a personal one', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const ofTrip = await makeTag(t, user.id, { trip: trip.id, name: 'Monument' });
const personal = createTag(testDb, user.id, { name: 'personal' });
const rows = await tags.findByIds([personal.id, ofTrip.id]);
expect(rows.sort((a, b) => a.id - b.id)).toEqual(
[
{ id: personal.id, user_id: user.id, trip_id: null },
{ id: ofTrip.id, user_id: user.id, trip_id: trip.id },
].sort((a, b) => a.id - b.id),
);
});
it('FINDBYIDSREPO-001: returns id + user_id for the matching ids, empty input short-circuits', async () => {
const { user: ownerA } = createUser(testDb);
const { user: ownerB } = createUser(testDb, { username: 'owner_b' });
@@ -561,6 +561,7 @@ describe('TripsRepository.findForViewer / listForUser / activeTrip (Plan 3c Task
is_archived: 0,
cover_image: null,
reminder_days: 3,
costs_mode: 'split',
});
// Seen INSIDE the open transaction — the write and the read share
// one connection.
@@ -610,6 +611,7 @@ describe('TripsRepository.insertTrip / updateTripRow / setCoverImage / deleteByI
is_archived: 1,
cover_image: 'c.png',
reminder_days: 7,
costs_mode: 'totals',
});
const row = await tripRow(trip.id);
expect(row).toMatchObject({
@@ -621,6 +623,7 @@ describe('TripsRepository.insertTrip / updateTripRow / setCoverImage / deleteByI
is_archived: 1,
cover_image: 'c.png',
reminder_days: 7,
costs_mode: 'totals',
});
// CURRENT_TIMESTAMP has one-second resolution — a same-second before/after
// comparison is flaky, not a real assertion; the column being non-null and
@@ -648,7 +651,7 @@ describe('TripsRepository.insertTrip / updateTripRow / setCoverImage / deleteByI
// ── Plan 3c Task 8 (`TripsService.copy`, TP37) — additive ───────────────────
describe('TripsRepository.insertTripCopy (TP37)', () => {
it('TRIPREPO-039: writes the 8-column copy set, is_archived hard-coded to 0 regardless of the caller', async () => {
it('TRIPREPO-039: writes the 9-column copy set, is_archived hard-coded to 0 regardless of the caller', async () => {
const { user: owner } = createUser(testDb);
const { user: newOwner } = createUser(testDb);
const newId = await trips.insertTripCopy({
@@ -660,9 +663,20 @@ describe('TripsRepository.insertTripCopy (TP37)', () => {
currency: 'USD',
cover_image: 'c.png',
reminder_days: 7,
costs_mode: 'totals',
});
const { user_id, title, description, start_date, end_date, currency, cover_image, is_archived, reminder_days } =
await tripRow(newId);
const {
user_id,
title,
description,
start_date,
end_date,
currency,
cover_image,
is_archived,
reminder_days,
costs_mode,
} = await tripRow(newId);
const row = {
user_id,
title,
@@ -673,6 +687,7 @@ describe('TripsRepository.insertTripCopy (TP37)', () => {
cover_image,
is_archived,
reminder_days,
costs_mode,
};
expect(row).toEqual({
user_id: newOwner.id,
@@ -684,6 +699,7 @@ describe('TripsRepository.insertTripCopy (TP37)', () => {
cover_image: 'c.png',
is_archived: 0,
reminder_days: 7,
costs_mode: 'totals',
});
// The source trip (never touched) proves is_archived: 0 is a literal, not a copied value.
await setTrip(owner.id, { is_archived: 1 });
@@ -702,6 +718,7 @@ describe('TripsRepository.insertTripCopy (TP37)', () => {
currency: null,
cover_image: null,
reminder_days: 3,
costs_mode: 'split',
});
expect((await tripRow(newId)).is_archived).toBe(0);
});
@@ -669,6 +669,25 @@ describe('UsersRepository', () => {
expect(row.updated_at).toBe('2020-01-01 00:00:00');
});
it('USERSREPO-088: linkOidcIdentity with nulls removes the SSO link WITHOUT touching updated_at (#3065)', async () => {
const { user } = createUser(testDb);
await updateRows(
t,
Users,
{ id: user.id },
{ oidc_sub: 'sub-1', oidc_issuer: 'https://idp.example.com', updated_at: '2020-01-01 00:00:00' },
);
await users.linkOidcIdentity(user.id, null, null);
const row = (await findRow(t, Users, { id: user.id })) as {
oidc_sub: string | null;
oidc_issuer: string | null;
updated_at: string;
};
expect(row.oidc_sub).toBeNull();
expect(row.oidc_issuer).toBeNull();
expect(row.updated_at).toBe('2020-01-01 00:00:00');
});
it('USERSREPO-042: setRole (O8) writes role WITHOUT touching updated_at', async () => {
const { user } = createUser(testDb);
await updateRows(t, Users, { id: user.id }, { updated_at: '2020-01-01 00:00:00' });
@@ -41,13 +41,15 @@ const AT6 = (n: number) => `
WHERE r.trip_id IN (${Array(n).fill('?').join(',')}) AND e.role IN ('from', 'to')
AND ${TRAVELER_OWNS}`;
// AT45 also names the trip's last day since #2648, the dashboard's order of countries.
const AT45 = `
SELECT DISTINCT e.id, e.reservation_id, r.trip_id, e.role, e.code, e.lat, e.lng, e.local_date, e.local_time,
r.type AS reservation_type, r.status AS reservation_status,
CASE e.role
WHEN 'to' THEN COALESCE(r.reservation_end_time, r.reservation_time)
ELSE COALESCE(r.reservation_time, r.reservation_end_time)
END AS fallback_time
END AS fallback_time,
COALESCE(t.end_date, t.start_date) AS trip_last_date
FROM reservation_endpoints e
JOIN reservations r ON e.reservation_id = r.id
JOIN trips t ON r.trip_id = t.id
@@ -0,0 +1,94 @@
/**
* `Migration20200101046440_a_trip_owns_its_tags`: a tag can belong to a trip.
* Every tag from before stays a personal one, a trip's tag has to name a real
* trip, and it goes with that trip, taking itself off the places that carried it.
*/
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
import { describe, expect, it } from 'vitest';
const TARGET = 'Migration20200101046440_a_trip_owns_its_tags';
async function ormBeforeTarget(): Promise<MikroORM> {
const orm = await createMigrationOrm();
const names = await pendingNames(orm);
const index = names.indexOf(TARGET);
expect(index).toBeGreaterThan(0);
await migrateTo(orm, names[index - 1]);
return orm;
}
describe('a trip owns its tags', () => {
it('TRIPTAG-MIG-001: keeps every existing tag personal, on the places it was on', async () => {
const orm = await ormBeforeTarget();
try {
await rawExec(
orm,
"INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')",
);
await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'Lisbon')");
await rawExec(orm, "INSERT INTO places (id, trip_id, name) VALUES (20, 10, 'Belem Tower')");
await rawExec(orm, "INSERT INTO tags (id, user_id, name, color) VALUES (30, 1, 'hidden gem', '#ff0000')");
await rawExec(orm, 'INSERT INTO place_tags (place_id, tag_id) VALUES (20, 30)');
await migrateTo(orm, TARGET);
expect(await rawQuery(orm, 'SELECT id, user_id, trip_id, name, color FROM tags')).toEqual([
{ id: 30, user_id: 1, trip_id: null, name: 'hidden gem', color: '#ff0000' },
]);
expect(await rawQuery(orm, 'SELECT place_id, tag_id FROM place_tags')).toEqual([{ place_id: 20, tag_id: 30 }]);
} finally {
await orm.close(true);
}
}, 30000);
it('TRIPTAG-MIG-002: a tag of a trip names a real trip and goes when the trip goes', async () => {
const orm = await ormBeforeTarget();
try {
await rawExec(
orm,
"INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')",
);
await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'Lisbon'), (11, 1, 'Porto')");
await rawExec(orm, "INSERT INTO places (id, trip_id, name) VALUES (20, 10, 'Belem Tower'), (21, 11, 'Ribeira')");
await migrateTo(orm, TARGET);
await rawExec(orm, "INSERT INTO tags (id, user_id, trip_id, name) VALUES (30, 1, 10, 'Monument')");
await rawExec(orm, "INSERT INTO tags (id, user_id, trip_id, name) VALUES (31, 1, 11, 'Zone')");
await rawExec(orm, "INSERT INTO tags (id, user_id, name) VALUES (32, 1, 'personal')");
await rawExec(orm, 'INSERT INTO place_tags (place_id, tag_id) VALUES (20, 30), (21, 31), (21, 32)');
await expect(
rawExec(orm, "INSERT INTO tags (user_id, trip_id, name) VALUES (1, 999, 'Nowhere')"),
).rejects.toThrow(/FOREIGN KEY/);
await rawExec(orm, 'DELETE FROM trips WHERE id = 10');
expect(await rawQuery(orm, 'SELECT id, trip_id FROM tags ORDER BY id')).toEqual([
{ id: 31, trip_id: 11 },
{ id: 32, trip_id: null },
]);
expect(await rawQuery(orm, 'SELECT place_id, tag_id FROM place_tags ORDER BY tag_id')).toEqual([
{ place_id: 21, tag_id: 31 },
{ place_id: 21, tag_id: 32 },
]);
} finally {
await orm.close(true);
}
}, 30000);
it('TRIPTAG-MIG-003: the trip column is indexed, so deleting a trip does not scan every tag', async () => {
const orm = await ormBeforeTarget();
try {
await migrateTo(orm, TARGET);
const indexes = await rawQuery<{ name: string }>(orm, "SELECT name FROM pragma_index_list('tags')");
expect(indexes.map((index) => index.name)).toContain('idx_tags_trip_id');
expect(await rawQuery(orm, "SELECT name FROM pragma_index_info('idx_tags_trip_id')")).toEqual([
{ name: 'trip_id' },
]);
} finally {
await orm.close(true);
}
}, 30000);
});