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
+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>
);
}