feat(mail-ingest): tables for forwarded booking mails and their bookings

Five tables carry the mail import: forwarding addresses (token hash plus the
encrypted token), a person's switches, the readers' cursor and lease, every
mail as it arrived, and each booking read from it with its checks and fate.
Repositories read the trips a booking may go to by column, so the import
weighs a booking without reaching into five other domains.
This commit is contained in:
Maurice
2026-11-13 15:30:07 +01:00
parent 53ebc9d632
commit baa906fb6b
29 changed files with 2118 additions and 4 deletions
+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 168 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(168);
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);
});
@@ -63,7 +63,10 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
// + storage_release_queue: category, key, due_at (a queued release is only ever written whole, by the release queue).
// + flight_live_states: callsign, service_date, origin, destination (a flight's state is always found and
// written by its key).
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 615;
// + 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', () => {
@@ -108,6 +108,7 @@ const UNNUMBERED = [
'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',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -0,0 +1,84 @@
/**
* 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, and a mail notes the address it came in on.
*/
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);
});
});
@@ -0,0 +1,250 @@
/**
* 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 { makePlace } from '../../../helpers/factories/places';
import { makeReservation } from '../../../helpers/factories/reservations';
import { addTripMember, 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 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,
});
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('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('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 });
expect(await candidates.listDayDates([trip.id])).toEqual([
{ trip_id: trip.id, date: '2027-03-01' },
{ trip_id: trip.id, date: '2027-03-02' },
]);
expect(await candidates.listDayDates([])).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',
});
expect(await candidates.tripHasExternal(trip.id, ['import', 'mail'], 'ABC123|flight|2027-03-01|hnd-itm')).toBe(true);
expect(await candidates.tripHasExternal(trip.id, ['import'], 'ABC123|flight|2027-03-01|hnd-itm')).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('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);
});
});
@@ -0,0 +1,63 @@
/**
* 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.find('pipeline', '')).toMatchObject({ lease_owner: 'b' });
await cursor.releaseLease('pipeline', '', 'b');
expect(await cursor.find('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.find('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.find('imap', 'INBOX');
expect(row).toMatchObject({ uid_validity: 7, last_uid: 42, last_ok_at: T1, last_error: null });
expect(await cursor.find('cloud', '')).toBeNull();
});
});
@@ -0,0 +1,191 @@
/**
* 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 };
}
function store(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(id).not.toBeNull();
expect(await store(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('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();
});
});