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();
});
});
@@ -122,11 +122,17 @@ describe('MailReadService.read', () => {
});
it('reports a spent allowance as its outcome and logs no content', async () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);
const lines: string[] = [];
for (const method of ['log', 'info', 'warn', 'error'] as const) {
vi.spyOn(console, method).mockImplementation((...args: unknown[]) => {
lines.push(args.map(String).join(' '));
});
}
extract.mockRejectedValue(new LlmRequestError('gate', 429, 'QUOTA_SPENT'));
const reading = await service.read(input(), 1, '2026-11-13');
expect(reading.outcome).toBe('quota_exhausted');
expect(String(error.mock.calls[0][0])).not.toContain('ABC123');
expect(lines.join(' | ')).toContain('Mail read failed');
expect(lines.join(' | ')).not.toContain('ABC123');
});
it('reads through the local router without a trip choice', async () => {
@@ -0,0 +1,246 @@
/**
* The server's checks on a booking read from a mail (G1 to G8) and the choice
* of its trip: the AI's pick is one input, the dates and the trip list decide,
* and every failure names the first reason the inbox shows.
*/
import {
checkInText,
chooseTrip,
contentHash,
fitsTrip,
implausible,
isCancellation,
judgeBooking,
missingCritical,
missingReference,
nearTrip,
type CheckContext,
type MailDraft,
type TripOption,
} from '../../../../src/nest/mail-ingest/mail-ingest-checks';
import type { BookingImportPreviewItem } from '@trek/shared';
import { describe, expect, it } from 'vitest';
const NOW = new Date('2030-01-15T10:00:00Z');
const endpoint = (role: 'from' | 'to', name: string, code: string, lat: number, lng: number) => ({
role,
sequence: role === 'from' ? 0 : 1,
name,
code,
lat,
lng,
timezone: null,
local_time: null,
local_date: null,
});
const HND = endpoint('from', 'Tokyo Haneda', 'HND', 35.55, 139.78);
const ITM = endpoint('to', 'Osaka Itami', 'ITM', 34.78, 135.44);
const FLIGHT: BookingImportPreviewItem = {
type: 'flight',
title: 'LH 716 Tokyo to Osaka',
reservation_time: '2030-03-02T10:00',
reservation_end_time: '2030-03-02T11:15',
confirmation_number: 'ABC123',
metadata: { flight_number: 'LH716', price: 120.5, priceCurrency: 'EUR' },
endpoints: [HND, ITM],
source: { fileName: 'mail.eml', index: 0 },
};
const HOTEL: BookingImportPreviewItem = {
type: 'hotel',
title: 'Hotel Sakura',
confirmation_number: 'H-778',
_venue: { name: 'Hotel Sakura', lat: 35.01, lng: 135.76 },
_accommodation: { check_in: '2030-03-03T15:00', check_out: '2030-03-05T11:00' },
source: { fileName: 'mail.eml', index: 0 },
};
const TEXT = 'Your booking ABC123: flight LH 716 from Tokyo to Osaka. Hotel Sakura, reference H-778.';
function trip(id: number, start: string | null, end: string | null, over: Partial<TripOption> = {}): TripOption {
const days = new Map<string, number>();
if (start && end) {
for (let d = new Date(`${start}T00:00:00Z`), n = 1; d <= new Date(`${end}T00:00:00Z`); n++) {
days.set(d.toISOString().slice(0, 10), id * 100 + n);
d = new Date(d.getTime() + 86_400_000);
}
}
return {
id,
title: `Trip ${id}`,
start_date: start,
end_date: end,
ownerId: 1,
currency: 'EUR',
days,
places: [],
...over,
};
}
const JAPAN = trip(1, '2030-03-01', '2030-03-10');
const context = (over: Partial<CheckContext> = {}): CheckContext => ({
trips: [JAPAN],
addressTripId: null,
subject: 'Your flight',
documentText: TEXT,
now: NOW,
knownAirport: (code) => ['HND', 'ITM'].includes(code),
...over,
});
const draft = (over: Partial<MailDraft> = {}): MailDraft => ({
item: FLIGHT,
source: 'kitinerary',
kind: 'new_booking',
aiTripId: null,
uncertainFields: [],
suggestedNewTrip: null,
imageOnly: false,
disagrees: false,
...over,
});
describe('the single checks', () => {
it('needs a type, a start and, for a transport, both ends', () => {
expect(missingCritical(FLIGHT)).toBe(false);
expect(missingCritical({ ...FLIGHT, reservation_time: null })).toBe(true);
expect(missingCritical({ ...FLIGHT, endpoints: [HND] })).toBe(true);
expect(missingCritical(HOTEL)).toBe(false);
});
it('needs a booking reference for a transport, a stay or a rental only', () => {
expect(missingReference({ ...FLIGHT, confirmation_number: ' ' })).toBe(true);
expect(missingReference({ ...FLIGHT, type: 'restaurant', confirmation_number: null })).toBe(false);
});
it('refuses values that cannot be right (G5)', () => {
const known = (code: string) => code !== 'XXX';
expect(implausible(FLIGHT, NOW, known)).toBe(false);
expect(implausible({ ...FLIGHT, reservation_time: 'soon' }, NOW, known)).toBe(true);
expect(implausible({ ...FLIGHT, reservation_time: '2034-01-01T10:00' }, NOW, known)).toBe(true);
expect(implausible({ ...FLIGHT, reservation_end_time: '2030-03-01T10:00' }, NOW, known)).toBe(true);
expect(implausible({ ...FLIGHT, reservation_end_time: '2030-03-03T10:00' }, NOW, known)).toBe(true);
expect(implausible({ ...FLIGHT, confirmation_number: 'A' }, NOW, known)).toBe(true);
expect(implausible({ ...FLIGHT, metadata: { price: 200_000 } }, NOW, known)).toBe(true);
expect(implausible({ ...FLIGHT, metadata: { priceCurrency: 'euro' } }, NOW, known)).toBe(true);
expect(implausible({ ...FLIGHT, metadata: { price: '1.234,50' } }, NOW, known)).toBe(false);
expect(implausible(FLIGHT, NOW, (code) => code !== 'ITM')).toBe(true);
const longStay = { ...HOTEL, _accommodation: { check_in: '2030-03-01', check_out: '2030-06-01' } };
expect(implausible(longStay, NOW, known)).toBe(true);
});
it('vetoes a cancellation by kind, status or subject (G8)', () => {
const cancelled = { ...FLIGHT, metadata: { reservationStatus: 'ReservationCancelled' } };
expect(isCancellation(FLIGHT, 'cancellation', null)).toBe(true);
expect(isCancellation(cancelled, 'new_booking', null)).toBe(true);
expect(isCancellation(FLIGHT, 'new_booking', 'Ihre Buchung wurde storniert')).toBe(true);
expect(isCancellation(FLIGHT, 'new_booking', 'Your booking at Hotel Sakura')).toBe(false);
});
it('wants an AI value in the mail, and only marks a free text it cannot find (G6)', () => {
expect(checkInText(FLIGHT, TEXT)).toEqual({ ok: true, uncertain: [] });
expect(checkInText({ ...FLIGHT, confirmation_number: 'ZZZ999' }, TEXT).ok).toBe(false);
expect(checkInText({ ...FLIGHT, title: 'Paris Express', location: 'Gare du Nord' }, TEXT)).toEqual({
ok: true,
uncertain: ['title', 'location'],
});
});
it('fits a booking into a trip by its dates and the days it needs (G3)', () => {
expect(fitsTrip(FLIGHT, JAPAN)).toBe(true);
expect(fitsTrip(HOTEL, JAPAN)).toBe(true);
expect(fitsTrip(FLIGHT, trip(2, '2030-04-01', '2030-04-05'))).toBe(false);
expect(fitsTrip(FLIGHT, trip(3, null, null))).toBe(false);
// A day of slack is no day row: the booking needs the day it starts on.
expect(fitsTrip(FLIGHT, trip(4, '2030-03-03', '2030-03-05'))).toBe(false);
expect(fitsTrip({ ...FLIGHT, reservation_time: null }, JAPAN)).toBe(false);
});
it('confirms a booking lies near a trip by the trip’s places', () => {
const kyoto = trip(5, '2030-03-01', '2030-03-10', {
places: [{ name: 'Kyoto Station', address: null, lat: 34.98, lng: 135.75 }],
});
expect(nearTrip(HOTEL, kyoto)).toBe(true);
expect(nearTrip(FLIGHT, kyoto)).toBe(true);
expect(nearTrip({ ...HOTEL, _venue: { name: 'Far', lat: 43.06, lng: 141.35 } }, kyoto)).toBe(false);
});
it('hashes what a booking says', () => {
expect(contentHash(FLIGHT)).toBe(contentHash({ ...FLIGHT, confirmation_number: 'abc 123' }));
expect(contentHash(FLIGHT)).not.toBe(contentHash({ ...FLIGHT, reservation_time: '2030-03-02T11:00' }));
});
});
describe('chooseTrip', () => {
const second = trip(2, '2030-02-25', '2030-03-05', {
places: [{ name: 'Osaka', address: null, lat: 34.7, lng: 135.5 }],
});
it('takes the one trip whose dates fit', () => {
expect(chooseTrip(FLIGHT, null, context())).toEqual({ tripId: 1, suggestedTripId: 1, reason: null });
});
it('of several, takes the AI’s pick only when the booking lies near it', () => {
const both = context({ trips: [JAPAN, second] });
expect(chooseTrip(FLIGHT, 2, both)).toEqual({ tripId: 2, suggestedTripId: 2, reason: null });
expect(chooseTrip(FLIGHT, 1, both)).toEqual({ tripId: null, suggestedTripId: 1, reason: 'trip_ambiguous' });
expect(chooseTrip(FLIGHT, null, both)).toEqual({ tripId: null, suggestedTripId: 1, reason: 'trip_ambiguous' });
});
it('suggests the AI’s pick when no trip fits, and names trips without dates', () => {
const later = trip(6, '2030-06-01', '2030-06-10');
expect(chooseTrip(FLIGHT, 6, context({ trips: [later] }))).toEqual({
tripId: null,
suggestedTripId: 6,
reason: 'no_trip_in_range',
});
expect(chooseTrip(FLIGHT, 9, context({ trips: [trip(7, null, null)] })).reason).toBe('trip_without_dates');
});
it('keeps a trip address’s booking to its trip, whatever the AI says', () => {
expect(chooseTrip(FLIGHT, 2, context({ addressTripId: 1, trips: [JAPAN, second] }))).toEqual({
tripId: 1,
suggestedTripId: 1,
reason: null,
});
const undated = trip(8, null, null);
expect(chooseTrip(FLIGHT, null, context({ addressTripId: 8, trips: [undated] })).tripId).toBe(8);
const elsewhen = trip(9, '2030-06-01', '2030-06-10');
const outside = chooseTrip(FLIGHT, null, context({ addressTripId: 9, trips: [elsewhen] }));
expect(outside.reason).toBe('outside_trip_dates');
expect(chooseTrip(FLIGHT, null, context({ addressTripId: 10 })).reason).toBe('no_edit_permission');
});
});
describe('judgeBooking', () => {
it('passes a machine-read booking that fits one trip', () => {
const verdict = judgeBooking(draft(), context());
expect(verdict.reason).toBeNull();
expect(verdict.checks).toMatchObject({ schema: 'pass', dates: 'pass', agreement: 'skipped', in_text: 'skipped' });
expect(verdict.choice.tripId).toBe(1);
});
it('names the first reason in the order the inbox reads them', () => {
expect(judgeBooking(draft({ kind: 'change' }), context()).reason).toBe('change_or_cancellation');
expect(judgeBooking(draft({ kind: 'cancellation' }), context()).reason).toBe('change_or_cancellation');
expect(judgeBooking(draft(), context({ subject: 'Cancelled: your flight' })).reason).toBe('cancelled');
expect(judgeBooking(draft({ item: { ...FLIGHT, endpoints: [] } }), context()).reason).toBe(
'missing_critical_field',
);
expect(judgeBooking(draft({ item: { ...FLIGHT, title: '' } }), context()).reason).toBe('missing_critical_field');
expect(judgeBooking(draft(), context({ knownAirport: () => false })).reason).toBe('implausible');
expect(judgeBooking(draft({ source: 'ai', disagrees: true }), context()).reason).toBe('source_mismatch');
expect(judgeBooking(draft({ source: 'ai', imageOnly: true }), context()).reason).toBe('image_only');
expect(judgeBooking(draft({ source: 'ai' }), context({ documentText: 'nothing' })).reason).toBe('not_in_text');
const noReference = { ...FLIGHT, confirmation_number: null };
expect(judgeBooking(draft({ item: noReference }), context()).reason).toBe('missing_confirmation');
expect(judgeBooking(draft(), context({ trips: [] })).reason).toBe('no_trip_in_range');
});
it('adds the fields it could not find to the AI’s own uncertain ones', () => {
const verdict = judgeBooking(
draft({ source: 'ai', uncertainFields: ['seat'], item: { ...FLIGHT, location: 'Terminal 9' } }),
context(),
);
expect(verdict.uncertain).toEqual(['seat', 'location']);
expect(verdict.checks.in_text).toBe('pass');
});
});
@@ -0,0 +1,132 @@
/**
* The mail import's pure pieces: what a mail is before anything reads it, a
* signed sender as a hint, a price read to the cent or not at all, the
* address token, and the sealed mail.
*/
import { walkMail } from '../../../../src/nest/llm-parse/mime-walker';
import { addressOf, classifyMail, senderVerified } from '../../../../src/nest/mail-ingest/mail-classify';
import { hashToken, newToken, tokenOf } from '../../../../src/nest/mail-ingest/mail-ingest-address.service';
import { parsePriceMinor } from '../../../../src/nest/mail-ingest/mail-money';
import { openMail, sealMail } from '../../../../src/nest/mail-ingest/mail-seal';
import { describe, expect, it } from 'vitest';
/** A mail with the given headers and body, as the walker reads it. */
function mail(headers: Record<string, string>, body: string) {
const head = Object.entries({ From: 'Mia <mia@example.com>', Subject: 'Hello', ...headers })
.map(([name, value]) => `${name}: ${value}`)
.join('\r\n');
const walked = walkMail(Buffer.from(`${head}\r\nContent-Type: text/plain\r\n\r\n${body}`));
if (!walked) throw new Error('the fixture is no mail');
return walked;
}
const BOOKING_BODY = 'Your booking ABC123 is confirmed. Flight LH 716 on 2030-03-02.';
describe('classifyMail', () => {
it('reads a booking mail', () => {
expect(classifyMail(mail({ Subject: 'Your flight' }, BOOKING_BODY))).toEqual({ kind: 'read' });
});
it('shows the code of a forwarding confirmation and clicks nothing', () => {
const gmail = mail(
{ From: 'forwarding-noreply@google.com', Subject: '(#123) Gmail Forwarding Confirmation' },
'Confirmation code: 612345678. To allow forwarding, click the link.',
);
expect(classifyMail(gmail)).toEqual({ kind: 'forwarding_confirmation', code: '612345678' });
});
it('drops an automatic reply, but not a confirmation a booking system generated', () => {
expect(classifyMail(mail({ 'Auto-Submitted': 'auto-replied' }, BOOKING_BODY))).toEqual({
kind: 'drop',
reason: 'auto_reply',
});
expect(classifyMail(mail({ Subject: 'Out of office' }, BOOKING_BODY)).kind).toBe('drop');
expect(classifyMail(mail({ 'Auto-Submitted': 'auto-generated' }, BOOKING_BODY))).toEqual({ kind: 'read' });
});
it('drops an empty mail', () => {
expect(classifyMail(mail({}, 'hi'))).toEqual({ kind: 'drop', reason: 'empty_mail' });
});
it('drops a list mail without a booking in it, and keeps one that has one', () => {
const list = { 'List-Unsubscribe': '<mailto:off@example.com>' };
expect(classifyMail(mail(list, 'Our autumn deals are here, have a look at them all.'))).toEqual({
kind: 'drop',
reason: 'newsletter',
});
expect(classifyMail(mail(list, BOOKING_BODY))).toEqual({ kind: 'read' });
const bulk = mail({ Precedence: 'bulk' }, 'Weekly news for travellers who love to read.');
expect(classifyMail(bulk).kind).toBe('drop');
});
});
describe('senderVerified', () => {
const signed = { 'Authentication-Results': 'mx.example.net; dkim=pass header.d=example.com; spf=pass' };
it('holds for the person’s own address, signed by its domain', () => {
expect(senderVerified(mail(signed, BOOKING_BODY), 'Mia@Example.com')).toBe(true);
});
it('does not hold for another sender or without a signature', () => {
expect(senderVerified(mail(signed, BOOKING_BODY), 'other@example.com')).toBe(false);
expect(senderVerified(mail({}, BOOKING_BODY), 'mia@example.com')).toBe(false);
const forged = { 'Authentication-Results': 'mx.example.net; dkim=pass header.d=evil.test' };
expect(senderVerified(mail(forged, BOOKING_BODY), 'mia@example.com')).toBe(false);
});
it('reads a bare address out of a From header', () => {
expect(addressOf('Mia <MIA@example.com>')).toBe('mia@example.com');
expect(addressOf('mia@example.com')).toBe('mia@example.com');
expect(addressOf(null)).toBeNull();
});
});
describe('parsePriceMinor', () => {
it('takes a number as it is and reads unambiguous text', () => {
expect(parsePriceMinor(120.5, 'EUR')).toBe(12050);
expect(parsePriceMinor('1.234,56', 'EUR')).toBe(123456);
expect(parsePriceMinor('1,234.56', 'USD')).toBe(123456);
expect(parsePriceMinor('€ 89,35', 'EUR')).toBe(8935);
expect(parsePriceMinor('1.234.567', 'EUR')).toBe(123456700);
expect(parsePriceMinor('12000', 'JPY')).toBe(1200000);
expect(parsePriceMinor('0,5', null)).toBe(50);
});
it('refuses what it would have to guess', () => {
expect(parsePriceMinor('1.234', 'EUR')).toBeNull();
expect(parsePriceMinor('12.50', 'JPY')).toBeNull();
expect(parsePriceMinor('1,2,3', 'EUR')).toBeNull();
expect(parsePriceMinor('12.34,5.6', 'EUR')).toBeNull();
expect(parsePriceMinor(Number.NaN, 'EUR')).toBeNull();
expect(parsePriceMinor({ amount: 1 }, 'EUR')).toBeNull();
expect(parsePriceMinor('', 'EUR')).toBeNull();
});
});
describe('the address token', () => {
it('is 24 base32 characters and looked up by its hash, whatever its case', () => {
const token = newToken();
expect(token).toMatch(/^[a-z2-7]{24}$/);
expect(newToken()).not.toBe(token);
expect(hashToken(token.toUpperCase())).toBe(hashToken(token));
});
it('is read from where the template puts it, or after a plus', () => {
const token = 'abcdefghijklmnopqrstuvwx';
expect(tokenOf(`Trips <trek+${token}@mail.example.com>`, 'trek+{token}@mail.example.com')).toBe(token);
expect(tokenOf(`ab12${token}@in.example.com`, 'ab12{token}@in.example.com')).toBe(token);
expect(tokenOf(`box+${token}@example.com`, null)).toBe(token);
expect(tokenOf('box+short@example.com', null)).toBeNull();
expect(tokenOf('someone@example.com', 'trek+{token}@mail.example.com')).toBeNull();
});
});
describe('the sealed mail', () => {
it('opens to the same bytes, and a broken seal to nothing', () => {
const raw = Buffer.from([0x46, 0x72, 0x6f, 0x6d, 0x3a, 0x20, 0xe9, 0x00, 0xff]);
expect(openMail(sealMail(raw))?.equals(raw)).toBe(true);
expect(openMail(null)).toBeNull();
expect(openMail('enc:v1:broken')).toBeNull();
});
});
@@ -0,0 +1,86 @@
/**
* What the mail import tells people: the forwarder gets keep or undo, the
* other members of the trip a notice, a waiting mail one note; a failed
* notification never fails the write. The notification's undo button reaches
* the inbox's undo with the person who tapped it.
*/
import { MailIngestActionsService } from '../../../../src/nest/mail-ingest/mail-ingest-actions.service';
import { MailIngestNotificationActions } from '../../../../src/nest/mail-ingest/mail-ingest-notification-actions';
import { MailIngestNotifyService } from '../../../../src/nest/mail-ingest/mail-ingest-notify.service';
import { NotificationsService } from '../../../../src/nest/notifications/notifications.service';
import { Test } from '@nestjs/testing';
import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('../../../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo: vi.fn(),
logDebug: vi.fn(),
logError: vi.fn(),
logWarn: vi.fn(),
}));
const notifications = { send: vi.fn(), registerResponseAction: vi.fn() };
const actions = { undo: vi.fn(async () => ({})) };
let notify: MailIngestNotifyService;
let buttons: MailIngestNotificationActions;
beforeEach(async () => {
vi.clearAllMocks();
notifications.send.mockResolvedValue({ attempted: 1, delivered: 1 });
const moduleRef = await Test.createTestingModule({
providers: [
MailIngestNotifyService,
MailIngestNotificationActions,
{ provide: NotificationsService, useValue: notifications },
{ provide: MailIngestActionsService, useValue: actions },
],
}).compile();
notify = moduleRef.get(MailIngestNotifyService);
buttons = moduleRef.get(MailIngestNotificationActions);
});
const MIA = { id: 3, username: 'mia', email: 'mia@example.com', role: 'user' };
const BOOKING = { candidateId: 11, tripId: 7, tripTitle: 'Japan', title: 'LH 716', type: 'flight' };
describe('MailIngestNotifyService', () => {
it('asks the forwarder to keep or undo, and tells the trip’s other members', async () => {
await notify.bookingAdded(MIA, BOOKING);
const [forwarder, trip] = notifications.send.mock.calls.map(([payload]) => payload);
expect(forwarder).toMatchObject({
event: 'mail_booking_added',
scope: 'user',
targetId: 3,
params: { booking: 'LH 716', trip: 'Japan', tripId: '7', role: 'forwarder' },
inApp: {
type: 'boolean',
negativeTextKey: 'notif.action.undo',
negativeCallback: { action: 'mail_ingest_undo', payload: { candidateId: 11 } },
},
});
expect(trip).toMatchObject({ scope: 'trip', targetId: 7, actorId: 3, params: { role: 'traveller', actor: 'mia' } });
});
it('sends one note for waiting bookings, and survives a failed send', async () => {
notifications.send.mockRejectedValue(new Error('smtp down'));
await expect(notify.bookingsPending(3, 2)).resolves.toBeUndefined();
expect(notifications.send).toHaveBeenCalledWith(
expect.objectContaining({ event: 'mail_booking_pending', params: { count: '2' } }),
);
});
});
describe('MailIngestNotificationActions', () => {
it('registers undo and keep, and undoes the named booking for the person who tapped', async () => {
buttons.onModuleInit();
expect(notifications.registerResponseAction.mock.calls.map(([action]) => action)).toEqual([
'mail_ingest_undo',
'mail_ingest_keep',
]);
await buttons.undo({ candidateId: 11 }, 3);
expect(actions.undo).toHaveBeenCalledWith(11, 3, false);
await expect(buttons.undo({}, 3)).rejects.toThrow('This notification names no booking');
const keep = notifications.registerResponseAction.mock.calls[1][1] as () => Promise<void>;
await expect(keep()).resolves.toBeUndefined();
});
});
@@ -0,0 +1,91 @@
/**
* Whether the mail import runs and how: off until switched on, the TREK Cloud
* relay as the only transport of a managed install, the address template only
* with its placeholder, and a person's switches all on until they change one.
*/
import { MailIngestPrefs } from '../../../../src/db/entities/MailIngestPrefs.entity';
import { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';
import { MailIngestSettingsService } from '../../../../src/nest/mail-ingest/mail-ingest-settings.service';
import { SettingsService } from '../../../../src/nest/settings/settings.service';
import { getRepositoryToken } from '@mikro-orm/nestjs';
import { Test } from '@nestjs/testing';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const stored = new Map<string, string>();
const settings = { getAppSetting: vi.fn(async (key: string) => stored.get(key) ?? null) };
const env = { isManaged: vi.fn(() => false) };
const prefs = { findForUser: vi.fn(), upsertForUser: vi.fn(async () => undefined) };
let service: MailIngestSettingsService;
beforeEach(async () => {
vi.clearAllMocks();
stored.clear();
env.isManaged.mockReturnValue(false);
prefs.findForUser.mockResolvedValue(null);
const moduleRef = await Test.createTestingModule({
providers: [
MailIngestSettingsService,
{ provide: SettingsService, useValue: settings },
{ provide: RuntimeEnvService, useValue: env },
{ provide: getRepositoryToken(MailIngestPrefs), useValue: prefs },
],
}).compile();
service = moduleRef.get(MailIngestSettingsService);
});
describe('MailIngestSettingsService', () => {
it('is off until switched on', async () => {
expect(await service.isAvailable()).toBe(false);
stored.set('mail_ingest_enabled', 'true');
expect(await service.isAvailable()).toBe(true);
});
it('reads the transport, off for anything it does not know, the relay on a managed install', async () => {
expect(await service.transport()).toBe('off');
stored.set('mail_ingest_transport', 'imap');
expect(await service.transport()).toBe('imap');
stored.set('mail_ingest_transport', 'carrier-pigeon');
expect(await service.transport()).toBe('off');
env.isManaged.mockReturnValue(true);
expect(await service.transport()).toBe('cloud');
});
it('takes an address template only with its placeholder', async () => {
expect(await service.addressTemplate()).toBeNull();
stored.set('mail_ingest_address_template', 'trips@example.com');
expect(await service.addressTemplate()).toBeNull();
stored.set('mail_ingest_address_template', ' trek+{token}@example.com ');
expect(await service.addressTemplate()).toBe('trek+{token}@example.com');
});
it('reads the daily AI limit, ten when unset or broken', async () => {
expect(await service.aiDailyCap()).toBe(10);
stored.set('mail_ingest_ai_per_user_daily', '3');
expect(await service.aiDailyCap()).toBe(3);
stored.set('mail_ingest_ai_per_user_daily', '-1');
expect(await service.aiDailyCap()).toBe(10);
});
it('takes larger mails on the TREK Cloud, and the admin’s file types', async () => {
expect(service.maxMailBytes()).toBe(10 * 1024 * 1024);
env.isManaged.mockReturnValue(true);
expect(service.maxMailBytes()).toBe(25 * 1024 * 1024);
expect(await service.allowedFileTypes()).toContain('pdf');
stored.set('allowed_file_types', 'pdf');
expect(await service.allowedFileTypes()).toBe('pdf');
});
it('has every switch on for a person who never changed one, and writes only what changes', async () => {
expect(await service.prefsOf(4)).toEqual({ enabled: true, ai_enabled: true, auto_add: true });
prefs.findForUser.mockResolvedValue({ id: 1, user_id: 4, enabled: 1, ai_enabled: 0, auto_add: 1 });
expect(await service.updatePrefs(4, { ai_enabled: false })).toEqual({
enabled: true,
ai_enabled: false,
auto_add: true,
});
expect(prefs.upsertForUser).toHaveBeenCalledWith(4, { ai_enabled: 0 });
await service.updatePrefs(4, { enabled: true, auto_add: false });
expect(prefs.upsertForUser).toHaveBeenLastCalledWith(4, { enabled: 1, auto_add: 0 });
});
});
@@ -0,0 +1,128 @@
/**
* The forwarding addresses inside MailIngestModule over a snapshot test db: a
* person's own address and a trip's, renewing that retires the old token at
* once, and a trip address that stops working when its owner can no longer
* add bookings to the trip.
*/
import { MailIngestAddresses } from '../../../../src/db/entities/MailIngestAddresses.entity';
import { TripMembers } from '../../../../src/db/entities/TripMembers.entity';
import { DomainError } from '../../../../src/nest/common/domain-error';
import { MailIngestAddressService } from '../../../../src/nest/mail-ingest/mail-ingest-address.service';
import { MailIngestIntakeService } from '../../../../src/nest/mail-ingest/mail-ingest-intake.service';
import { MailIngestSettingsService } from '../../../../src/nest/mail-ingest/mail-ingest-settings.service';
import { MailIngestModule } from '../../../../src/nest/mail-ingest/mail-ingest.module';
import { PermissionsService } from '../../../../src/nest/permissions/permissions.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { deleteRows, findRow } from '../../../helpers/factories/rows';
import { setAppSetting } from '../../../helpers/factories/settings';
import { addTripMember, makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestModule, type TestModule } from '../../../helpers/test-module';
import { MikroORM } from '@mikro-orm/core';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
const orm = () => t.get(MikroORM);
const addresses = () => t.get(MailIngestAddressService);
const TEMPLATE = 'trek+{token}@mail.example.com';
const permissions = { checkPermission: vi.fn(async () => true) };
beforeAll(async () => {
t = await createTestModule({
db,
imports: [MailIngestModule],
overrides: [{ provide: PermissionsService, useValue: permissions }],
});
});
beforeEach(async () => {
resetTestDb(db);
vi.clearAllMocks();
permissions.checkPermission.mockResolvedValue(true);
await setAppSetting(orm(), 'mail_ingest_enabled', 'true');
await setAppSetting(orm(), 'mail_ingest_address_template', TEMPLATE);
});
afterAll(async () => {
await t.close();
db.close();
});
const tokenIn = (address: string) => /^trek\+([a-z2-7]+)@/.exec(address)?.[1] ?? '';
function mailTo(address: string, id: string): Buffer {
const lines = ['From: mia@example.com', `To: ${address}`, 'Subject: Booking', `Message-ID: <${id}@x>`];
return Buffer.from(`${lines.join('\r\n')}\r\n\r\nBooking ABC123`);
}
describe('a person’s own address', () => {
it('exists once asked for, and a renewal retires the old token', async () => {
const { user } = await makeUser(orm());
expect(await addresses().ownAddress(user.id)).toBeNull();
const first = await addresses().renewOwn(user.id);
expect(first?.address).toMatch(/^trek\+[a-z2-7]{24}@mail\.example\.com$/);
expect(first?.trip_id).toBeNull();
expect((await addresses().ownAddress(user.id))?.address).toBe(first?.address);
const second = await addresses().renewOwn(user.id);
expect(second?.address).not.toBe(first?.address);
const intake = t.get(MailIngestIntakeService);
expect(await intake.receive(mailTo(first?.address ?? '', 'old'), 'webhook')).toEqual({
status: 'refused',
reason: 'unknown_address',
});
expect(await intake.receive(mailTo(second?.address ?? '', 'new'), 'webhook')).toMatchObject({ status: 'accepted' });
const row = await findRow(orm(), MailIngestAddresses, { id: second?.id });
expect(row?.last_used_at).not.toBeNull();
});
it('cannot be made without an address template, and is not shown without one', async () => {
const { user } = await makeUser(orm());
await addresses().ensureOwn(user.id);
await setAppSetting(orm(), 'mail_ingest_address_template', '');
await expect(addresses().renewOwn(user.id)).rejects.toThrow(DomainError);
expect(await addresses().ownAddress(user.id)).toBeNull();
});
it('takes no mail while its person has the import off', async () => {
const { user } = await makeUser(orm());
const own = await addresses().renewOwn(user.id);
await t.get(MailIngestSettingsService).updatePrefs(user.id, { enabled: false });
expect(await addresses().resolve([own?.address ?? ''])).toBeNull();
await t.get(MailIngestSettingsService).updatePrefs(user.id, { enabled: true });
expect((await addresses().resolve([`Mia <${own?.address}>`]))?.person.id).toBe(user.id);
expect(tokenIn(own?.address ?? '')).toHaveLength(24);
});
});
describe('a trip address', () => {
it('belongs to the member who made it and stops working when they leave the trip', async () => {
const { user: owner } = await makeUser(orm());
const { user: member } = await makeUser(orm());
const trip = await makeTrip(orm(), owner.id);
await addTripMember(orm(), trip.id, member.id);
const made = await addresses().renewTripAddress(member.id, trip.id);
expect(made?.trip_id).toBe(trip.id);
expect((await addresses().tripAddress(member.id, trip.id))?.address).toBe(made?.address);
expect(await addresses().tripAddress(owner.id, trip.id)).toBeNull();
expect((await addresses().resolve([made?.address ?? '']))?.address.trip_id).toBe(trip.id);
await deleteRows(orm(), TripMembers, { trip: trip.id, user: member.id });
expect(await addresses().resolve([made?.address ?? ''])).toBeNull();
await expect(addresses().tripAddress(member.id, trip.id)).rejects.toThrow('Trip not found');
});
it('is refused to a member who may not add bookings, and revoked on request', async () => {
const { user: owner } = await makeUser(orm());
const trip = await makeTrip(orm(), owner.id);
const made = await addresses().renewTripAddress(owner.id, trip.id);
await addresses().revokeTripAddress(owner.id, trip.id);
expect(await addresses().tripAddress(owner.id, trip.id)).toBeNull();
expect(await addresses().resolve([made?.address ?? ''])).toBeNull();
permissions.checkPermission.mockResolvedValue(false);
await expect(addresses().renewTripAddress(owner.id, trip.id)).rejects.toThrow('Trip not found');
});
});
@@ -0,0 +1,418 @@
/**
* The mail import end to end inside MailIngestModule, over a snapshot test db
* with its real repositories and the real reservation, place and cost writes.
* Only what reaches outside is replaced: the AI reading (the walker stays
* real), kitinerary, file storage, geocoding and the notifications.
*/
import { BudgetItems } from '../../../../src/db/entities/BudgetItems.entity';
import { MailIngestCandidates } from '../../../../src/db/entities/MailIngestCandidates.entity';
import { MailIngestMessages } from '../../../../src/db/entities/MailIngestMessages.entity';
import { Reservations } from '../../../../src/db/entities/Reservations.entity';
import { importExternalId } from '../../../../src/nest/booking-import/booking-origin';
import { BookingImportService } from '../../../../src/nest/booking-import/booking-import.service';
import { DomainError } from '../../../../src/nest/common/domain-error';
import { FilesService } from '../../../../src/nest/files/files.service';
import { MailReadService } from '../../../../src/nest/llm-parse/mail-read.service';
import type { MailReading as AiReading } from '../../../../src/nest/llm-parse/mail-read.types';
import { walkMail } from '../../../../src/nest/llm-parse/mime-walker';
import { MailIngestActionsService } from '../../../../src/nest/mail-ingest/mail-ingest-actions.service';
import { MailIngestIntakeService } from '../../../../src/nest/mail-ingest/mail-ingest-intake.service';
import { MailIngestProcessJob } from '../../../../src/nest/mail-ingest/mail-ingest-process.job';
import { MailIngestRetentionJob } from '../../../../src/nest/mail-ingest/mail-ingest-retention.job';
import { MailIngestSettingsService } from '../../../../src/nest/mail-ingest/mail-ingest-settings.service';
import { MailIngestModule } from '../../../../src/nest/mail-ingest/mail-ingest.module';
import { MapsService } from '../../../../src/nest/maps/maps.service';
import { NotificationsService } from '../../../../src/nest/notifications/notifications.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { countRows, findRow, findRows, updateRows } from '../../../helpers/factories/rows';
import { setAddonEnabled, setAppSetting } from '../../../helpers/factories/settings';
import { addTripMember, makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestModule, type TestModule } from '../../../helpers/test-module';
import { MikroORM } from '@mikro-orm/core';
import type { BookingImportPreviewItem } from '@trek/shared';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('../../../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo: vi.fn(),
logDebug: vi.fn(),
logError: vi.fn(),
logWarn: vi.fn(),
}));
const NOW = new Date('2030-01-15T10:00:00Z');
const endpoint = (role: 'from' | 'to', name: string, code: string, lat: number, lng: number) => ({
role,
sequence: role === 'from' ? 0 : 1,
name,
code,
lat,
lng,
timezone: null,
local_time: null,
local_date: null,
});
const FLIGHT: BookingImportPreviewItem = {
type: 'flight',
title: 'LH 716 Tokyo to Osaka',
reservation_time: '2030-03-02T10:00',
reservation_end_time: '2030-03-02T11:15',
confirmation_number: 'ABC123',
metadata: { flight_number: 'LH716', price: '120,50', priceCurrency: 'EUR' },
endpoints: [
endpoint('from', 'Tokyo Haneda', 'HND', 35.55, 139.78),
endpoint('to', 'Osaka Itami', 'ITM', 34.78, 135.44),
],
source: { fileName: 'mail.eml', index: 0 },
};
const BODY = 'Booking reference ABC123. Flight LH 716 from Tokyo to Osaka on 2030-03-02.';
const machine = vi.fn(async (): Promise<BookingImportPreviewItem[]> => [FLIGHT]);
const bookingImport = {
readMailBookings: machine,
mapAiReservations: vi.fn(async (): Promise<BookingImportPreviewItem[]> => [FLIGHT]),
externalKey: (item: BookingImportPreviewItem) => importExternalId(item),
};
const aiRead = vi.fn();
const reader = { walk: (raw: Buffer) => walkMail(raw), isAvailable: vi.fn(async () => false), read: aiRead };
const files = {
createFileFromBytes: vi.fn(async () => ({ id: 77 })),
softDeleteFile: vi.fn(async () => undefined),
};
const notifications = { send: vi.fn(async () => ({ attempted: 1, delivered: 1 })), registerResponseAction: vi.fn() };
const db = createSnapshotTestDb();
let t: TestModule;
const orm = () => t.get(MikroORM);
beforeAll(async () => {
t = await createTestModule({
db,
imports: [MailIngestModule],
overrides: [
{ provide: BookingImportService, useValue: bookingImport },
{ provide: MailReadService, useValue: reader },
{ provide: FilesService, useValue: files },
{ provide: MapsService, useValue: { geocodeQuery: vi.fn(async () => null) } },
{ provide: NotificationsService, useValue: notifications },
],
});
});
beforeEach(async () => {
resetTestDb(db);
vi.clearAllMocks();
machine.mockResolvedValue([FLIGHT]);
reader.isAvailable.mockResolvedValue(false);
await setAppSetting(orm(), 'mail_ingest_enabled', 'true');
await setAddonEnabled(orm(), 'budget', true);
await setAddonEnabled(orm(), 'documents', true);
});
afterAll(async () => {
await t.close();
db.close();
});
const intake = () => t.get(MailIngestIntakeService);
const job = () => t.get(MailIngestProcessJob);
const actions = () => t.get(MailIngestActionsService);
function eml(id: string, subject = 'Fwd: Your flight LH 716', body = BODY): Buffer {
return Buffer.from(
[
'From: Mia <mia@example.com>',
'To: trips@example.com',
`Subject: ${subject}`,
`Message-ID: <${id}@example.com>`,
'Date: Mon, 1 Jan 2030 10:00:00 +0000',
'Content-Type: text/plain; charset=utf-8',
'',
body,
].join('\r\n'),
);
}
async function person() {
const { user } = await makeUser(orm(), { email: 'mia@example.com', username: 'mia' });
return user;
}
/** Uploads a mail for the person and runs the pipeline over it; answers the mail's id. */
async function forward(userId: number, raw: Buffer): Promise<number> {
const taken = await intake().upload(raw, userId);
if (taken.status !== 'accepted') throw new Error(`the mail was not taken in: ${JSON.stringify(taken)}`);
expect(await job().tick(NOW)).toBe(1);
return taken.messageId;
}
const entriesOf = (messageId: number) =>
findRows(orm(), MailIngestCandidates, { message: messageId }, { position: 'asc' });
describe('taking a mail in', () => {
it('refuses everything while the import is off', async () => {
const user = await person();
await setAppSetting(orm(), 'mail_ingest_enabled', 'false');
expect(await intake().upload(eml('a'), user.id)).toEqual({ status: 'refused', reason: 'unavailable' });
expect(await job().tick(NOW)).toBe(0);
});
it('stores a mail once, and refuses what is no mail', async () => {
const user = await person();
const first = await intake().upload(eml('a'), user.id);
expect(first.status).toBe('accepted');
expect(await intake().upload(eml('a'), user.id)).toMatchObject({ status: 'duplicate' });
expect(await intake().upload(Buffer.from('nothing to see'), user.id)).toEqual({
status: 'refused',
reason: 'not_a_mail',
});
const stored = await findRow(orm(), MailIngestMessages, { user: user.id });
expect(stored?.raw_eml_enc).toMatch(/^enc:v1:/);
});
it('refuses a mail to an address nobody holds', async () => {
expect(await intake().receive(eml('b'), 'webhook', ['trek+aaaaaaaaaaaaaaaaaaaaaaaa@example.com'])).toEqual({
status: 'refused',
reason: 'unknown_address',
});
});
});
describe('a booking that passes every check', () => {
it('lands in its trip with its cost and documents, and tells the forwarder and the trip', async () => {
const user = await person();
const { user: friend } = await makeUser(orm());
const trip = await makeTrip(orm(), user.id, { title: 'Japan', start_date: '2030-03-01', end_date: '2030-03-10' });
await addTripMember(orm(), trip.id, friend.id);
const messageId = await forward(user.id, eml('flight'));
const [entry] = await entriesOf(messageId);
expect(entry).toMatchObject({
resolution: 'auto_applied',
reason: null,
resolved_trip_id: trip.id,
source: 'kitinerary',
});
const booking = await findRow(orm(), Reservations, { trip: trip.id });
expect(booking).toMatchObject({
title: 'LH 716 Tokyo to Osaka',
external_source: 'mail',
external_id: importExternalId(FLIGHT),
sync_enabled: 0,
needs_review: 0,
});
expect(await findRow(orm(), BudgetItems, { trip: trip.id })).toMatchObject({ total_price: 120.5 });
expect(files.createFileFromBytes).toHaveBeenCalledWith(
trip.id,
expect.objectContaining({ originalname: 'mail.txt' }),
user.id,
expect.objectContaining({ reservation_id: booking?.id }),
);
expect(JSON.parse(String((await entriesOf(messageId))[0].created_ids_json)).file_ids).toEqual([77]);
expect(await findRow(orm(), MailIngestMessages, { id: messageId })).toMatchObject({ status: 'processed' });
const events = notifications.send.mock.calls.map(([payload]) => [payload.event, payload.scope]);
expect(events).toEqual([
['mail_booking_added', 'user'],
['mail_booking_added', 'trip'],
]);
expect(t.realtime.broadcastMock).toHaveBeenCalledWith(trip.id, 'reservation:created', expect.anything());
});
it('is undone by its forwarder: the booking and its cost go, the same mail again waits in the inbox', async () => {
const user = await person();
const trip = await makeTrip(orm(), user.id, { start_date: '2030-03-01', end_date: '2030-03-10' });
const [entry] = await entriesOf(await forward(user.id, eml('flight')));
await actions().undo(entry.id, user.id, false, NOW);
expect(await countRows(orm(), Reservations, { trip: trip.id })).toBe(0);
expect(await countRows(orm(), BudgetItems, { trip: trip.id })).toBe(0);
expect(files.softDeleteFile).toHaveBeenCalledWith(77);
await expect(actions().undo(entry.id, user.id, false, NOW)).rejects.toThrow(DomainError);
const [again] = await entriesOf(await forward(user.id, eml('flight-again')));
expect(again).toMatchObject({ resolution: 'pending', reason: 'possible_duplicate' });
});
it('asks before undoing a booking that was edited since', async () => {
const user = await person();
const trip = await makeTrip(orm(), user.id, { start_date: '2030-03-01', end_date: '2030-03-10' });
const [entry] = await entriesOf(await forward(user.id, eml('flight')));
await updateRows(orm(), Reservations, { trip: trip.id }, { notes: 'Window seat please' });
const refused = await actions()
.undo(entry.id, user.id, false, NOW)
.catch((err: unknown) => err);
expect(refused).toBeInstanceOf(DomainError);
expect((refused as DomainError).getResponse()).toMatchObject({ code: 'needs_confirmation', affects: ['edited'] });
await actions().undo(entry.id, user.id, true, NOW);
expect(await countRows(orm(), Reservations, { trip: trip.id })).toBe(0);
});
it('is not written twice when the trip holds it already', async () => {
const user = await person();
await makeTrip(orm(), user.id, { start_date: '2030-03-01', end_date: '2030-03-10' });
await forward(user.id, eml('flight'));
const [second] = await entriesOf(await forward(user.id, eml('flight-forwarded-again')));
expect(second).toMatchObject({ resolution: 'duplicate' });
});
});
describe('a booking that waits in the inbox', () => {
it('names why: no trip in its dates, and the person hears of it once', async () => {
const user = await person();
await makeTrip(orm(), user.id, { start_date: '2030-06-01', end_date: '2030-06-10' });
const [entry] = await entriesOf(await forward(user.id, eml('flight')));
expect(entry).toMatchObject({ resolution: 'pending', reason: 'no_trip_in_range' });
expect(notifications.send).toHaveBeenCalledWith(expect.objectContaining({ event: 'mail_booking_pending' }));
});
it('asks first when the person said so', async () => {
const user = await person();
await makeTrip(orm(), user.id, { start_date: '2030-03-01', end_date: '2030-03-10' });
await t.get(MailIngestSettingsService).updatePrefs(user.id, { auto_add: false });
const [entry] = await entriesOf(await forward(user.id, eml('flight')));
expect(entry).toMatchObject({ resolution: 'pending', reason: 'ask_first', suggested_trip_id: expect.any(Number) });
});
it('keeps a mail without a booking for its ways out, with why the AI did not read it', async () => {
const user = await person();
machine.mockResolvedValue([]);
const [entry] = await entriesOf(await forward(user.id, eml('nothing')));
expect(entry).toMatchObject({ resolution: 'pending', reason: 'ai_disabled', item_json: null });
const prefill = await actions().prefill(entry.id, user.id);
expect(prefill.item).toMatchObject({
type: 'flight',
confirmation_number: 'ABC123',
reservation_time: '2030-03-02',
});
const trip = await makeTrip(orm(), user.id, { start_date: '2030-03-01', end_date: '2030-03-10' });
const filed = await actions().fileToTrip(entry.id, user.id, trip.id, NOW);
expect(filed).toMatchObject({ resolution: 'filed', resolved_trip_id: trip.id });
});
it('is added by hand to the trip the person picks, and can be discarded instead', async () => {
const user = await person();
const trip = await makeTrip(orm(), user.id, { start_date: '2030-03-01', end_date: '2030-03-10' });
await t.get(MailIngestSettingsService).updatePrefs(user.id, { auto_add: false });
const [entry] = await entriesOf(await forward(user.id, eml('flight')));
const applied = await actions().applyToTrip(entry.id, user.id, trip.id, NOW);
expect(applied).toMatchObject({ resolution: 'applied', resolved_trip_id: trip.id });
expect(await countRows(orm(), Reservations, { trip: trip.id })).toBe(1);
await expect(actions().discard(entry.id, user.id, NOW)).rejects.toThrow('This entry was decided already');
});
});
describe('mails that are no booking', () => {
it('drops a newsletter without reading it', async () => {
const user = await person();
const raw = Buffer.from(
[
'From: news@shop.example',
'Subject: Our autumn deals',
'List-Unsubscribe: <mailto:off@shop.example>',
'Message-ID: <news@shop.example>',
'',
'Fresh deals for everyone who loves to shop with us.',
].join('\r\n'),
);
const messageId = await forward(user.id, raw);
expect(machine).not.toHaveBeenCalled();
expect(await findRow(orm(), MailIngestMessages, { id: messageId })).toMatchObject({
status: 'discarded',
reason: 'newsletter',
});
});
it('shows a forwarding confirmation’s code in the inbox', async () => {
const user = await person();
const messageId = await forward(
user.id,
eml('confirm', 'Gmail Forwarding Confirmation', 'Confirmation code: 612345678 for forwarding.'),
);
expect(await findRow(orm(), MailIngestMessages, { id: messageId })).toMatchObject({
forwarding_code: '612345678',
reason: 'forwarding_confirmation',
});
expect((await entriesOf(messageId))[0]).toMatchObject({ reason: 'forwarding_confirmation' });
});
it('discards a mail the AI read and found no booking in', async () => {
const user = await person();
reader.isAvailable.mockResolvedValue(true);
machine.mockResolvedValue([]);
aiRead.mockResolvedValue({ outcome: 'empty', bookings: [], documentText: BODY, imageOnly: false } as AiReading);
const messageId = await forward(user.id, eml('chat'));
expect(await findRow(orm(), MailIngestMessages, { id: messageId })).toMatchObject({
status: 'discarded',
reason: 'not_a_booking',
ai_used: 1,
});
});
});
describe('the AI’s trip pick', () => {
it('decides between two trips that fit only where the booking lies near the pick', async () => {
const user = await person();
reader.isAvailable.mockResolvedValue(true);
const japan = await makeTrip(orm(), user.id, { title: 'Japan', start_date: '2030-03-01', end_date: '2030-03-10' });
await makeTrip(orm(), user.id, { title: 'Work', start_date: '2030-02-25', end_date: '2030-03-05' });
aiRead.mockImplementation(async (input: { trips: Array<{ ref: string; title: string }> }) => ({
outcome: 'ok',
documentText: BODY,
imageOnly: false,
bookings: [
{
kind: 'new_booking',
reservations: [{ '@type': 'FlightReservation' }],
tripRef: input.trips.find((trip) => trip.title === 'Japan')?.ref ?? null,
tripConfidence: 0.9,
uncertainFields: [],
suggestedNewTrip: null,
},
],
}));
const [entry] = await entriesOf(await forward(user.id, eml('flight')));
// Japan has no place near Osaka the server could confirm: the inbox suggests it.
expect(entry).toMatchObject({ resolution: 'pending', reason: 'trip_ambiguous', suggested_trip_id: japan.id });
expect(entry.source).toBe('ai');
});
});
describe('a mail that keeps failing', () => {
it('is tried again later and given up after its last try', async () => {
const user = await person();
await makeTrip(orm(), user.id, { start_date: '2030-03-01', end_date: '2030-03-10' });
machine.mockRejectedValue(new Error('kitinerary crashed'));
const taken = await intake().upload(eml('poison'), user.id);
if (taken.status !== 'accepted') throw new Error('not taken in');
expect(await job().tick(NOW)).toBe(1);
expect(await findRow(orm(), MailIngestMessages, { id: taken.messageId })).toMatchObject({ status: 'queued' });
expect(await job().tick(new Date(NOW.getTime() + 60 * 60 * 1000))).toBe(1);
expect(await job().tick(new Date(NOW.getTime() + 2 * 60 * 60 * 1000))).toBe(1);
expect(await findRow(orm(), MailIngestMessages, { id: taken.messageId })).toMatchObject({
status: 'failed',
reason: 'processing_failed',
});
});
});
describe('the retention', () => {
it('purges a settled mail and keeps one an entry waits on', async () => {
const user = await person();
await makeTrip(orm(), user.id, { start_date: '2030-03-01', end_date: '2030-03-10' });
const added = await forward(user.id, eml('flight'));
machine.mockResolvedValue([]);
const waiting = await forward(user.id, eml('nothing'));
// Settled long ago: the mail with nothing waiting on it goes, the one an entry waits on stays.
const longAgo = { processed_at: '2000-01-01 00:00:00' };
await updateRows(orm(), MailIngestMessages, { id: { $in: [added, waiting] } }, longAgo);
await t.get(MailIngestRetentionJob).tick(new Date());
expect(await findRow(orm(), MailIngestMessages, { id: added })).toMatchObject({ raw_eml_enc: null });
expect((await findRow(orm(), MailIngestMessages, { id: waiting }))?.raw_eml_enc).toMatch(/^enc:v1:/);
});
});