feat(mail-ingest): read forwarded booking mails and add what passes the checks to its trip

Addresses per person and per trip (random base32 token, stored hashed and
encrypted), an intake every transport shares, and a job that reads each
mail once under a lease: filters without AI, machine-readable data always,
one AI request with the person's trips, the server's checks G1 to G9, then
one transaction per mail that adds what passed, keeps the rest in the inbox
with a reason, and notifies the forwarder and co-travellers. Undo within
7 days, manual apply, filing as documents, a prefilled form and a nightly
retention complete it; on a managed install the operator's switch decides.
This commit is contained in:
Maurice
2026-11-13 16:04:26 +01:00
parent 340454cfc7
commit de7de4b8de
36 changed files with 4038 additions and 54 deletions
@@ -15,9 +15,10 @@ import type { MailIngestMessagesRepository } from '../../../../src/db/repositori
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 } from '../../../helpers/factories/trips';
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';
@@ -67,7 +68,8 @@ async function mailOf(userId: number): Promise<number> {
rawEnc: 'enc',
receivedAt: DAY1,
});
return id!;
if (id === null) throw new Error('the mail was stored already');
return id;
}
function entry(messageId: number, userId: number, over: Partial<MailIngestCandidateInsert> = {}) {
@@ -128,6 +130,26 @@ describe('MailIngestCandidatesRepository: the entries', () => {
});
});
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);
@@ -184,17 +206,32 @@ describe('MailIngestCandidatesRepository: what it reads of the trips', () => {
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 });
expect(await candidates.listDayDates([trip.id])).toEqual([
{ trip_id: trip.id, date: '2027-03-01' },
{ trip_id: trip.id, date: '2027-03-02' },
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(await candidates.listDayDates([])).toEqual([]);
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 },
]);
@@ -243,6 +280,20 @@ describe('MailIngestCandidatesRepository: what it reads of the trips', () => {
).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);
@@ -56,7 +56,14 @@ async function inbox() {
return { userId: user.id, addressId };
}
function store(box: { userId: number; addressId: number }, hash: string, receivedAt = DAY1) {
/** 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>`,
@@ -88,12 +95,11 @@ 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 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();
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 () => {
@@ -101,7 +107,7 @@ describe('MailIngestMessagesRepository', () => {
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);
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);
});
@@ -118,14 +124,14 @@ describe('MailIngestMessagesRepository', () => {
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 });
expect(await messages.findById(id)).toMatchObject({ status: 'processing', attempts: 2 });
await messages.retryLater(id!, at('2026-11-01T12:00:00Z'));
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({
await messages.finish(id, DONE);
expect(await messages.findById(id)).toMatchObject({
status: 'processed',
ai_used: 1,
from_verified: 1,
@@ -138,10 +144,10 @@ describe('MailIngestMessagesRepository', () => {
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 messages.finish(waiting, DONE);
await messages.finish(settled, DONE);
await candidates.insertCandidate({
messageId: waiting!,
messageId: waiting,
userId: box.userId,
position: 0,
itemJson: null,
@@ -159,9 +165,9 @@ describe('MailIngestMessagesRepository', () => {
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 });
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 () => {
@@ -169,10 +175,10 @@ describe('MailIngestMessagesRepository', () => {
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 messages.finish(bare, { ...DONE, status: 'discarded' });
await messages.finish(withEntry, DONE);
await candidates.insertCandidate({
messageId: withEntry!,
messageId: withEntry,
userId: box.userId,
position: 0,
itemJson: null,
@@ -189,8 +195,8 @@ describe('MailIngestMessagesRepository', () => {
});
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();
expect(await messages.findById(bare)).toBeNull();
expect(await messages.findById(queued)).not.toBeNull();
expect(await messages.findById(withEntry)).not.toBeNull();
});
});