feat(mail-ingest): inbox, settings and trip address UI on desktop and phone (wip)

This commit is contained in:
Maurice
2026-11-13 17:20:56 +01:00
parent cbd1800976
commit 8dedab0375
30 changed files with 1621 additions and 51 deletions
+42
View File
@@ -0,0 +1,42 @@
import apiClient from './client';
/**
* The booking mail import (server nest/mail-ingest): the person's settings and
* forwarding address, the inbox of bookings read from forwarded mails, and the
* actions on them. Answers come back unparsed; store/mailIngestStore.ts checks
* them against the shared contracts. apiClient puts an idempotency key on every
* write, so a request sent again on a flaky connection acts once.
*/
const data = (response: { data: unknown }) => response.data;
export type MailIngestAction = 'apply' | 'move' | 'file' | 'undo' | 'discard' | 'read-ai';
export const mailIngestApi = {
settings: (): Promise<unknown> => apiClient.get('/mail-ingest/settings').then(data),
updateSettings: (body: { enabled?: boolean; ai_enabled?: boolean; auto_add?: boolean }): Promise<unknown> =>
apiClient.patch('/mail-ingest/settings', body).then(data),
renewAddress: (): Promise<unknown> => apiClient.post('/mail-ingest/address/renew', {}).then(data),
tripAddress: (tripId: number): Promise<unknown> => apiClient.get(`/trips/${tripId}/mail-ingest/address`).then(data),
createTripAddress: (tripId: number): Promise<unknown> =>
apiClient.post(`/trips/${tripId}/mail-ingest/address`, {}).then(data),
inbox: (params: { status?: 'open' | 'resolved'; before?: number; limit?: number }): Promise<unknown> =>
apiClient.get('/mail-ingest/inbox', { params }).then(data),
inboxCount: (): Promise<unknown> => apiClient.get('/mail-ingest/inbox/count').then(data),
preview: (messageId: number): Promise<unknown> => apiClient.get(`/mail-ingest/messages/${messageId}/preview`).then(data),
prefill: (candidateId: number): Promise<unknown> =>
apiClient.get(`/mail-ingest/candidates/${candidateId}/prefill`).then(data),
act: (candidateId: number, action: MailIngestAction, body: Record<string, unknown> = {}): Promise<unknown> =>
apiClient.post(`/mail-ingest/candidates/${candidateId}/${action}`, body).then(data),
review: (tripId: number, reservationId: number, fields?: string[]): Promise<unknown> =>
apiClient.post(`/trips/${tripId}/reservations/${reservationId}/mail-review`, fields ? { fields } : {}).then(data),
upload: (file: File): Promise<unknown> => {
const form = new FormData();
form.append('file', file);
return apiClient.post('/mail-ingest/upload', form).then(data);
},
};
+23 -1
View File
@@ -6,7 +6,7 @@ import { useSettingsStore } from '../../store/settingsStore'
import { useAddonStore } from '../../store/addonStore'
import { usePluginStore } from '../../store/pluginStore'
import { useTranslation } from '../../i18n'
import { Plane, LogOut, Settings, ChevronDown, Shield, ArrowLeft, ChevronLeft, Moon, Sun, Monitor, CalendarDays, Briefcase, Globe, Compass, BookOpen, Bookmark } from 'lucide-react'
import { Plane, LogOut, Settings, ChevronDown, Shield, ArrowLeft, ChevronLeft, Moon, Sun, Monitor, CalendarDays, Briefcase, Globe, Compass, BookOpen, Bookmark, Inbox } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import InAppNotificationBell from './InAppNotificationBell.tsx'
import HelpButton from '../Help/HelpButton'
@@ -14,6 +14,9 @@ import AssistantLauncher from '../Assistant/AssistantLauncher'
import { resolvePluginIcon } from '../shared/PluginIcon'
import { visibleManagedNavItems } from '../../managed'
import { useCollapseOnOverflow } from '../../hooks/useCollapseOnOverflow'
import { useMailIngestStore } from '../../store/mailIngestStore'
import { openMailInbox } from '../MailIngest/mailInboxOpener'
import MailInboxDialog from '../MailIngest/MailInboxDialog'
const ADDON_ICONS: Record<string, LucideIcon> = { CalendarDays, Briefcase, Globe, Compass, Bookmark }
@@ -43,6 +46,14 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
const location = useLocation()
const [userMenuOpen, setUserMenuOpen] = useState<boolean>(false)
const [scrolled, setScrolled] = useState<boolean>(false)
// The booking mail import's inbox: its menu entry shows only where the import is on for this person.
const mailImport = useMailIngestStore(s => s.settings)
const mailPending = useMailIngestStore(s => s.pending)
const mailImportOn = !!mailImport?.available && mailImport.prefs.enabled
const userId = user?.id
useEffect(() => {
if (userId) void useMailIngestStore.getState().loadSettings()
}, [userId])
const darkMode = settings.dark_mode
const dark = darkMode === true || darkMode === 'dark' || (darkMode === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)
@@ -326,6 +337,16 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
{t('nav.settings')}
</Link>
{/* Bookings from forwarded mails that wait for a decision; only where the import is on. */}
{mailImportOn && (
<button type="button" onClick={() => { setUserMenuOpen(false); openMailInbox() }}
className="flex w-full items-center gap-2 px-4 py-2 text-sm transition-colors text-content-secondary hover:bg-surface-hover">
<Inbox className="w-4 h-4" />
<span className="min-w-0 flex-1 truncate text-start">{t('mailInbox.title')}</span>
{mailPending > 0 && <span className="rounded-full bg-accent px-1.5 text-xs font-semibold text-accent-text">{mailPending}</span>}
</button>
)}
{!managed && (
<Link to="/help" onClick={() => setUserMenuOpen(false)}
className="flex items-center gap-2 px-4 py-2 text-sm transition-colors text-content-secondary"
@@ -378,6 +399,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
</div>
)}
</div>
{mailImportOn && <MailInboxDialog />}
</nav>
)
}
@@ -0,0 +1,177 @@
import { useId, type ReactElement } from 'react';
import { Copy, FilePlus2, FileText, Inbox, Loader2, Mail, PencilLine, Plus, Sparkles, Trash2 } from 'lucide-react';
import type { MailIngestInboxEntry } from '@trek/shared';
import { useTranslation } from '../../i18n';
import { copyText } from '../../utils/clipboard';
import { formatDate } from '../../utils/formatters';
import { RES_ICONS } from '../Planner/DayPlanSidebar.constants';
import { DialogButton, DialogHeader, DialogIconButton, DialogShell, DialogTile, NEUTRAL_TINT } from '../shared/DialogShell';
import { useToast } from '../shared/Toast';
import { entryDates, entryTitle, reasonText, type InboxAction } from './mailInboxModel';
import { useMailInbox, type InboxTrip } from './useMailInbox';
/** The icon and the label of each way out, so a row and the trip picker word them alike. */
function actionLook(action: InboxAction, t: (key: string) => string): { icon: ReactElement; label: string } {
switch (action) {
case 'add':
return { icon: <Plus size={14} strokeWidth={2.2} />, label: t('mailInbox.action.add') };
case 'choose':
return { icon: <Plus size={14} strokeWidth={2.2} />, label: t('mailInbox.action.choose') };
case 'file':
return { icon: <FilePlus2 size={14} strokeWidth={2} />, label: t('mailInbox.action.file') };
case 'manual':
return { icon: <PencilLine size={14} strokeWidth={2} />, label: t('mailInbox.action.manual') };
case 'readAi':
return { icon: <Sparkles size={14} strokeWidth={2} />, label: t('mailInbox.action.readAi') };
case 'discard':
return { icon: <Trash2 size={14} strokeWidth={2} />, label: t('mailInbox.action.discard') };
}
}
function Entry({ entry, inbox }: { entry: MailIngestInboxEntry; inbox: ReturnType<typeof useMailInbox> }) {
const { t, locale } = useTranslation();
const toast = useToast();
const title = entryTitle(entry) ?? t('mailInbox.untitled');
const dates = entryDates(entry);
const reason = entry.reason ?? entry.message.reason;
const Icon = entry.item ? RES_ICONS[entry.item.type as keyof typeof RES_ICONS] || Mail : Mail;
const [primary, ...rest] = inbox.actionsOf(entry);
const busy = inbox.busy === entry.id;
const code = entry.message.forwarding_code;
return (
<li className="flex gap-3 rounded-xl border border-edge-faint bg-surface-card p-3.5">
<span className="grid h-9 w-9 flex-none place-items-center rounded-lg bg-surface-tertiary text-content-muted">
<Icon size={16} strokeWidth={2} />
</span>
<div className="min-w-0 flex-1">
<div className="flex min-w-0 items-baseline gap-2">
<span dir="auto" className="min-w-0 truncate text-body font-semibold text-content">{title}</span>
{dates && (
<span className="flex-none text-caption tabular-nums text-content-muted">
{formatDate(dates.start, locale)}
{dates.end ? ` → ${formatDate(dates.end, locale)}` : ''}
</span>
)}
</div>
{reason && <div className="mt-0.5 text-caption text-warning">{reasonText(reason, t)}</div>}
{code && (
<div className="mt-2 flex items-center gap-2">
<code dir="ltr" className="rounded-lg bg-surface-tertiary px-2.5 py-1 font-geist text-subtitle font-semibold tracking-[0.08em] text-content">
{code}
</code>
<DialogIconButton
label={t('mailInbox.settings.copy')}
icon={<Copy size={13} strokeWidth={2} />}
onClick={async () => {
if (await copyText(code)) toast.success(t('common.copied'));
}}
/>
</div>
)}
<div className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-caption text-content-faint">
{entry.suggested_trip && (
<span className="rounded-full bg-surface-tertiary px-2 py-0.5 font-medium text-content-secondary">{entry.suggested_trip.title}</span>
)}
<button type="button" onClick={() => inbox.showMail(entry)} className="inline-flex items-center gap-1 hover:text-content">
<FileText size={12} strokeWidth={2} />
{t('mailInbox.showMail')}
</button>
</div>
</div>
<div className="flex flex-none items-start gap-1.5">
{busy && <Loader2 size={16} strokeWidth={2} className="mt-2 animate-spin text-content-faint" />}
{rest.map((action) => {
const look = actionLook(action, t);
return <DialogIconButton key={action} label={look.label} icon={look.icon} danger={action === 'discard'} disabled={busy} onClick={() => inbox.perform(entry, action)} />;
})}
{primary && primary !== 'discard' && (
<DialogButton variant="primary" icon={actionLook(primary, t).icon} disabled={busy} onClick={() => inbox.perform(entry, primary)}>
{actionLook(primary, t).label}
</DialogButton>
)}
{primary === 'discard' && (
<DialogIconButton label={actionLook('discard', t).label} icon={actionLook('discard', t).icon} danger disabled={busy} onClick={() => inbox.perform(entry, 'discard')} />
)}
</div>
</li>
);
}
function TripPicker({ trips, onPick, onCancel }: { trips: InboxTrip[]; onPick: (id: number) => void; onCancel: () => void }) {
const { t, locale } = useTranslation();
return (
<div className="flex flex-col gap-2">
<div className="text-body font-semibold text-content">{t('mailInbox.pickTrip')}</div>
<ul className="flex max-h-[50vh] flex-col gap-1.5 overflow-y-auto">
{trips.map((trip) => (
<li key={trip.id}>
<button type="button" onClick={() => onPick(trip.id)} className="flex w-full items-baseline justify-between gap-3 rounded-lg bg-surface-tertiary px-3 py-2.5 text-start hover:bg-surface-hover">
<span dir="auto" className="min-w-0 truncate text-body font-medium text-content">{trip.title}</span>
{trip.start_date && <span className="flex-none text-caption tabular-nums text-content-muted">{formatDate(trip.start_date, locale)}</span>}
</button>
</li>
))}
</ul>
<div>
<DialogButton onClick={onCancel}>{t('common.cancel')}</DialogButton>
</div>
</div>
);
}
/**
* Bookings from forwarded mails that wait for the person: one row each with
* what TREK read, why it waits, the trip it suggests, and the ways out (add,
* choose a trip, keep the mail as a document, fill in the form, read again with
* AI, discard). Mounted once by the layout; opened from the account menu, the
* settings card or a notification.
*/
export default function MailInboxDialog(): ReactElement | null {
const { t } = useTranslation();
const inbox = useMailInbox();
const titleId = useId();
if (!inbox.open) return null;
const header = (
<DialogHeader
tile={<DialogTile><Inbox size={18} strokeWidth={2} /></DialogTile>}
tint={NEUTRAL_TINT}
labelId={titleId}
onClose={inbox.close}
title={t('mailInbox.title')}
sub={inbox.pending > 0 ? t('mailInbox.pendingCount', { count: inbox.pending }) : t('mailInbox.empty')}
/>
);
return (
<DialogShell onClose={inbox.close} labelledBy={titleId} width="editor" align="top" header={header} blocked={!!inbox.picking}>
{inbox.picking ? (
<TripPicker trips={inbox.trips} onPick={inbox.pick} onCancel={inbox.cancelPick} />
) : inbox.preview ? (
<div className="flex flex-col gap-3">
<div className="text-body font-semibold text-content">{inbox.preview.subject ?? t('mailInbox.untitled')}</div>
<pre className="max-h-[55vh] overflow-auto whitespace-pre-wrap rounded-lg bg-surface-tertiary p-3 font-geist text-caption text-content-secondary">{inbox.preview.text}</pre>
<div>
<DialogButton onClick={inbox.closePreview}>{t('mailInbox.backToList')}</DialogButton>
</div>
</div>
) : inbox.entries.length === 0 ? (
<div className="flex flex-col items-center gap-2 py-10 text-center">
<Inbox size={28} strokeWidth={1.6} className="text-content-faint" />
<div className="text-body font-medium text-content">{t('mailInbox.empty')}</div>
<div className="max-w-sm text-caption text-content-muted">{t('mailInbox.emptyHint')}</div>
</div>
) : (
<ul className="flex flex-col gap-2">
{inbox.entries.map((entry) => <Entry key={entry.id} entry={entry} inbox={inbox} />)}
{inbox.hasMore && (
<li className="flex justify-center pt-1">
<DialogButton onClick={inbox.loadMore} disabled={inbox.loading}>{t('mailInbox.loadMore')}</DialogButton>
</li>
)}
</ul>
)}
</DialogShell>
);
}
@@ -0,0 +1,96 @@
import { mailIngestAddressResponseSchema, type MailIngestAddress } from '@trek/shared';
import { useEffect, useState, type ReactElement } from 'react';
import { Copy, Mail, Plus } from 'lucide-react';
import { mailIngestApi } from '../../api/mailIngest';
import { useTranslation } from '../../i18n';
import { useMailIngestStore } from '../../store/mailIngestStore';
import { copyText } from '../../utils/clipboard';
import { useToast } from '../shared/Toast';
/**
* The trip's own forwarding address, under the file drop of the import dialog
* (desktop and phone share that dialog): a mail sent to it lands in this trip
* without any guessing. Created on request, since most people forward to their
* own address; it is the person's own, so a fellow traveller gets another.
* Nothing where the import is off for the person.
*/
export default function TripMailForward({ tripId }: { tripId: number }): ReactElement | null {
const { t } = useTranslation();
const toast = useToast();
const settings = useMailIngestStore((s) => s.settings);
const loadSettings = useMailIngestStore((s) => s.loadSettings);
const on = !!settings?.available && settings.prefs.enabled;
const [address, setAddress] = useState<MailIngestAddress | null>(null);
const [creating, setCreating] = useState(false);
useEffect(() => {
if (!settings) void loadSettings();
}, [settings, loadSettings]);
useEffect(() => {
if (!on) return;
let live = true;
mailIngestApi
.tripAddress(tripId)
.then((raw) => {
const parsed = mailIngestAddressResponseSchema.safeParse(raw);
if (live && parsed.success) setAddress(parsed.data.address);
})
.catch(() => {});
return () => {
live = false;
};
}, [on, tripId]);
if (!on) return null;
const create = async () => {
setCreating(true);
try {
setAddress(mailIngestAddressResponseSchema.parse(await mailIngestApi.createTripAddress(tripId)).address);
} catch {
toast.error(t('mailInbox.settings.saveError'));
} finally {
setCreating(false);
}
};
const copy = async () => {
if (address && (await copyText(address.address))) toast.success(t('common.copied'));
};
return (
<div className="mt-1 flex flex-col gap-2 rounded-xl bg-surface-tertiary px-3.5 py-3">
<div className="flex items-center gap-2 text-body font-semibold text-content">
<Mail size={15} strokeWidth={2} className="text-content-muted" />
{t('mailInbox.trip.title')}
</div>
<div className="text-caption text-content-muted">{t('mailInbox.trip.hint')}</div>
{address ? (
<div className="flex min-w-0 items-center gap-2">
<code dir="ltr" className="min-w-0 flex-1 truncate rounded-lg bg-surface-card px-2.5 py-1.5 font-geist text-caption text-content">
{address.address}
</code>
<button
type="button"
onClick={() => void copy()}
aria-label={t('mailInbox.settings.copy')}
className="grid h-8 w-8 flex-none place-items-center rounded-lg bg-surface-card text-content-muted hover:text-content"
>
<Copy size={14} strokeWidth={2} />
</button>
</div>
) : (
<button
type="button"
onClick={() => void create()}
disabled={creating}
className="inline-flex w-fit items-center gap-1.5 rounded-lg bg-surface-card px-3 py-1.5 text-caption font-semibold text-content hover:bg-surface-hover disabled:opacity-50"
>
<Plus size={13} strokeWidth={2.2} />
{t('mailInbox.trip.create')}
</button>
)}
</div>
);
}
@@ -0,0 +1,84 @@
// FE-MAILINBOX-MODEL-001 to FE-MAILINBOX-MODEL-006
import type { MailIngestInboxEntry } from '@trek/shared';
import { MAIL_INGEST_REASONS } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import { actionsOf, canUndo, entryDates, entryTitle, reasonText } from './mailInboxModel';
function entry(over: Partial<MailIngestInboxEntry> = {}, message: Partial<MailIngestInboxEntry['message']> = {}): MailIngestInboxEntry {
return {
id: 1,
message_id: 10,
item: {
type: 'hotel',
title: 'Hotel Kanra Kyoto',
reservation_time: '2026-06-11T15:00',
reservation_end_time: '2026-06-14T10:00',
source: { fileName: 'mail.eml', index: 0 },
},
source: 'ai',
uncertain_fields: [],
checks: {},
suggested_trip: { id: 5, title: 'Japan', start_date: '2026-06-10', end_date: '2026-06-20' },
suggested_new_trip: null,
resolution: 'pending',
reason: 'ask_first',
resolved_trip_id: null,
reservation_ids: [],
file_ids: [],
created_at: '2026-06-01T10:00:00.000Z',
resolved_at: null,
undo_until: null,
message: {
id: 10,
transport: 'imap',
subject: 'Your booking at Hotel Kanra',
received_at: '2026-06-01T09:59:00.000Z',
status: 'processed',
reason: null,
hints: [],
ai_used: true,
trip_id: null,
attachments: [],
forwarding_code: null,
...message,
},
...over,
};
}
describe('mailInboxModel', () => {
it('FE-MAILINBOX-MODEL-001: a read booking with a suggested trip is added in one tap, with every way out after it', () => {
expect(actionsOf(entry(), false)).toEqual(['add', 'file', 'manual', 'discard']);
});
it('FE-MAILINBOX-MODEL-002: without a suggestion the person chooses the trip', () => {
expect(actionsOf(entry({ suggested_trip: null }), false)[0]).toBe('choose');
});
it('FE-MAILINBOX-MODEL-003: a mail without a booking offers the document, the form, and AI only where it can help', () => {
const none = entry({ item: null, reason: 'not_a_booking' }, { attachments: [{ file_name: 'invoice.pdf', kind: 'pdf', size: 1 }] });
expect(actionsOf(none, false)).toEqual(['file', 'manual', 'discard']);
expect(actionsOf(none, true)).toEqual(['file', 'manual', 'readAi', 'discard']);
});
it('FE-MAILINBOX-MODEL-004: a forwarding confirmation or a newsletter only informs', () => {
expect(actionsOf(entry({ item: null, reason: null }, { reason: 'forwarding_confirmation', forwarding_code: '123456' }), true)).toEqual(['discard']);
});
it('FE-MAILINBOX-MODEL-005: every reason has its words, and title and dates come from the booking', () => {
const t = (key: string) => key;
for (const reason of MAIL_INGEST_REASONS) expect(reasonText(reason, t)).toMatch(/^mailInbox\.reason\./);
expect(entryTitle(entry())).toBe('Hotel Kanra Kyoto');
expect(entryTitle(entry({ item: null }))).toBe('Your booking at Hotel Kanra');
expect(entryDates(entry())).toEqual({ start: '2026-06-11', end: '2026-06-14' });
expect(entryDates(entry({ item: null }))).toBeNull();
});
it('FE-MAILINBOX-MODEL-006: an added booking can be undone until its deadline', () => {
const now = Date.parse('2026-06-05T00:00:00Z');
expect(canUndo({ resolution: 'auto_applied', undo_until: '2026-06-08T00:00:00Z' }, now)).toBe(true);
expect(canUndo({ resolution: 'auto_applied', undo_until: '2026-06-01T00:00:00Z' }, now)).toBe(false);
expect(canUndo({ resolution: 'pending', undo_until: '2026-06-08T00:00:00Z' }, now)).toBe(false);
});
});
@@ -0,0 +1,123 @@
import type { MailIngestInboxEntry, MailIngestReason } from '@trek/shared';
/**
* What an inbox entry offers and how it reads, worked out once for the desktop
* dialog and the phone sheet. Pure: the reasons come from the server as codes
* (MAIL_INGEST_REASONS) and are worded here through i18n keys, never as server
* prose.
*/
/** The ways out of an entry, in the order the row offers them. */
export type InboxAction = 'add' | 'choose' | 'file' | 'manual' | 'readAi' | 'discard';
/** Reasons where reading the mail again with AI is worth a try. */
const AI_RETRY: ReadonlySet<MailIngestReason> = new Set(['ai_quota_exhausted', 'ai_user_cap', 'ai_provider_error', 'ai_disabled', 'not_a_booking', 'mail_unreadable']);
/** Reasons that need no booking decision at all: the entry only informs. */
const INFO_ONLY: ReadonlySet<MailIngestReason> = new Set(['forwarding_confirmation', 'newsletter', 'auto_reply']);
export function actionsOf(entry: MailIngestInboxEntry, aiAvailable: boolean): InboxAction[] {
const reason = entry.reason ?? entry.message.reason;
if (reason && INFO_ONLY.has(reason)) return ['discard'];
const actions: InboxAction[] = [];
if (entry.item) actions.push(entry.suggested_trip ? 'add' : 'choose');
if (entry.message.attachments.length > 0 || entry.item) actions.push('file');
actions.push('manual');
if (aiAvailable && reason && AI_RETRY.has(reason)) actions.push('readAi');
actions.push('discard');
return actions;
}
/**
* A reason in the reader's words. A switch of literal keys rather than a table,
* so the i18n check sees every key in use and a new code fails the type check
* here first.
*/
export function reasonText(reason: MailIngestReason, t: (key: string) => string): string {
switch (reason) {
case 'forwarding_confirmation':
return t('mailInbox.reason.forwardingConfirmation');
case 'newsletter':
return t('mailInbox.reason.newsletter');
case 'auto_reply':
return t('mailInbox.reason.autoReply');
case 'empty_mail':
return t('mailInbox.reason.emptyMail');
case 'mail_unreadable':
return t('mailInbox.reason.mailUnreadable');
case 'not_a_booking':
return t('mailInbox.reason.notABooking');
case 'too_large':
return t('mailInbox.reason.tooLarge');
case 'address_invalid':
return t('mailInbox.reason.addressInvalid');
case 'address_daily_limit':
return t('mailInbox.reason.addressDailyLimit');
case 'processing_failed':
return t('mailInbox.reason.processingFailed');
case 'ai_quota_exhausted':
return t('mailInbox.reason.aiQuotaExhausted');
case 'ai_disabled':
return t('mailInbox.reason.aiDisabled');
case 'ai_user_cap':
return t('mailInbox.reason.aiUserCap');
case 'ai_provider_error':
return t('mailInbox.reason.aiProviderError');
case 'no_trip_in_range':
return t('mailInbox.reason.noTripInRange');
case 'trip_ambiguous':
return t('mailInbox.reason.tripAmbiguous');
case 'trip_without_dates':
return t('mailInbox.reason.tripWithoutDates');
case 'no_edit_permission':
return t('mailInbox.reason.noEditPermission');
case 'demo_mode':
return t('mailInbox.reason.demoMode');
case 'outside_trip_dates':
return t('mailInbox.reason.outsideTripDates');
case 'source_mismatch':
return t('mailInbox.reason.sourceMismatch');
case 'implausible':
return t('mailInbox.reason.implausible');
case 'not_in_text':
return t('mailInbox.reason.notInText');
case 'image_only':
return t('mailInbox.reason.imageOnly');
case 'missing_critical_field':
return t('mailInbox.reason.missingCriticalField');
case 'missing_confirmation':
return t('mailInbox.reason.missingConfirmation');
case 'too_many_bookings':
return t('mailInbox.reason.tooManyBookings');
case 'change_or_cancellation':
return t('mailInbox.reason.changeOrCancellation');
case 'cancelled':
return t('mailInbox.reason.cancelled');
case 'possible_duplicate':
return t('mailInbox.reason.possibleDuplicate');
case 'change_available':
return t('mailInbox.reason.changeAvailable');
case 'conflict':
return t('mailInbox.reason.conflict');
case 'ask_first':
return t('mailInbox.reason.askFirst');
}
}
/** The entry's headline: the booking's title, else the mail's subject, else nothing to show. */
export function entryTitle(entry: MailIngestInboxEntry): string | null {
return entry.item?.title || entry.message.subject || null;
}
/** The booking's day, or days, as YYYY-MM-DD for the caller to format; null when it has none. */
export function entryDates(entry: MailIngestInboxEntry): { start: string; end: string | null } | null {
const start = entry.item?.reservation_time?.slice(0, 10);
if (!start) return null;
const end = entry.item?.reservation_end_time?.slice(0, 10) ?? null;
return { start, end: end && end !== start ? end : null };
}
/** True while an added booking can still be taken back in one tap. */
export function canUndo(entry: { undo_until: string | null; resolution: string }, now: number): boolean {
return (entry.resolution === 'applied' || entry.resolution === 'auto_applied') && !!entry.undo_until && Date.parse(entry.undo_until) > now;
}
@@ -0,0 +1,11 @@
import { create } from 'zustand';
/**
* Whether the inbox of bookings from forwarded mails is open. One flag for the
* whole app, so the settings card, the account menu and a notification open
* the same dialog (desktop) or sheet (phone), which the layout mounts once.
*/
export const useMailInboxOpen = create<{ open: boolean }>(() => ({ open: false }));
export const openMailInbox = (): void => useMailInboxOpen.setState({ open: true });
export const closeMailInbox = (): void => useMailInboxOpen.setState({ open: false });
@@ -0,0 +1,101 @@
import { mailIngestSettingsResponseSchema, mailIngestUploadResponseSchema, type MailIngestPrefs } from '@trek/shared';
import { useEffect, useRef, useState } from 'react';
import { mailIngestApi } from '../../api/mailIngest';
import { useTranslation } from '../../i18n';
import { useMailIngestStore } from '../../store/mailIngestStore';
import { copyText } from '../../utils/clipboard';
import { useToast } from '../shared/Toast';
/** How long the renew button waits for its second tap before it gives up. */
const CONFIRM_MS = 4000;
/**
* The booking mail import card behind both settings shells: the person's
* address with copy and renew, the three switches, and the .eml upload. The
* desktop section and its phone twin only lay this out. Renewing needs a second
* tap within a few seconds, because the old address stops working at once and
* every forwarding rule pointing at it has to change.
*/
export function useMailImportSettings() {
const { t } = useTranslation();
const toast = useToast();
const settings = useMailIngestStore((s) => s.settings);
const setSettings = useMailIngestStore((s) => s.setSettings);
const loadSettings = useMailIngestStore((s) => s.loadSettings);
const [saving, setSaving] = useState<keyof MailIngestPrefs | null>(null);
const [renewArmed, setRenewArmed] = useState(false);
const [renewing, setRenewing] = useState(false);
const [uploading, setUploading] = useState(false);
const armTimer = useRef(0);
useEffect(() => {
void loadSettings();
}, [loadSettings]);
useEffect(() => () => window.clearTimeout(armTimer.current), []);
const toggle = async (key: keyof MailIngestPrefs) => {
if (!settings || saving) return;
setSaving(key);
try {
const parsed = mailIngestSettingsResponseSchema.parse(
await mailIngestApi.updateSettings({ [key]: !settings.prefs[key] }),
);
setSettings(parsed);
} catch {
toast.error(t('mailInbox.settings.saveError'));
} finally {
setSaving(null);
}
};
const copyAddress = async () => {
if (!settings?.address) return;
if (await copyText(settings.address.address)) toast.success(t('common.copied'));
else toast.error(t('mailInbox.settings.copyError'));
};
const renew = async () => {
if (!renewArmed) {
setRenewArmed(true);
armTimer.current = window.setTimeout(() => setRenewArmed(false), CONFIRM_MS);
return;
}
window.clearTimeout(armTimer.current);
setRenewArmed(false);
setRenewing(true);
try {
await mailIngestApi.renewAddress();
await loadSettings();
toast.success(t('mailInbox.settings.renewed'));
} catch {
toast.error(t('mailInbox.settings.saveError'));
} finally {
setRenewing(false);
}
};
const upload = async (file: File) => {
setUploading(true);
try {
const { duplicate } = mailIngestUploadResponseSchema.parse(await mailIngestApi.upload(file));
toast.success(duplicate ? t('mailInbox.settings.uploadDuplicate') : t('mailInbox.settings.uploaded'));
} catch {
toast.error(t('mailInbox.settings.uploadError'));
} finally {
setUploading(false);
}
};
return {
/** Null while loading; the card renders nothing where the import is not available. */
settings: settings?.available ? settings : null,
saving,
toggle,
copyAddress,
renew,
renewArmed,
renewing,
upload,
uploading,
};
}
@@ -0,0 +1,125 @@
import { mailIngestMessagePreviewResponseSchema, type MailIngestInboxEntry, type MailIngestMessagePreviewResponse } from '@trek/shared';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { tripsApi } from '../../api/client';
import { mailIngestApi, type MailIngestAction } from '../../api/mailIngest';
import { useTranslation } from '../../i18n';
import { useMailIngestStore } from '../../store/mailIngestStore';
import { useToast } from '../shared/Toast';
import { closeMailInbox, useMailInboxOpen } from './mailInboxOpener';
import { actionsOf, type InboxAction } from './mailInboxModel';
export interface InboxTrip {
id: number;
title: string;
start_date: string | null;
end_date: string | null;
}
/**
* The inbox of bookings from forwarded mails behind the desktop dialog and the
* phone sheet: the open entries, the trips to choose from, and every way out of
* an entry. An action that needs a trip and has none suggested asks for one
* first (`picking`); "Fill in yourself" opens the booking form in the trip with
* the mail's values, through the planner (?mailPrefill=).
*/
export function useMailInbox() {
const { t } = useTranslation();
const toast = useToast();
const navigate = useNavigate();
const open = useMailInboxOpen((s) => s.open);
const { entries, pending, nextBefore, loadingInbox, settings, loadInbox, loadSettings, act } = useMailIngestStore();
const [trips, setTrips] = useState<InboxTrip[]>([]);
const [busy, setBusy] = useState<number | null>(null);
/** The entry and the action waiting for a trip to be picked. */
const [picking, setPicking] = useState<{ entry: MailIngestInboxEntry; action: 'apply' | 'file' | 'manual' } | null>(null);
const [preview, setPreview] = useState<MailIngestMessagePreviewResponse | null>(null);
useEffect(() => {
if (!open) return;
void loadInbox();
if (!settings) void loadSettings();
tripsApi
.list()
.then((d: { trips?: InboxTrip[] }) => setTrips((d.trips ?? []).map(({ id, title, start_date, end_date }) => ({ id, title, start_date, end_date }))))
.catch(() => setTrips([]));
}, [open, loadInbox, loadSettings, settings]);
const run = async (entry: MailIngestInboxEntry, action: MailIngestAction, body: Record<string, unknown>, done: string) => {
setBusy(entry.id);
try {
await act(entry.id, action, body);
toast.success(done);
} catch {
toast.error(t('mailInbox.actionError'));
} finally {
setBusy(null);
}
};
const perform = (entry: MailIngestInboxEntry, action: InboxAction) => {
const tripId = entry.suggested_trip?.id;
switch (action) {
case 'add':
return run(entry, 'apply', {}, t('mailInbox.added'));
case 'choose':
return setPicking({ entry, action: 'apply' });
case 'file':
return tripId ? run(entry, 'file', { trip_id: tripId }, t('mailInbox.filed')) : setPicking({ entry, action: 'file' });
case 'readAi':
return run(entry, 'read-ai', {}, t('mailInbox.readAgain'));
case 'discard':
return run(entry, 'discard', {}, t('mailInbox.discarded'));
case 'manual':
return fillIn(entry);
}
};
const pick = (tripId: number) => {
if (!picking) return;
const { entry, action } = picking;
setPicking(null);
if (action === 'manual') return openForm(entry, tripId);
void run(entry, action, { trip_id: tripId }, action === 'apply' ? t('mailInbox.added') : t('mailInbox.filed'));
};
const openForm = (entry: MailIngestInboxEntry, tripId: number) => {
closeMailInbox();
navigate(`/trips/${tripId}?mailPrefill=${entry.id}`);
};
const fillIn = (entry: MailIngestInboxEntry) => {
const tripId = entry.suggested_trip?.id;
if (tripId) openForm(entry, tripId);
else setPicking({ entry, action: 'manual' });
};
const showMail = async (entry: MailIngestInboxEntry) => {
try {
setPreview(mailIngestMessagePreviewResponseSchema.parse(await mailIngestApi.preview(entry.message_id)));
} catch {
toast.error(t('mailInbox.previewError'));
}
};
const aiAvailable = !!settings?.ai_available && !!settings.prefs.ai_enabled;
return {
open,
close: closeMailInbox,
entries,
pending,
hasMore: nextBefore !== null,
loadMore: () => void loadInbox(true),
loading: loadingInbox,
trips,
busy,
actionsOf: (entry: MailIngestInboxEntry) => actionsOf(entry, aiAvailable),
perform: (entry: MailIngestInboxEntry, action: InboxAction) => void perform(entry, action),
picking,
pick,
cancelPick: () => setPicking(null),
preview,
showMail: (entry: MailIngestInboxEntry) => void showMail(entry),
closePreview: () => setPreview(null),
};
}
@@ -0,0 +1,50 @@
import { isTransportReservationType, mailIngestPrefillResponseSchema, type BookingImportPreviewItem } from '@trek/shared';
import { useEffect, useRef } from 'react';
import type { SetURLSearchParams } from 'react-router';
import { mailIngestApi } from '../../api/mailIngest';
/**
* "Fill in yourself" from the mail inbox lands in the trip as ?mailPrefill=<id>:
* once the trip has loaded, the booking form opens with what the mail held, the
* same per-item review a file import uses, and the parameter leaves the address
* so a reload does not open it again. Desktop and phone share the planner hook
* this runs in.
*/
export function useMailPrefillLink({
searchParams,
setSearchParams,
loaded,
startImportReview,
}: {
searchParams: URLSearchParams;
setSearchParams: SetURLSearchParams;
loaded: boolean;
startImportReview: (items: BookingImportPreviewItem[], files?: File[], kind?: 'transports' | 'bookings') => void;
}): void {
const requested = searchParams.get('mailPrefill');
const handled = useRef<string | null>(null);
useEffect(() => {
if (!requested || !loaded || handled.current === requested) return;
handled.current = requested;
setSearchParams(
(prev) => {
const next = new URLSearchParams(prev);
next.delete('mailPrefill');
return next;
},
{ replace: true },
);
const id = Number(requested);
if (!Number.isInteger(id) || id <= 0) return;
mailIngestApi
.prefill(id)
.then((raw) => {
const { item } = mailIngestPrefillResponseSchema.parse(raw);
startImportReview([item], [], isTransportReservationType(item.type) ? 'transports' : 'bookings');
})
.catch(() => {
// An entry decided meanwhile has nothing to prefill; the trip simply stays open.
});
}, [requested, loaded, setSearchParams, startImportReview]);
}
@@ -9,6 +9,7 @@ import { LLM_PHOTO_EXTENSIONS } from '@trek/shared'
import { useBackgroundTasksStore } from '../../store/backgroundTasksStore'
import { saveImportFiles } from '../../db/offlineDb'
import { isEffectivelyOffline } from '../../sync/networkMode'
import TripMailForward from '../MailIngest/TripMailForward'
interface BookingImportModalProps {
isOpen: boolean
@@ -209,6 +210,9 @@ export default function BookingImportModal({ isOpen, onClose, tripId, kind }: Bo
{error}
</div>
)}
{/* The other way in: forward the booking mail to the trip's own address. */}
<TripMailForward tripId={tripId} />
</div>
{/* Footer */}
@@ -15,7 +15,7 @@ import { formatMoney } from '../../../utils/formatters'
import { parseMeta, displayTitle, type CostTotal } from './bookingsModel'
import type { BookingFacts } from './bookingFacts'
import {
AirTrailPill, BOX, Block, Field, FileRows, ReviewPill, RoundAction, RouteBox, StatusDot, TravelerChips, TypeChip, WhenFields,
AirTrailPill, MailPill, BOX, Block, Field, FileRows, ReviewPill, RoundAction, RouteBox, StatusDot, TravelerChips, TypeChip, WhenFields,
fs, toneOf, toneTint,
} from './bookingParts'
import { TransitLegs, transitSummary } from './transitParts'
@@ -66,6 +66,7 @@ export default function BookingCard(p: BookingCardProps) {
{!!r.needs_review && <ReviewPill />}
</span>
<AirTrailPill r={r} />
<MailPill r={r} />
{p.canEdit && <RoundAction label={t('common.edit')} onClick={p.onEdit}><Pencil size={12} strokeWidth={2} /></RoundAction>}
{p.canEdit && <RoundAction label={t('common.delete')} onClick={p.onDelete} danger><Trash2 size={12} strokeWidth={2} /></RoundAction>}
</div>
@@ -21,7 +21,7 @@ import { copyText } from '../../../utils/clipboard'
import { fmtTransitDuration } from '../transitDisplay'
import { parseMeta, displayTitle } from './bookingsModel'
import { stayStats, type BookingFacts } from './bookingFacts'
import { AirTrailPill, BOX, Eyebrow, Field, FileRows, ReviewPill, TravelerChips, fs, toneOf } from './bookingParts'
import { AirTrailPill, MailPill, BOX, Eyebrow, Field, FileRows, ReviewPill, TravelerChips, fs, toneOf } from './bookingParts'
import { TransitLegs, transitSummary } from './transitParts'
import { BookingDialogHeader, StatusPill, TypePill } from './BookingDialogShell'
import { DeleteButton, DialogButton, DialogFooter, DialogSection as Section, DialogShell, FooterSpacer, PILL } from '../../shared/DialogShell'
@@ -145,6 +145,7 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) {
)}
{!!r.needs_review && <ReviewPill pill />}
<AirTrailPill r={r} pill />
<MailPill r={r} pill />
{r.confirmation_number && (
// The copy button rides in the pill's padding (-my-1), so this pill is as tall as its neighbours.
<span className={`${PILL} gap-1 pe-1`}>
@@ -7,7 +7,7 @@ import { formatMoney } from '../../../utils/formatters'
import { TransitLegChips } from '../transitDisplay'
import { displayTitle, parseMeta, type BookingGroup, type CostTotal } from './bookingsModel'
import type { BookingFacts } from './bookingFacts'
import { AirTrailPill, CountPill, EYEBROW, ReviewPill, RoundAction, StatusDot, TravelerStack, TypeTile, fs } from './bookingParts'
import { AirTrailPill, CountPill, MailPill, EYEBROW, ReviewPill, RoundAction, StatusDot, TravelerStack, TypeTile, fs } from './bookingParts'
export interface BookingsListProps {
groups: BookingGroup[]
@@ -102,6 +102,7 @@ function Row({ r, p, facts, files, costs, t, locale }: {
<span className="truncate font-semibold text-content" style={fs(13.5, 'body')}>{displayTitle(r)}</span>
{!!r.needs_review && <ReviewPill />}
<AirTrailPill r={r} />
<MailPill r={r} />
</div>
{transit ? (
<div className="mt-1"><TransitLegChips legs={Array.isArray(meta.transit?.legs) ? meta.transit.legs : []} size="sm" t={t} /></div>
@@ -1,5 +1,5 @@
import type { CSSProperties, ReactNode } from 'react'
import { AlertCircle, ChevronDown, ChevronUp, Download, FileText, Plane } from 'lucide-react'
import { AlertCircle, ChevronDown, ChevronUp, Download, FileText, Mail, Plane } from 'lucide-react'
import type { Reservation, TripFile } from '../../../types'
import type { ReservationTraveler } from '@trek/shared'
import { useTranslation } from '../../../i18n'
@@ -190,6 +190,27 @@ export function ReviewPill({ pill = false }: { pill?: boolean }) {
* The AirTrail link of a booking. A multi-leg import is detached from sync by
* design (#1535), which is not the same as a flight removed upstream (#1646).
*/
/** Added from a forwarded booking mail (mail-ingest): said quietly, so the person knows where it came from. */
export function MailPill({ r, pill = false }: { r: Reservation; pill?: boolean }) {
const { t } = useTranslation()
if (r.external_source !== 'mail') return null
return (
<Tooltip label={t('mailInbox.fromMailHint')}>
{pill ? (
<span className={PILL} style={fs(12, 'body')}>
<Mail size={13} strokeWidth={2.2} className="text-content-faint" />
{t('mailInbox.fromMail')}
</span>
) : (
<span className="inline-flex flex-none items-center gap-1 rounded-full bg-surface-tertiary px-2 py-[2px] font-geist font-bold uppercase tracking-[.03em] text-content-faint" style={fs(9)}>
<Mail size={10} />
{t('mailInbox.fromMail')}
</span>
)}
</Tooltip>
)
}
export function AirTrailPill({ r, pill = false }: { r: Reservation; pill?: boolean }) {
const { t } = useTranslation()
if (r.external_source !== 'airtrail') return null
@@ -6,6 +6,7 @@ import { useToast } from '../shared/Toast'
import { Trash2, Copy, Terminal, Plus, Check, Key, KeyRound, ChevronRight, RefreshCw, AlertTriangle, Link2 } from 'lucide-react'
import PhotoProvidersSection from './PhotoProvidersSection'
import AirTrailConnectionSection from './AirTrailConnectionSection'
import MailImportSection from './MailImportSection'
import DawarichConnectionSection from './DawarichConnectionSection'
import LlmConnectionSection from './LlmConnectionSection'
import AiConnectionSection from './ai/AiConnectionSection'
@@ -28,6 +29,8 @@ export default function IntegrationsTab(): React.ReactElement {
const demoLocked = useDemoAccountLock()
return (
<>
{/* Forwarded booking mails: hides itself where this server or plan has no import. */}
<MailImportSection />
{/* Immich, Synology Photos and AirTrail all connect to a server the reader
runs themselves. On a managed install there is none, and every one of
these would ask for an address that cannot be reached from here. */}
@@ -0,0 +1,140 @@
import { useRef, type ReactElement } from 'react';
import { ChevronRight, Copy, FileUp, Inbox, Loader2, Mail, RefreshCw } from 'lucide-react';
import { useTranslation } from '../../i18n';
import { useMailImportSettings } from '../MailIngest/useMailImportSettings';
import { openMailInbox } from '../MailIngest/mailInboxOpener';
import { Tooltip } from '../shared/Tooltip';
import Section from './Section';
import ToggleSwitch from './ToggleSwitch';
import { SETTINGS_BUTTON, SETTINGS_ICON_BUTTON, SettingRow, SettingRows, SettingsHint, StatusPill } from './settingsKit';
/**
* Settings → Integrations → Booking mail import: the person's forwarding
* address to copy, how to forward automatically, the switches (import on,
* AI reading, add on its own) and an .eml upload for a mail already on disk.
* Nothing where the import is not available on this server or plan.
*/
export default function MailImportSection(): ReactElement | null {
const { t } = useTranslation();
const s = useMailImportSettings();
const file = useRef<HTMLInputElement>(null);
if (!s.settings) return null;
const { address, prefs, ai_available: aiAvailable, pending } = s.settings;
return (
<Section
title={t('mailInbox.settings.title')}
icon={Mail}
badge={
<StatusPill tone={prefs.enabled ? 'success' : 'neutral'} icon={<span className="h-1.5 w-1.5 rounded-full bg-current" />}>
{prefs.enabled ? t('mailInbox.settings.on') : t('mailInbox.settings.off')}
</StatusPill>
}
>
{address && prefs.enabled && (
<div className="flex flex-col gap-2">
<div className="text-caption font-semibold uppercase tracking-[0.06em] text-content-faint">
{t('mailInbox.settings.yourAddress')}
</div>
<div className="flex min-w-0 items-center gap-2">
<code
dir="ltr"
className="min-w-0 flex-1 truncate rounded-lg bg-surface-tertiary px-3 py-2 font-geist text-body text-content"
>
{address.address}
</code>
<Tooltip label={t('mailInbox.settings.copy')}>
<button type="button" onClick={() => void s.copyAddress()} aria-label={t('mailInbox.settings.copy')} className={SETTINGS_ICON_BUTTON}>
<Copy size={14} strokeWidth={2} />
</button>
</Tooltip>
<Tooltip label={s.renewArmed ? t('mailInbox.settings.renewConfirm') : t('mailInbox.settings.renew')}>
<button
type="button"
onClick={() => void s.renew()}
disabled={s.renewing}
aria-label={s.renewArmed ? t('mailInbox.settings.renewConfirm') : t('mailInbox.settings.renew')}
className={`${SETTINGS_ICON_BUTTON} ${s.renewArmed ? 'text-warning ring-warning' : ''}`}
>
<RefreshCw size={14} strokeWidth={2} className={s.renewing ? 'animate-spin' : ''} />
</button>
</Tooltip>
</div>
<SettingsHint>{t('mailInbox.settings.addressHint')}</SettingsHint>
<details className="group rounded-lg bg-surface-tertiary px-3 py-2 text-body text-content-secondary">
<summary className="flex cursor-pointer list-none items-center gap-1.5 font-medium text-content">
<ChevronRight size={14} strokeWidth={2} className="transition-transform group-open:rotate-90 rtl:-scale-x-100" />
{t('mailInbox.settings.howTo')}
</summary>
<ul className="mt-2 flex list-disc flex-col gap-1.5 ps-5 text-caption">
<li>{t('mailInbox.settings.howToGmail')}</li>
<li>{t('mailInbox.settings.howToOutlook')}</li>
<li>{t('mailInbox.settings.howToManual')}</li>
</ul>
</details>
</div>
)}
<SettingRows>
<SettingRow
label={t('mailInbox.settings.enabled')}
hint={t('mailInbox.settings.enabledHint')}
control={<ToggleSwitch on={prefs.enabled} disabled={s.saving !== null} onToggle={() => void s.toggle('enabled')} label={t('mailInbox.settings.enabled')} />}
/>
<SettingRow
label={t('mailInbox.settings.ai')}
hint={aiAvailable ? t('mailInbox.settings.aiHint') : t('mailInbox.settings.aiUnavailable')}
dimmed={!prefs.enabled}
control={
<ToggleSwitch
on={prefs.ai_enabled && aiAvailable}
disabled={!prefs.enabled || !aiAvailable || s.saving !== null}
onToggle={() => void s.toggle('ai_enabled')}
label={t('mailInbox.settings.ai')}
/>
}
/>
<SettingRow
label={t('mailInbox.settings.autoAdd')}
hint={t('mailInbox.settings.autoAddHint')}
dimmed={!prefs.enabled}
control={
<ToggleSwitch
on={prefs.auto_add}
disabled={!prefs.enabled || s.saving !== null}
onToggle={() => void s.toggle('auto_add')}
label={t('mailInbox.settings.autoAdd')}
/>
}
/>
</SettingRows>
{prefs.enabled && (
<div className="flex flex-wrap items-center gap-2 text-body">
<button type="button" onClick={openMailInbox} className={SETTINGS_BUTTON}>
<Inbox size={14} strokeWidth={2.2} />
{t('mailInbox.title')}
{pending > 0 && <span className="rounded-full bg-accent px-1.5 text-caption font-semibold text-accent-text">{pending}</span>}
</button>
<button type="button" onClick={() => file.current?.click()} disabled={s.uploading} className={SETTINGS_BUTTON}>
{s.uploading ? <Loader2 size={14} strokeWidth={2.2} className="animate-spin" /> : <FileUp size={14} strokeWidth={2.2} />}
{t('mailInbox.settings.upload')}
</button>
<input
ref={file}
type="file"
accept=".eml,message/rfc822"
className="hidden"
onChange={(e) => {
const picked = e.target.files?.[0];
e.target.value = '';
if (picked) void s.upload(picked);
}}
/>
</div>
)}
<SettingsHint>{t('mailInbox.settings.privacy')}</SettingsHint>
</Section>
);
}
+2
View File
@@ -9,6 +9,7 @@ import MKeyboardHost from './keyboard/MKeyboardHost'
import MShellShortcuts from './keyboard/MShellShortcuts'
import MToastHost from './components/MToastHost'
import MEdgeBack from './components/MEdgeBack'
import MMailInboxHost from './screens/mail/MMailInboxHost'
import { useNativeCapabilities } from '../native/capabilities'
import { isNativeIos } from '../native/platform'
import { useWindowFold } from '../native/windowFold'
@@ -94,6 +95,7 @@ export default function MobileShell({ isPhone, children }: MobileShellProps) {
<ErrorBoundary boundaryId="chrome:m-bottom-nav" fallback={null}><MBottomNav /></ErrorBoundary>
)}
<ErrorBoundary boundaryId="chrome:m-toast" fallback={null}><MToastHost /></ErrorBoundary>
<ErrorBoundary boundaryId="chrome:m-mail-inbox" fallback={null}><MMailInboxHost /></ErrorBoundary>
{/* A hardware keyboard (an iPad's, mostly) gets the shortcuts an iPad app has. */}
<ErrorBoundary boundaryId="chrome:m-keyboard" fallback={null}>
<MKeyboardHost />
@@ -1,6 +1,6 @@
import React from 'react'
import { useNavigate } from 'react-router'
import { LogOut, Moon, Settings2, Shield, Sun, SunMoon } from 'lucide-react'
import { Inbox, LogOut, Moon, Settings2, Shield, Sun, SunMoon } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import { useTranslation } from '../../../i18n'
import { useAuthStore } from '../../../store/authStore'
@@ -8,6 +8,8 @@ import { useIsDark } from '../../../hooks/useIsDark'
import { useSettingsStore } from '../../../store/settingsStore'
import MDropdownPanel from '../../components/MDropdownPanel'
import MListRow from '../../components/MListRow'
import { useMailIngestStore } from '../../../store/mailIngestStore'
import { openMailInbox } from '../../../components/MailIngest/mailInboxOpener'
type ThemeMode = 'dark' | 'light' | 'auto'
@@ -46,6 +48,10 @@ export default function MUserMenu({ open, onClose }: MUserMenuProps): React.Reac
const dark = useIsDark()
const darkMode = useSettingsStore(s => s.settings.dark_mode)
const updateSetting = useSettingsStore(s => s.updateSetting)
// The inbox of bookings from forwarded mails, only where the import is on for this person.
const mailImport = useMailIngestStore(s => s.settings)
const mailPending = useMailIngestStore(s => s.pending)
const mailImportOn = !!mailImport?.available && mailImport.prefs.enabled
const mode = resolveMode(darkMode)
const ThemeIcon = THEME_ICON[mode]
@@ -80,6 +86,14 @@ export default function MUserMenu({ open, onClose }: MUserMenuProps): React.Reac
</div>
</div>
<MListRow icon={Settings2} label={t('nav.bottomSettings')} onClick={() => go('/settings')} />
{mailImportOn && (
<MListRow
icon={Inbox}
label={t('mailInbox.title')}
onClick={() => { onClose(); openMailInbox() }}
trailing={mailPending > 0 ? <span className="flex-none rounded-full bg-[color:var(--m-act)] px-[7px] font-geist text-caption font-bold text-[color:var(--m-actfg)]">{mailPending}</span> : undefined}
/>
)}
{user?.role === 'admin' && (
<MListRow icon={Shield} label={t('nav.bottomAdmin')} onClick={() => go('/admin')} />
)}
@@ -0,0 +1,18 @@
import { useEffect, type ReactElement } from 'react';
import { useAuthStore } from '../../../store/authStore';
import { useMailIngestStore } from '../../../store/mailIngestStore';
import MMailInboxSheet from './MMailInboxSheet';
/**
* The phone shell's one inbox of bookings from forwarded mails: reads the
* person's import settings once they are signed in (the user menu's badge
* needs them) and mounts the sheet only where the import is on.
*/
export default function MMailInboxHost(): ReactElement | null {
const userId = useAuthStore((s) => s.user?.id);
const settings = useMailIngestStore((s) => s.settings);
useEffect(() => {
if (userId) void useMailIngestStore.getState().loadSettings();
}, [userId]);
return settings?.available && settings.prefs.enabled ? <MMailInboxSheet /> : null;
}
@@ -0,0 +1,211 @@
import type { ReactElement } from 'react';
import { ChevronLeft, Copy, FilePlus2, FileText, Inbox, Mail, PencilLine, Plus, Sparkles, Trash2 } from 'lucide-react';
import type { MailIngestInboxEntry } from '@trek/shared';
import { useTranslation } from '../../../i18n';
import { copyText } from '../../../utils/clipboard';
import { formatDate } from '../../../utils/formatters';
import { RES_ICONS } from '../../../components/Planner/DayPlanSidebar.constants';
import { useToast } from '../../../components/shared/Toast';
import { entryDates, entryTitle, reasonText, type InboxAction } from '../../../components/MailIngest/mailInboxModel';
import { useMailInbox } from '../../../components/MailIngest/useMailInbox';
import MSheet from '../../components/MSheet';
import { INNER_CLS, TileHeader } from '../trip/sheets/MTripSheetUi';
const ROUND = 'grid h-9 w-9 flex-none place-items-center rounded-full bg-[color:var(--m-ic)] text-m-ink disabled:opacity-50';
function icon(action: InboxAction): ReactElement {
switch (action) {
case 'add':
case 'choose':
return <Plus size={15} strokeWidth={2.2} />;
case 'file':
return <FilePlus2 size={15} strokeWidth={2} />;
case 'manual':
return <PencilLine size={15} strokeWidth={2} />;
case 'readAi':
return <Sparkles size={15} strokeWidth={2} />;
case 'discard':
return <Trash2 size={15} strokeWidth={2} />;
}
}
function label(action: InboxAction, t: (key: string) => string): string {
switch (action) {
case 'add':
return t('mailInbox.action.add');
case 'choose':
return t('mailInbox.action.choose');
case 'file':
return t('mailInbox.action.file');
case 'manual':
return t('mailInbox.action.manual');
case 'readAi':
return t('mailInbox.action.readAi');
case 'discard':
return t('mailInbox.action.discard');
}
}
function Entry({ entry, inbox }: { entry: MailIngestInboxEntry; inbox: ReturnType<typeof useMailInbox> }) {
const { t, locale } = useTranslation();
const toast = useToast();
const dates = entryDates(entry);
const reason = entry.reason ?? entry.message.reason;
const Icon = entry.item ? RES_ICONS[entry.item.type as keyof typeof RES_ICONS] || Mail : Mail;
const [primary, ...rest] = inbox.actionsOf(entry);
const busy = inbox.busy === entry.id;
const code = entry.message.forwarding_code;
return (
<li className={`rounded-[16px] px-3 py-[11px] ${INNER_CLS}`}>
<div className="flex items-start gap-[10px]">
<span className="grid h-9 w-9 flex-none place-items-center rounded-[11px] bg-[color:var(--m-ic)] text-m-muted">
<Icon size={16} strokeWidth={2} />
</span>
<div className="min-w-0 flex-1">
<div dir="auto" className="truncate text-body font-semibold text-m-ink">{entryTitle(entry) ?? t('mailInbox.untitled')}</div>
{dates && (
<div className="font-geist text-caption tabular-nums text-m-muted">
{formatDate(dates.start, locale)}
{dates.end ? ` → ${formatDate(dates.end, locale)}` : ''}
</div>
)}
{reason && <div className="mt-[2px] text-caption" style={{ color: 'var(--m-st-pending)' }}>{reasonText(reason, t)}</div>}
{entry.suggested_trip && (
<span className="mt-[6px] inline-block max-w-full truncate rounded-full bg-[color:var(--m-ic)] px-[9px] py-[2px] text-caption font-medium text-m-muted">
{entry.suggested_trip.title}
</span>
)}
</div>
</div>
{code && (
<div className="mt-[10px] flex items-center gap-2">
<code dir="ltr" className="min-w-0 flex-1 rounded-[12px] bg-[color:var(--m-ic)] px-3 py-[8px] text-center font-geist text-subtitle font-bold tracking-[0.1em] text-m-ink">
{code}
</code>
<button
type="button"
aria-label={t('mailInbox.settings.copy')}
className={ROUND}
onClick={async () => {
if (await copyText(code)) toast.success(t('common.copied'));
}}
>
<Copy size={15} strokeWidth={2} />
</button>
</div>
)}
<div className="mt-[10px] flex items-center gap-[7px]">
<button type="button" aria-label={t('mailInbox.showMail')} className={ROUND} onClick={() => inbox.showMail(entry)}>
<FileText size={15} strokeWidth={2} />
</button>
{rest.map((action) => (
<button
key={action}
type="button"
aria-label={label(action, t)}
disabled={busy}
onClick={() => inbox.perform(entry, action)}
className={ROUND}
style={action === 'discard' ? { color: 'var(--m-st-danger)' } : undefined}
>
{icon(action)}
</button>
))}
{primary && (
<button
type="button"
disabled={busy}
onClick={() => inbox.perform(entry, primary)}
aria-label={label(primary, t)}
className={
primary === 'discard'
? `${ROUND} ms-auto`
: 'ms-auto inline-flex h-9 items-center gap-[6px] rounded-full bg-[color:var(--m-act)] px-[14px] text-caption font-bold text-[color:var(--m-actfg)] disabled:opacity-50'
}
style={primary === 'discard' ? { color: 'var(--m-st-danger)' } : undefined}
>
{icon(primary)}
{primary !== 'discard' && label(primary, t)}
</button>
)}
</div>
</li>
);
}
/**
* The phone's inbox of bookings from forwarded mails, as a sheet: the same
* entries and ways out as the desktop dialog (useMailInbox), with icon actions
* and one worded main action per row. Picking a trip and reading the mail open
* as pages inside the sheet, with a back button in the head.
*/
export default function MMailInboxSheet(): ReactElement {
const { t, locale } = useTranslation();
const inbox = useMailInbox();
const sub = inbox.pending > 0 ? t('mailInbox.pendingCount', { count: inbox.pending }) : t('mailInbox.empty');
const page = inbox.picking ? 'pick' : inbox.preview ? 'mail' : 'list';
const back = page === 'pick' ? inbox.cancelPick : page === 'mail' ? inbox.closePreview : null;
return (
<MSheet open={inbox.open} onClose={inbox.close} variant="card" material="glass" ariaLabel={t('mailInbox.title')}>
<div className="flex-none px-[18px] pt-4">
<TileHeader
icon={
back ? (
<button type="button" onClick={back} aria-label={t('common.back')} className="grid h-full w-full place-items-center">
<ChevronLeft size={19} strokeWidth={2} className="rtl:-scale-x-100" />
</button>
) : (
<Inbox size={19} strokeWidth={1.8} />
)
}
title={page === 'pick' ? t('mailInbox.pickTrip') : page === 'mail' ? (inbox.preview?.subject ?? t('mailInbox.untitled')) : t('mailInbox.title')}
sub={page === 'list' ? sub : undefined}
onClose={inbox.close}
closeLabel={t('common.close')}
/>
</div>
<div className="m-scroll-fade mt-2 min-h-0 flex-1 overflow-y-auto px-[18px] pb-[18px] pt-[10px]">
{page === 'pick' && (
<ul className="flex flex-col gap-[7px]">
{inbox.trips.map((trip) => (
<li key={trip.id}>
<button
type="button"
onClick={() => inbox.pick(trip.id)}
className={`flex w-full items-baseline justify-between gap-3 rounded-[14px] px-3 py-[11px] text-start ${INNER_CLS}`}
>
<span dir="auto" className="min-w-0 truncate text-body font-semibold text-m-ink">{trip.title}</span>
{trip.start_date && <span className="flex-none font-geist text-caption text-m-muted">{formatDate(trip.start_date, locale)}</span>}
</button>
</li>
))}
</ul>
)}
{page === 'mail' && inbox.preview && (
<pre className={`whitespace-pre-wrap rounded-[14px] p-3 font-geist text-caption text-m-muted ${INNER_CLS}`}>{inbox.preview.text}</pre>
)}
{page === 'list' && inbox.entries.length === 0 && (
<div className="flex flex-col items-center gap-2 py-10 text-center">
<Inbox size={28} strokeWidth={1.6} className="text-m-faint" />
<div className="text-body font-semibold text-m-ink">{t('mailInbox.empty')}</div>
<div className="max-w-[260px] text-caption text-m-muted">{t('mailInbox.emptyHint')}</div>
</div>
)}
{page === 'list' && inbox.entries.length > 0 && (
<ul className="flex flex-col gap-2">
{inbox.entries.map((entry) => <Entry key={entry.id} entry={entry} inbox={inbox} />)}
{inbox.hasMore && (
<li className="flex justify-center pt-1">
<button type="button" onClick={inbox.loadMore} disabled={inbox.loading} className="rounded-full bg-[color:var(--m-ic)] px-4 py-2 text-caption font-semibold text-m-ink">
{t('mailInbox.loadMore')}
</button>
</li>
)}
</ul>
)}
</div>
</MSheet>
);
}
@@ -0,0 +1,111 @@
import { useRef, type ReactElement } from 'react';
import { Copy, FileUp, Inbox, Mail, RefreshCw } from 'lucide-react';
import { useTranslation } from '../../../i18n';
import { useMailImportSettings } from '../../../components/MailIngest/useMailImportSettings';
import { openMailInbox } from '../../../components/MailIngest/mailInboxOpener';
import MToggle from '../../components/MToggle';
import { MSetButton, MSetCard, MSetEyebrow, MSetHint, MSetRow } from './MSettingsUi';
/**
* Phone twin of components/Settings/MailImportSection: the forwarding address
* with copy and renew as icons, the three switches as rows, the inbox and the
* .eml upload as buttons. Same logic (useMailImportSettings), the MSet* card
* system for the look. Nothing where the import is not available.
*/
export default function MMailImportSection(): ReactElement | null {
const { t } = useTranslation();
const s = useMailImportSettings();
const file = useRef<HTMLInputElement>(null);
if (!s.settings) return null;
const { address, prefs, ai_available: aiAvailable, pending } = s.settings;
const round =
'grid h-9 w-9 flex-none place-items-center rounded-full bg-[color:var(--m-ic)] text-m-ink disabled:opacity-50';
return (
<MSetCard title={t('mailInbox.settings.title')} icon={Mail} className="mt-3">
{address && prefs.enabled && (
<>
<MSetEyebrow className="mb-[6px]">{t('mailInbox.settings.yourAddress')}</MSetEyebrow>
<div className="flex min-w-0 items-center gap-2">
<code dir="ltr" className="min-w-0 flex-1 truncate rounded-[12px] bg-[color:var(--m-ic)] px-3 py-[9px] font-geist text-caption text-m-ink">
{address.address}
</code>
<button type="button" onClick={() => void s.copyAddress()} aria-label={t('mailInbox.settings.copy')} className={round}>
<Copy size={15} strokeWidth={2} />
</button>
<button
type="button"
onClick={() => void s.renew()}
disabled={s.renewing}
aria-label={s.renewArmed ? t('mailInbox.settings.renewConfirm') : t('mailInbox.settings.renew')}
className={round}
style={s.renewArmed ? { color: 'var(--m-st-pending)' } : undefined}
>
<RefreshCw size={15} strokeWidth={2} className={s.renewing ? 'animate-spin' : ''} />
</button>
</div>
{s.renewArmed && <MSetHint>{t('mailInbox.settings.renewConfirm')}</MSetHint>}
<MSetHint>{t('mailInbox.settings.addressHint')}</MSetHint>
</>
)}
<div className="mt-3">
<MSetRow
first
label={t('mailInbox.settings.enabled')}
sub={t('mailInbox.settings.enabledHint')}
trailing={<MToggle checked={prefs.enabled} disabled={s.saving !== null} onChange={() => void s.toggle('enabled')} ariaLabel={t('mailInbox.settings.enabled')} />}
/>
<MSetRow
label={t('mailInbox.settings.ai')}
sub={aiAvailable ? t('mailInbox.settings.aiHint') : t('mailInbox.settings.aiUnavailable')}
trailing={
<MToggle
checked={prefs.ai_enabled && aiAvailable}
disabled={!prefs.enabled || !aiAvailable || s.saving !== null}
onChange={() => void s.toggle('ai_enabled')}
ariaLabel={t('mailInbox.settings.ai')}
/>
}
/>
<MSetRow
label={t('mailInbox.settings.autoAdd')}
sub={t('mailInbox.settings.autoAddHint')}
trailing={
<MToggle
checked={prefs.auto_add}
disabled={!prefs.enabled || s.saving !== null}
onChange={() => void s.toggle('auto_add')}
ariaLabel={t('mailInbox.settings.autoAdd')}
/>
}
/>
</div>
{prefs.enabled && (
<div className="mt-3 flex flex-wrap items-center gap-2">
<MSetButton variant="ghost" onClick={openMailInbox}>
<Inbox size={14} /> {t('mailInbox.title')}
{pending > 0 && <span className="rounded-full bg-[color:var(--m-act)] px-[6px] font-geist text-caption font-bold text-[color:var(--m-actfg)]">{pending}</span>}
</MSetButton>
<MSetButton variant="ghost" onClick={() => file.current?.click()} disabled={s.uploading}>
<FileUp size={14} /> {t('mailInbox.settings.upload')}
</MSetButton>
<input
ref={file}
type="file"
accept=".eml,message/rfc822"
className="hidden"
onChange={(e) => {
const picked = e.target.files?.[0];
e.target.value = '';
if (picked) void s.upload(picked);
}}
/>
</div>
)}
<MSetHint>{t('mailInbox.settings.privacy')}</MSetHint>
</MSetCard>
);
}
@@ -1,5 +1,6 @@
import MPhotoProvidersSection from './MPhotoProvidersSection'
import MAirTrailConnectionSection from './MAirTrailConnectionSection'
import MMailImportSection from './MMailImportSection'
import MDawarichConnectionSection from './MDawarichConnectionSection'
import MLlmConnectionSection from './MLlmConnectionSection'
import MAiConnectionSection from './MAiConnectionSection'
@@ -17,6 +18,8 @@ export default function MSettingsIntegrations() {
return (
<>
{/* Forwarded booking mails: hides itself where this server or plan has no import. */}
<MMailImportSection />
{/* Immich, Synology Photos, AirTrail and Dawarich all reach a server the reader
runs themselves, which a managed install has no route to: the same gate the
desktop shell puts on them. */}
@@ -70,6 +70,7 @@ import { useIsWide } from '../../hooks/sizeClass'
import { useRoadtripVias } from '../../components/Roadtrip/useRoadtripVias'
import { TRIP_SPLASH_AFTER_MS } from '../../components/shared/useTripSplashBeats'
import { useFlightLiveSync } from '../../components/Planner/flightLive/useFlightLiveSync'
import { useMailPrefillLink } from '../../components/MailIngest/useMailPrefillLink'
/**
* The trip's roster from the server: the owner and the members. Null offline
@@ -651,6 +652,7 @@ export function useTripPlanner() {
editingReservation, setEditingReservation, setShowReservationModal,
editingTransport, setEditingTransport, setShowTransportModal, setTransportModalDayId,
})
useMailPrefillLink({ searchParams, setSearchParams, loaded: !isLoading && trip?.id === tripId, startImportReview })
// ── The plan's booking detail ───────────────────────────────────────────────
// A click on a booking in the plan shows it first; the editor is one Edit away.
+86
View File
@@ -0,0 +1,86 @@
// FE-STORE-MAILINGEST-001 to FE-STORE-MAILINGEST-004
import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('../api/mailIngest', () => ({
mailIngestApi: { settings: vi.fn(), inbox: vi.fn(), inboxCount: vi.fn(), act: vi.fn() },
}));
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => false) }));
import { mailIngestApi } from '../api/mailIngest';
import { useMailIngestStore } from './mailIngestStore';
const candidate = (id: number, resolution = 'pending') => ({
id,
message_id: 10 + id,
item: null,
source: null,
uncertain_fields: [],
checks: {},
suggested_trip: null,
suggested_new_trip: null,
resolution,
reason: 'not_a_booking',
resolved_trip_id: null,
reservation_ids: [],
file_ids: [],
created_at: '2026-06-01T10:00:00.000Z',
resolved_at: null,
undo_until: null,
});
const entry = (id: number) => ({
...candidate(id),
message: {
id: 10 + id,
transport: 'upload',
subject: null,
received_at: '2026-06-01T09:59:00.000Z',
status: 'processed',
reason: null,
hints: [],
ai_used: false,
trip_id: null,
attachments: [],
forwarding_code: null,
},
});
beforeEach(() => {
useMailIngestStore.setState({ settings: null, entries: [], nextBefore: null, pending: 0, loadingInbox: false });
vi.mocked(mailIngestApi.inbox).mockReset();
vi.mocked(mailIngestApi.act).mockReset();
});
describe('mailIngestStore', () => {
it('FE-STORE-MAILINGEST-001: reads the open entries and the count', async () => {
vi.mocked(mailIngestApi.inbox).mockResolvedValue({ entries: [entry(1), entry(2)], pending: 2, next_before: null });
await useMailIngestStore.getState().loadInbox();
expect(useMailIngestStore.getState().entries.map((e) => e.id)).toEqual([1, 2]);
expect(useMailIngestStore.getState().pending).toBe(2);
});
it('FE-STORE-MAILINGEST-002: a further page is appended, a malformed answer is ignored', async () => {
vi.mocked(mailIngestApi.inbox).mockResolvedValueOnce({ entries: [entry(1)], pending: 2, next_before: 1 });
await useMailIngestStore.getState().loadInbox();
vi.mocked(mailIngestApi.inbox).mockResolvedValueOnce({ entries: [entry(2)], pending: 2, next_before: null });
await useMailIngestStore.getState().loadInbox(true);
vi.mocked(mailIngestApi.inbox).mockResolvedValueOnce({ nope: true });
await useMailIngestStore.getState().loadInbox(true);
expect(useMailIngestStore.getState().entries.map((e) => e.id)).toEqual([1, 2]);
});
it('FE-STORE-MAILINGEST-003: a decided entry leaves the list and the count', async () => {
useMailIngestStore.setState({ entries: [entry(1), entry(2)] as never, pending: 2 });
vi.mocked(mailIngestApi.act).mockResolvedValue({ candidate: candidate(1, 'discarded') });
await useMailIngestStore.getState().act(1, 'discard');
expect(useMailIngestStore.getState().entries.map((e) => e.id)).toEqual([2]);
expect(useMailIngestStore.getState().pending).toBe(1);
});
it('FE-STORE-MAILINGEST-004: an entry still open after an action stays, updated', async () => {
useMailIngestStore.setState({ entries: [entry(1)] as never, pending: 1 });
vi.mocked(mailIngestApi.act).mockResolvedValue({ candidate: { ...candidate(1), reason: 'ai_provider_error' } });
await useMailIngestStore.getState().act(1, 'read-ai');
expect(useMailIngestStore.getState().entries[0].reason).toBe('ai_provider_error');
expect(useMailIngestStore.getState().pending).toBe(1);
});
});
+86
View File
@@ -0,0 +1,86 @@
import {
mailIngestCandidateResponseSchema,
mailIngestInboxCountResponseSchema,
mailIngestInboxResponseSchema,
mailIngestSettingsResponseSchema,
type MailIngestCandidate,
type MailIngestInboxEntry,
type MailIngestSettingsResponse,
} from '@trek/shared';
import { create } from 'zustand';
import { mailIngestApi, type MailIngestAction } from '../api/mailIngest';
import { isEffectivelyOffline } from '../sync/networkMode';
/**
* The booking mail import as the person sees it: their settings and address,
* and the inbox of bookings that wait for them. Online only on purpose: every
* action asks the server to decide (which trip, whether it is a duplicate), so
* there is nothing an offline copy could do. The pending count drives the badge
* on the menu entry, on the desktop and on the phone alike.
*/
interface MailIngestState {
settings: MailIngestSettingsResponse | null;
entries: MailIngestInboxEntry[];
nextBefore: number | null;
pending: number;
loadingInbox: boolean;
loadSettings: () => Promise<void>;
setSettings: (settings: MailIngestSettingsResponse) => void;
loadCount: () => Promise<void>;
loadInbox: (more?: boolean) => Promise<void>;
/** Runs an action on an entry; the entry leaves the open list once it is decided. */
act: (candidateId: number, action: MailIngestAction, body?: Record<string, unknown>) => Promise<MailIngestCandidate>;
}
const OPEN = new Set(['pending']);
export const useMailIngestStore = create<MailIngestState>((set, get) => ({
settings: null,
entries: [],
nextBefore: null,
pending: 0,
loadingInbox: false,
loadSettings: async () => {
if (isEffectivelyOffline()) return;
const parsed = mailIngestSettingsResponseSchema.safeParse(await mailIngestApi.settings().catch(() => null));
if (parsed.success) set({ settings: parsed.data, pending: parsed.data.pending });
},
setSettings: (settings) => set({ settings, pending: settings.pending }),
loadCount: async () => {
if (isEffectivelyOffline()) return;
const parsed = mailIngestInboxCountResponseSchema.safeParse(await mailIngestApi.inboxCount().catch(() => null));
if (parsed.success) set({ pending: parsed.data.pending });
},
loadInbox: async (more = false) => {
if (isEffectivelyOffline() || get().loadingInbox) return;
set({ loadingInbox: true });
try {
const before = more ? (get().nextBefore ?? undefined) : undefined;
const parsed = mailIngestInboxResponseSchema.safeParse(await mailIngestApi.inbox({ status: 'open', before }));
if (!parsed.success) return;
const { entries, pending, next_before } = parsed.data;
set((state) => ({ entries: more ? [...state.entries, ...entries] : entries, pending, nextBefore: next_before }));
} catch {
// The inbox stays as it was; the next open reads it again.
} finally {
set({ loadingInbox: false });
}
},
act: async (candidateId, action, body = {}) => {
const { candidate } = mailIngestCandidateResponseSchema.parse(await mailIngestApi.act(candidateId, action, body));
set((state) => {
const stillOpen = OPEN.has(candidate.resolution);
const entries = state.entries.flatMap((entry) =>
entry.id !== candidate.id ? [entry] : stillOpen ? [{ ...entry, ...candidate }] : [],
);
const removed = state.entries.length - entries.length;
return { entries, pending: Math.max(0, state.pending - removed) };
});
return candidate;
},
}));