The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
feat(mail-ingest): shared contracts for the booking mail import
Mauriced01f973e6292
diff --git a/shared/src/index.ts b/shared/src/index.tsindex e9433cfd7..f5ae4f5df 100644--- a/shared/src/index.ts+++ b/shared/src/index.ts@@ -45,6 +45,8 @@ export * from './reservation/reservation.schema';export * from './reservation/reservation-types';export * from './reservation/ki-reservation.schema';export * from './reservation/reservation-read.schema';+export * from './mail-ingest/mail-ingest-reason.schema';+export * from './mail-ingest/mail-ingest.schema';export * from './datetime/datetime-normalize';export * from './airtrail/airtrail.schema';export * from './dawarich/dawarich.schema';diff --git a/shared/src/mail-ingest/mail-ingest-reason.schema.ts b/shared/src/mail-ingest/mail-ingest-reason.schema.tsnew file mode 100644index 000000000..39cf129f4--- /dev/null+++ b/shared/src/mail-ingest/mail-ingest-reason.schema.ts@@ -0,0 +1,159 @@+import type { LlmParseOutcome } from '../reservation/reservation.schema';++import { z } from 'zod';++/**+ * Why a forwarded mail, or one booking read from it, was not added on its own:+ * the one list the inbox, the notifications, the admin status card and the MCP+ * tools name a reason from. The client words each one; the server never sends+ * prose for it.+ */+export const MAIL_INGEST_REASONS = [+ // The mail as a whole.+ /** A Gmail or Outlook forwarding confirmation: its code is shown, nothing is clicked. */+ 'forwarding_confirmation',+ /** A newsletter, a bulk or list mail. */+ 'newsletter',+ /** An out-of-office or other automatic reply. */+ 'auto_reply',+ /** Neither text nor an attachment worth reading. */+ 'empty_mail',+ /** The mail could not be read: broken MIME, a scan without a model that reads images. */+ 'mail_unreadable',+ /** Read, and holds no booking. */+ 'not_a_booking',+ /** More than the import or the model takes. */+ 'too_large',+ /** The address it came in on was renewed, revoked or belongs to someone who left the trip. */+ 'address_invalid',+ /** The address took its mails for the day. */+ 'address_daily_limit',+ /** Reading it failed three times. */+ 'processing_failed',++ // The AI reading.+ /** The TREK Cloud allowance for the period is used up. */+ 'ai_quota_exhausted',+ /** No AI reading for this person: not set up, switched off, or the new consent not given yet. */+ 'ai_disabled',+ /** The person's own daily limit of AI-read mails is reached. */+ 'ai_user_cap',+ /** The AI provider failed or refused. */+ 'ai_provider_error',++ // The trip.+ /** No trip the person may add bookings to covers the booking's dates. */+ 'no_trip_in_range',+ /** More than one trip could be meant. */+ 'trip_ambiguous',+ /** The trip has no dates to check the booking against. */+ 'trip_without_dates',+ /** The person may not add bookings to the trip. */+ 'no_edit_permission',+ /** A demo account adds nothing. */+ 'demo_mode',++ // The checks on one booking (plan G3 to G8).+ /** A date lies outside the trip, or on a day the trip has no row for (G3). */+ 'outside_trip_dates',+ /** The AI read a critical field differently from the machine-readable data (G4). */+ 'source_mismatch',+ /** A value that cannot be right: an unknown airport, an arrival before departure (G5). */+ 'implausible',+ /** A value the AI gave is not in the mail (G6). */+ 'not_in_text',+ /** Read from a page image alone, with no text to check it against (G6). */+ 'image_only',+ /** No type, start, or for a transport no origin and destination. */+ 'missing_critical_field',+ /** A transport, stay or rental without a booking reference. */+ 'missing_confirmation',+ /** More bookings in one mail than are added on their own. */+ 'too_many_bookings',+ /** A change or cancellation of an earlier booking. */+ 'change_or_cancellation',+ /** The booking itself is cancelled (G8). */+ 'cancelled',++ // Bookings already in the trip.+ /** A booking like it is in the trip already. */+ 'possible_duplicate',+ /** The trip holds this booking, and the mail says something else about it. */+ 'change_available',+ /** The same booking with different content. */+ 'conflict',++ // The person's own choice.+ /** "Ask first" is on: nothing is added without a tap. */+ 'ask_first',+] as const;+export const mailIngestReasonSchema = z.enum(MAIL_INGEST_REASONS);+export type MailIngestReason = z.infer<typeof mailIngestReasonSchema>;++/**+ * What the inbox notes about a mail without holding it back: an unconfirmed+ * sender is shown, never a reason to stop (owner decision 13.11.2026).+ */+export const mailIngestHintSchema = z.enum(['sender_unverified', 'attachments_skipped']);+export type MailIngestHint = z.infer<typeof mailIngestHintSchema>;++/**+ * The reason an AI reading that found nothing to add stands for; null where it+ * found bookings. One list instead of two: the outcome is how the reading+ * ended, the reason is what the person reads.+ */+export const MAIL_INGEST_REASON_BY_LLM_OUTCOME: Readonly<Record<LlmParseOutcome, MailIngestReason | null>> = {+ ok: null,+ empty: 'not_a_booking',+ no_text: 'mail_unreadable',+ quota_exhausted: 'ai_quota_exhausted',+ ai_disabled: 'ai_disabled',+ user_cap: 'ai_user_cap',+ provider_error: 'ai_provider_error',+ too_large: 'too_large',+};++/** The server's checks on a booking read from a mail, as the inbox lists them (plan G1 to G8). */+export const mailIngestCheckSchema = z.enum([+ 'schema',+ 'trip',+ 'dates',+ 'agreement',+ 'plausible',+ 'in_text',+ 'assignment',+ 'cancellation',+]);+export type MailIngestCheck = z.infer<typeof mailIngestCheckSchema>;++export const mailIngestCheckResultSchema = z.enum(['pass', 'fail', 'skipped']);+export type MailIngestCheckResult = z.infer<typeof mailIngestCheckResultSchema>;++/**+ * The fields of a booking the server may mark as uncertain: the AI's own+ * `uncertain_fields` must name these and nothing else, so a mail cannot write+ * free text through it.+ */+export const mailIngestFieldSchema = z.enum([+ 'type',+ 'title',+ 'status',+ 'reservation_time',+ 'reservation_end_time',+ 'confirmation_number',+ 'location',+ 'endpoints',+ 'check_in',+ 'check_out',+ 'price',+ 'currency',+ 'travelers',+ 'url',+ 'operator',+ 'seat',+ 'class',+ 'terminal',+ 'gate',+ 'trip',+]);+export type MailIngestField = z.infer<typeof mailIngestFieldSchema>;diff --git a/shared/src/mail-ingest/mail-ingest.schema.spec.ts b/shared/src/mail-ingest/mail-ingest.schema.spec.tsnew file mode 100644index 000000000..dc6701877--- /dev/null+++ b/shared/src/mail-ingest/mail-ingest.schema.spec.ts@@ -0,0 +1,183 @@+import { llmParseOutcomeSchema } from '../reservation/reservation.schema';+import {+ MAIL_INGEST_REASON_BY_LLM_OUTCOME,+ mailIngestFieldSchema,+ mailIngestHintSchema,+ mailIngestReasonSchema,+} from './mail-ingest-reason.schema';+import {+ mailIngestAddressSchema,+ mailIngestAdminStatusResponseSchema,+ mailIngestApplyRequestSchema,+ mailIngestCandidateSchema,+ mailIngestFileRequestSchema,+ mailIngestInboxEntrySchema,+ mailIngestInboxQuerySchema,+ mailIngestInboundResponseSchema,+ mailIngestMessageSchema,+ mailIngestMoveRequestSchema,+ mailIngestPrefsUpdateRequestSchema,+ mailIngestReviewRequestSchema,+ mailIngestSettingsResponseSchema,+ mailIngestUndoConflictSchema,+ mailIngestUndoRequestSchema,+} from './mail-ingest.schema';++import { describe, expect, it } from 'vitest';++const NOW = '2026-11-13T09:00:00.000Z';++const message = {+ id: 4,+ transport: 'cloud',+ subject: 'Your booking LH 716',+ received_at: NOW,+ status: 'processed',+ reason: null,+ hints: ['sender_unverified'],+ ai_used: true,+ trip_id: null,+ attachments: [{ file_name: 'ticket.pdf', kind: 'pdf', size: 48_213 }],+ forwarding_code: null,+};++const candidate = {+ id: 9,+ message_id: 4,+ item: {+ type: 'flight',+ title: 'LH 716',+ confirmation_number: 'ABC123',+ reservation_time: '2027-04-02T13:25',+ source: { fileName: 'mail', index: 0 },+ },+ source: 'ai',+ uncertain_fields: ['seat'],+ checks: { schema: 'pass', dates: 'pass', in_text: 'fail' },+ suggested_trip: { id: 3, title: 'Japan 2027', start_date: '2027-04-02', end_date: '2027-04-20' },+ suggested_new_trip: null,+ resolution: 'pending',+ reason: 'not_in_text',+ resolved_trip_id: null,+ reservation_ids: [],+ file_ids: [],+ created_at: NOW,+ resolved_at: null,+ undo_until: null,+};++describe('mail-ingest reasons', () => {+ it('MAILC-001: every AI outcome stands for one reason, and only a reading with bookings for none', () => {+ for (const outcome of llmParseOutcomeSchema.options) {+ const reason = MAIL_INGEST_REASON_BY_LLM_OUTCOME[outcome];+ if (outcome === 'ok') expect(reason).toBeNull();+ else expect(mailIngestReasonSchema.safeParse(reason).success, outcome).toBe(true);+ }+ expect(MAIL_INGEST_REASON_BY_LLM_OUTCOME.quota_exhausted).toBe('ai_quota_exhausted');+ });++ it('MAILC-002: an unverified sender is a hint, never a reason to hold a mail back', () => {+ expect(mailIngestHintSchema.safeParse('sender_unverified').success).toBe(true);+ expect(mailIngestReasonSchema.safeParse('sender_unverified').success).toBe(false);+ });++ it('MAILC-003: an uncertain field is one of the known names, never free text', () => {+ expect(mailIngestFieldSchema.safeParse('reservation_time').success).toBe(true);+ expect(mailIngestFieldSchema.safeParse('ignore previous instructions').success).toBe(false);+ });+});++describe('mail-ingest rows', () => {+ it('MAILC-010: a message and an inbox entry parse as the server sends them', () => {+ expect(mailIngestMessageSchema.safeParse(message).success).toBe(true);+ expect(mailIngestCandidateSchema.safeParse(candidate).success).toBe(true);+ expect(mailIngestInboxEntrySchema.safeParse({ ...candidate, message }).success).toBe(true);+ });++ it('MAILC-011: the entry for a mail that yielded no booking has no item and still a reason', () => {+ const unread = { ...candidate, item: null, source: null, checks: {}, reason: 'mail_unreadable' };+ expect(mailIngestCandidateSchema.safeParse(unread).success).toBe(true);+ });++ it('MAILC-012: refuses an unknown reason, check result or resolution', () => {+ expect(mailIngestCandidateSchema.safeParse({ ...candidate, reason: 'because' }).success).toBe(false);+ expect(mailIngestCandidateSchema.safeParse({ ...candidate, checks: { dates: 'maybe' } }).success).toBe(false);+ expect(mailIngestCandidateSchema.safeParse({ ...candidate, resolution: 'done' }).success).toBe(false);+ });++ it('MAILC-013: timestamps carry an offset', () => {+ expect(mailIngestMessageSchema.safeParse({ ...message, received_at: '2026-11-13 09:00:00' }).success).toBe(false);+ const address = { id: 1, address: '[email protected]', trip_id: null, created_at: NOW };+ expect(mailIngestAddressSchema.safeParse({ ...address, last_used_at: null }).success).toBe(true);+ });++ it('MAILC-014: the settings card answer', () => {+ const settings = {+ available: true,+ address: null,+ prefs: { enabled: true, ai_enabled: true, auto_add: false },+ ai_available: false,+ pending: 2,+ };+ expect(mailIngestSettingsResponseSchema.safeParse(settings).success).toBe(true);+ });++ it('MAILC-015: the admin status card holds counts, not mails', () => {+ const status = {+ transport: 'imap',+ last_ok_at: NOW,+ last_error: null,+ lease_until: null,+ last_day: { by_status: { processed: 12, discarded: 3 }, by_reason: { newsletter: 3 } },+ auto_applied: 9,+ undone: 1,+ ai_calls_today: 4,+ backlog: [2, 1],+ };+ expect(mailIngestAdminStatusResponseSchema.safeParse(status).success).toBe(true);+ expect(mailIngestInboundResponseSchema.safeParse({ accepted: true, duplicate: false }).success).toBe(true);+ });+});++describe('mail-ingest requests', () => {+ it('MAILC-020: the switches take at least one known setting and nothing else', () => {+ expect(mailIngestPrefsUpdateRequestSchema.safeParse({ auto_add: false }).success).toBe(true);+ expect(mailIngestPrefsUpdateRequestSchema.safeParse({}).success).toBe(false);+ expect(mailIngestPrefsUpdateRequestSchema.safeParse({ auto_add: 'yes' }).success).toBe(false);+ expect(mailIngestPrefsUpdateRequestSchema.safeParse({ auto_add: true, address: 'x' }).success).toBe(false);+ });++ it('MAILC-021: apply takes an optional trip, move and file a required one, all closed', () => {+ expect(mailIngestApplyRequestSchema.safeParse({}).success).toBe(true);+ expect(mailIngestApplyRequestSchema.safeParse({ trip_id: 3 }).success).toBe(true);+ expect(mailIngestApplyRequestSchema.safeParse({ trip_id: 0 }).success).toBe(false);+ expect(mailIngestMoveRequestSchema.safeParse({}).success).toBe(false);+ expect(mailIngestFileRequestSchema.safeParse({ trip_id: 3, reservation_id: 4 }).success).toBe(false);+ });++ it('MAILC-022: undo asks for confirmation through its own 409', () => {+ expect(mailIngestUndoRequestSchema.safeParse({}).success).toBe(true);+ expect(mailIngestUndoRequestSchema.safeParse({ confirm: true }).success).toBe(true);+ const conflict = { error: 'This cost moved balances', code: 'needs_confirmation', affects: ['balances'] };+ expect(mailIngestUndoConflictSchema.safeParse(conflict).success).toBe(true);+ expect(mailIngestUndoConflictSchema.safeParse({ ...conflict, affects: [] }).success).toBe(false);+ });++ it('MAILC-023: "Looks right" names known fields or none', () => {+ expect(mailIngestReviewRequestSchema.safeParse({}).success).toBe(true);+ expect(mailIngestReviewRequestSchema.safeParse({ fields: ['seat', 'gate'] }).success).toBe(true);+ expect(mailIngestReviewRequestSchema.safeParse({ fields: [] }).success).toBe(false);+ expect(mailIngestReviewRequestSchema.safeParse({ fields: ['notes'] }).success).toBe(false);+ });++ it('MAILC-024: the inbox query defaults to the open entries, a page of 50, and coerces the cursor', () => {+ expect(mailIngestInboxQuerySchema.parse({})).toEqual({ status: 'open', limit: 50 });+ expect(mailIngestInboxQuerySchema.parse({ status: 'resolved', before: '40', limit: '10' })).toEqual({+ status: 'resolved',+ before: 40,+ limit: 10,+ });+ expect(mailIngestInboxQuerySchema.safeParse({ limit: '500' }).success).toBe(false);+ expect(mailIngestInboxQuerySchema.safeParse({ status: 'all' }).success).toBe(false);+ });+});diff --git a/shared/src/mail-ingest/mail-ingest.schema.ts b/shared/src/mail-ingest/mail-ingest.schema.tsnew file mode 100644index 000000000..16455db58--- /dev/null+++ b/shared/src/mail-ingest/mail-ingest.schema.ts@@ -0,0 +1,333 @@+import { idSchema, idParamSchema, isoDateTime } from '../common/primitives.schema';+import { bookingImportPreviewItemSchema } from '../reservation/reservation.schema';+import {+ mailIngestCheckResultSchema,+ mailIngestCheckSchema,+ mailIngestFieldSchema,+ mailIngestHintSchema,+ mailIngestReasonSchema,+} from './mail-ingest-reason.schema';++import { z } from 'zod';++/**+ * Booking mail import contract: the /api/mail-ingest endpoints, the trip+ * address under /api/trips/:tripId/mail-ingest, and the admin status card.+ *+ * A person forwards a booking mail to their own address; the server reads it,+ * adds what passes its checks to the matching trip and keeps the rest in the+ * inbox ("open bookings") with a reason and three ways out. Timestamps are+ * ISO 8601 with an offset. Addresses carry their secret token, so they are+ * only ever sent to their owner and never through MCP.+ */++// ── Building blocks ─────────────────────────────────────────────────────────++/** How a mail reached the server: the instance's own IMAP box or webhook, the TREK Cloud relay, or an upload. */+export const mailIngestTransportSchema = z.enum(['imap', 'webhook', 'cloud', 'upload']);+export type MailIngestTransport = z.infer<typeof mailIngestTransportSchema>;++/** The attachment types a booking travels in; every other attachment is left in the mail. */+export const mailAttachmentKindSchema = z.enum(['pdf', 'pkpass', 'ics', 'jpeg', 'png', 'webp']);+export type MailAttachmentKind = z.infer<typeof mailAttachmentKindSchema>;++/** A mail's way through the import: waiting, being read, done, dropped (no booking), or given up on. */+export const mailIngestMessageStatusSchema = z.enum(['queued', 'processing', 'processed', 'discarded', 'failed']);+export type MailIngestMessageStatus = z.infer<typeof mailIngestMessageStatusSchema>;++/** Where a booking's fields came from: the AI, or one of the machine-readable sources read without it. */+export const mailIngestSourceSchema = z.enum(['ai', 'kitinerary', 'json_ld', 'ics', 'pkpass', 'text']);+export type MailIngestSource = z.infer<typeof mailIngestSourceSchema>;++/**+ * What became of one booking read from a mail: waiting in the inbox, added on+ * its own or by the person, filed as a document, discarded, set aside as a+ * duplicate or a conflict, or added and undone.+ */+export const mailIngestResolutionSchema = z.enum([+ 'pending',+ 'auto_applied',+ 'applied',+ 'filed',+ 'discarded',+ 'duplicate',+ 'conflict',+ 'undone',+]);+export type MailIngestResolution = z.infer<typeof mailIngestResolutionSchema>;++/** A trip as the inbox names it: enough to show and pick it, nothing of its content. */+export const mailIngestTripRefSchema = z.object({+ id: idSchema,+ title: z.string(),+ start_date: z.string().nullable(),+ end_date: z.string().nullable(),+});+export type MailIngestTripRef = z.infer<typeof mailIngestTripRefSchema>;++/** The trip the AI proposed to create when none fits; never created on its own. */+export const mailIngestSuggestedTripSchema = z.object({+ destination: z.string().max(120),+ start_date: z.string().nullable(),+ end_date: z.string().nullable(),+});+export type MailIngestSuggestedTrip = z.infer<typeof mailIngestSuggestedTripSchema>;++// ── Address and preferences ────────────────────────────────────────────────++/**+ * A forwarding address: the person's own, or one for a single trip+ * (`trip_id`). The address holds its secret, so it reaches its owner only.+ */+export const mailIngestAddressSchema = z.object({+ id: idSchema,+ address: z.string().min(3).max(320),+ trip_id: idSchema.nullable(),+ created_at: isoDateTime,+ last_used_at: isoDateTime.nullable(),+});+export type MailIngestAddress = z.infer<typeof mailIngestAddressSchema>;++/** The person's own switches: the import itself, AI reading, and adding on its own or asking first. */+export const mailIngestPrefsSchema = z.object({+ enabled: z.boolean(),+ ai_enabled: z.boolean(),+ auto_add: z.boolean(),+});+export type MailIngestPrefs = z.infer<typeof mailIngestPrefsSchema>;++/** GET /api/mail-ingest/settings, and the answer to every write of the settings card. */+export const mailIngestSettingsResponseSchema = z.object({+ /** False where the import is off on this server or not part of the plan: the client shows nothing. */+ available: z.boolean(),+ address: mailIngestAddressSchema.nullable(),+ prefs: mailIngestPrefsSchema,+ /** Whether a mail could be read by AI for this person right now. */+ ai_available: z.boolean(),+ /** Open entries in the inbox. */+ pending: z.number().int().nonnegative(),+});+export type MailIngestSettingsResponse = z.infer<typeof mailIngestSettingsResponseSchema>;++/** PATCH /api/mail-ingest/settings: any of the switches, at least one. */+export const mailIngestPrefsUpdateRequestSchema = z+ .strictObject({+ enabled: z.boolean().optional(),+ ai_enabled: z.boolean().optional(),+ auto_add: z.boolean().optional(),+ })+ .refine((body) => Object.values(body).some((value) => value !== undefined), {+ message: 'Name at least one setting',+ });+export type MailIngestPrefsUpdateRequest = z.infer<typeof mailIngestPrefsUpdateRequestSchema>;++/**+ * POST /api/mail-ingest/address/renew, and GET, POST+ * /api/trips/:tripId/mail-ingest/address. A renewed address replaces the old+ * one at once; null where a trip has no address of the person's.+ */+export const mailIngestAddressResponseSchema = z.object({ address: mailIngestAddressSchema.nullable() });+export type MailIngestAddressResponse = z.infer<typeof mailIngestAddressResponseSchema>;++// ── Messages and the bookings read from them ────────────────────────────────++export const mailIngestAttachmentSchema = z.object({+ file_name: z.string(),+ kind: mailAttachmentKindSchema,+ size: z.number().int().nonnegative(),+});+export type MailIngestAttachment = z.infer<typeof mailIngestAttachmentSchema>;++/** One forwarded mail, without its content: the inbox row's header. */+export const mailIngestMessageSchema = z.object({+ id: idSchema,+ transport: mailIngestTransportSchema,+ subject: z.string().nullable(),+ received_at: isoDateTime,+ status: mailIngestMessageStatusSchema,+ reason: mailIngestReasonSchema.nullable(),+ hints: z.array(mailIngestHintSchema),+ /** Whether the AI read it, which counts against the person's limits. */+ ai_used: z.boolean(),+ /** The trip whose address it came in on, null for the person's own address. */+ trip_id: idSchema.nullable(),+ attachments: z.array(mailIngestAttachmentSchema),+ /** The code of a forwarding confirmation, shown large so the person can copy it; nothing is clicked. */+ forwarding_code: z.string().max(64).nullable(),+});+export type MailIngestMessage = z.infer<typeof mailIngestMessageSchema>;++/**+ * One booking read from a mail, or, for a mail that yielded none, the entry+ * standing for the mail itself (`item` null) so the ways out still apply.+ */+export const mailIngestCandidateSchema = z.object({+ id: idSchema,+ message_id: idSchema,+ item: bookingImportPreviewItemSchema.nullable(),+ source: mailIngestSourceSchema.nullable(),+ uncertain_fields: z.array(mailIngestFieldSchema),+ checks: z.partialRecord(mailIngestCheckSchema, mailIngestCheckResultSchema),+ suggested_trip: mailIngestTripRefSchema.nullable(),+ suggested_new_trip: mailIngestSuggestedTripSchema.nullable(),+ resolution: mailIngestResolutionSchema,+ reason: mailIngestReasonSchema.nullable(),+ resolved_trip_id: idSchema.nullable(),+ reservation_ids: z.array(idSchema),+ file_ids: z.array(idSchema),+ created_at: isoDateTime,+ resolved_at: isoDateTime.nullable(),+ /** Until when an added booking can be undone in one tap; null once that is over or for one not added. */+ undo_until: isoDateTime.nullable(),+});+export type MailIngestCandidate = z.infer<typeof mailIngestCandidateSchema>;++/** An inbox row: the booking and the mail it came from. */+export const mailIngestInboxEntrySchema = mailIngestCandidateSchema.extend({ message: mailIngestMessageSchema });+export type MailIngestInboxEntry = z.infer<typeof mailIngestInboxEntrySchema>;++// ── The inbox ───────────────────────────────────────────────────────────────++/** GET /api/mail-ingest/inbox: open entries (the default) or decided ones, newest first, paged by id. */+export const mailIngestInboxQuerySchema = z.strictObject({+ status: z.enum(['open', 'resolved']).default('open'),+ before: idParamSchema.optional(),+ limit: z.coerce.number().int().min(1).max(100).default(50),+});+export type MailIngestInboxQuery = z.infer<typeof mailIngestInboxQuerySchema>;++export const mailIngestInboxResponseSchema = z.object({+ entries: z.array(mailIngestInboxEntrySchema),+ pending: z.number().int().nonnegative(),+ /** The `before` of the next page, null on the last one. */+ next_before: idSchema.nullable(),+});+export type MailIngestInboxResponse = z.infer<typeof mailIngestInboxResponseSchema>;++/** GET /api/mail-ingest/inbox/count: the badge on the menu entry. */+export const mailIngestInboxCountResponseSchema = z.object({ pending: z.number().int().nonnegative() });+export type MailIngestInboxCountResponse = z.infer<typeof mailIngestInboxCountResponseSchema>;++/** GET /api/mail-ingest/messages/:id/preview: "Show mail", as plain text without its headers. */+export const mailIngestMessagePreviewResponseSchema = z.object({+ id: idSchema,+ subject: z.string().nullable(),+ received_at: isoDateTime,+ text: z.string(),+ attachments: z.array(mailIngestAttachmentSchema),+});+export type MailIngestMessagePreviewResponse = z.infer<typeof mailIngestMessagePreviewResponseSchema>;++// ── Acting on an entry ──────────────────────────────────────────────────────+// Every write takes an X-Idempotency-Key header, so a replayed tap from the+// offline queue does nothing twice; the key is not part of the bodies.++/**+ * POST /api/mail-ingest/candidates/:id/apply: add the booking, to the trip+ * the inbox suggested or, with `trip_id`, to the one the person picked.+ */+export const mailIngestApplyRequestSchema = z.strictObject({ trip_id: idSchema.optional() });+export type MailIngestApplyRequest = z.infer<typeof mailIngestApplyRequestSchema>;++/** POST /api/mail-ingest/candidates/:id/move: the added booking into another trip. */+export const mailIngestMoveRequestSchema = z.strictObject({ trip_id: idSchema });+export type MailIngestMoveRequest = z.infer<typeof mailIngestMoveRequestSchema>;++/** POST /api/mail-ingest/candidates/:id/file: the mail's attachments, or its text, as documents of a trip. */+export const mailIngestFileRequestSchema = z.strictObject({ trip_id: idSchema });+export type MailIngestFileRequest = z.infer<typeof mailIngestFileRequestSchema>;++/**+ * POST /api/mail-ingest/candidates/:id/undo. An added booking whose cost has+ * moved balances, or that was edited since, is only undone with `confirm`.+ */+export const mailIngestUndoRequestSchema = z.strictObject({ confirm: z.boolean().optional() });+export type MailIngestUndoRequest = z.infer<typeof mailIngestUndoRequestSchema>;++/** The 409 an undo without `confirm` answers with, naming what undoing it would touch. */+export const mailIngestUndoConflictSchema = z.object({+ error: z.string(),+ code: z.literal('needs_confirmation'),+ affects: z.array(z.enum(['balances', 'edited'])).min(1),+});+export type MailIngestUndoConflict = z.infer<typeof mailIngestUndoConflictSchema>;++/**+ * The answer of every action on an entry (apply, move, file, undo, discard,+ * read with AI): the entry as it is now, with what it created.+ */+export const mailIngestCandidateResponseSchema = z.object({ candidate: mailIngestCandidateSchema });+export type MailIngestCandidateResponse = z.infer<typeof mailIngestCandidateResponseSchema>;++/**+ * GET /api/mail-ingest/candidates/:id/prefill ("Fill in yourself"): the+ * booking form's starting values and the trip it opens in. The form saves+ * through the ordinary booking route.+ */+export const mailIngestPrefillResponseSchema = z.object({+ trip_id: idSchema.nullable(),+ item: bookingImportPreviewItemSchema,+});+export type MailIngestPrefillResponse = z.infer<typeof mailIngestPrefillResponseSchema>;++/**+ * POST /api/trips/:tripId/reservations/:id/mail-review ("Looks right"): clear+ * the check marks of the named fields, or of all of them.+ */+export const mailIngestReviewRequestSchema = z.strictObject({+ fields: z.array(mailIngestFieldSchema).min(1).optional(),+});+export type MailIngestReviewRequest = z.infer<typeof mailIngestReviewRequestSchema>;++export const mailIngestReviewResponseSchema = z.object({+ reservation_id: idSchema,+ /** The fields still marked. */+ uncertain_fields: z.array(mailIngestFieldSchema),+});+export type MailIngestReviewResponse = z.infer<typeof mailIngestReviewResponseSchema>;++// ── Mail coming in ──────────────────────────────────────────────────────────++/** POST /api/mail-ingest/upload: an .eml file read like a forwarded mail; a mail already in is not read twice. */+export const mailIngestUploadResponseSchema = z.object({+ message: mailIngestMessageSchema,+ duplicate: z.boolean(),+});+export type MailIngestUploadResponse = z.infer<typeof mailIngestUploadResponseSchema>;++/** POST /api/mail-ingest/inbound, the signed webhook: taken in, or known already. */+export const mailIngestInboundResponseSchema = z.object({+ accepted: z.literal(true),+ duplicate: z.boolean(),+});+export type MailIngestInboundResponse = z.infer<typeof mailIngestInboundResponseSchema>;++// ── Admin ───────────────────────────────────────────────────────────────────++/** How this instance takes mail in: not at all, its own IMAP box, a webhook, or the TREK Cloud relay. */+export const mailIngestTransportSettingSchema = z.enum(['off', 'imap', 'webhook', 'cloud']);+export type MailIngestTransportSetting = z.infer<typeof mailIngestTransportSettingSchema>;++const countSchema = z.number().int().nonnegative();++/**+ * GET /api/admin/mail-ingest/status: how the import runs, in counts only.+ * No subject, sender or content of any mail is part of it.+ */+export const mailIngestAdminStatusResponseSchema = z.object({+ transport: mailIngestTransportSettingSchema,+ last_ok_at: isoDateTime.nullable(),+ last_error: z.string().nullable(),+ lease_until: isoDateTime.nullable(),+ /** Mails of the last 24 hours, by status and by reason. */+ last_day: z.object({+ by_status: z.partialRecord(mailIngestMessageStatusSchema, countSchema),+ by_reason: z.partialRecord(mailIngestReasonSchema, countSchema),+ }),+ auto_applied: countSchema,+ undone: countSchema,+ ai_calls_today: countSchema,+ /** Open entries per person who has any, as numbers; who they are is not part of it. */+ backlog: z.array(countSchema),+});+export type MailIngestAdminStatusResponse = z.infer<typeof mailIngestAdminStatusResponseSchema>;diff --git a/shared/src/realtime/events.schema.spec.ts b/shared/src/realtime/events.schema.spec.tsindex 874a237a9..559c3f6de 100644--- a/shared/src/realtime/events.schema.spec.ts+++ b/shared/src/realtime/events.schema.spec.ts@@ -175,6 +175,8 @@ const FIXTURES: Record<TrekWsEventName, Record<string, unknown>> = {'journey:contributor:changed': { journeyId: 3, targetUserId: 2, role: 'editor' },'journey:photos:updated': { journeyId: 3 },'journey:recording:updated': { journeyId: 3, date: '2026-05-14' },+ 'mailInbox:changed': { pending: 3 },+ 'mailInbox:settings': {},'import:progress': { jobId: 'j1', tripId: 1, status: 'running', done: 1, total: 3, fileName: 'a.pdf' },'import:done': { jobId: 'j1', tripId: 1, result: { items: [] } },'import:error': { jobId: 'j1', tripId: 1, message: 'boom' },@@ -197,7 +199,7 @@ const DRIFT_VARIANTS: Partial<Record<TrekWsEventName, Record<string, unknown>[]>};describe('@trek/shared realtime event registry', () => {- it('WSEVT-REG-001: pins the authoritative inventory counts (79 trip + 41 user = 120)', () => {+ it('WSEVT-REG-001: pins the authoritative inventory counts (79 trip + 43 user = 122)', () => {// 67th to 69th trip event: the three collab:link:* a shared link emits.// 70th and 71st: the road trip's vias and tracks, which used to be written silently.// 74th: docsync:changed, so a sync run that moved documents refreshes the@@ -215,9 +217,11 @@ describe('@trek/shared realtime event registry', () => {// notification:read-all, trips:changed, settings:updated, tags:changed,// atlas:changed, journey:updated, journey:deleted). Registered first, the// writes that send them follow.+ // 42nd and 43rd user event: mailInbox:changed and mailInbox:settings, the+ // inbox of forwarded booking mails and its settings card.expect(TREK_WS_TRIP_EVENT_NAMES).toHaveLength(80);- expect(TREK_WS_USER_EVENT_NAMES).toHaveLength(41);- expect(TREK_WS_EVENT_NAMES).toHaveLength(121);+ expect(TREK_WS_USER_EVENT_NAMES).toHaveLength(43);+ expect(TREK_WS_EVENT_NAMES).toHaveLength(123);});it('WSEVT-REG-002: every name is domain:action shaped and outside the reserved plugin: namespace', () => {@@ -270,4 +274,12 @@ describe('@trek/shared realtime event registry', () => {false,);});++ it('WSEVT-REG-009: mailInbox:changed carries a count and nothing negative', () => {+ const changed = TREK_WS_EVENTS['mailInbox:changed'].payload;+ expect(changed.safeParse({ pending: 0 }).success).toBe(true);+ expect(changed.safeParse({ pending: -1 }).success).toBe(false);+ expect(changed.safeParse({ pending: 1.5 }).success).toBe(false);+ expect(changed.safeParse({}).success).toBe(false);+ });});diff --git a/shared/src/realtime/events.schema.ts b/shared/src/realtime/events.schema.tsindex e43d8c8d7..43ee28400 100644--- a/shared/src/realtime/events.schema.ts+++ b/shared/src/realtime/events.schema.ts@@ -441,6 +441,14 @@ export const TREK_WS_EVENTS = {}),},+ // ── Mail import (user-scoped) ────────────────────────────────────────────+ // The person's inbox of forwarded bookings changed: a mail was read, an entry+ // decided. Carries the open count for the badge; an open inbox reads itself again.+ 'mailInbox:changed': { scope: 'user', payload: z.object({ pending: z.number().int().nonnegative() }) },+ // The person's address or switches changed on another tab or device: the+ // settings card reads them again. Content-free, since the address holds a secret.+ 'mailInbox:settings': { scope: 'user', payload: empty },+// ── Booking import (user-scoped; push() injects jobId + tripId) ─────────'import:progress': {scope: 'user',