fix(mail-ingest): type errors and formatting after joining the flight work

The cron callbacks hand back nothing; the cursor's lookup is findCursor so it
no longer shadows the base repository's find(); the draft's suggested trip
uses the shared contract's type; endpoints spell out their optional columns;
the relay page's running count is typed. Prettier over every new file outside
the generated entities.
This commit is contained in:
Maurice
2026-11-13 18:03:14 +01:00
parent b19bd8e709
commit bd11cd347d
65 changed files with 440 additions and 195 deletions
@@ -1,11 +1,18 @@
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 { Copy, FilePlus2, FileText, Inbox, Loader2, Mail, PencilLine, Plus, Sparkles, Trash2 } from 'lucide-react';
import { useId, type ReactElement } from 'react';
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 {
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';
@@ -46,7 +53,9 @@ function Entry({ entry, inbox }: { entry: MailIngestInboxEntry; inbox: ReturnTyp
</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>
<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)}
@@ -57,7 +66,10 @@ function Entry({ entry, inbox }: { entry: MailIngestInboxEntry; inbox: ReturnTyp
{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
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
@@ -71,9 +83,15 @@ function Entry({ entry, inbox }: { entry: MailIngestInboxEntry; inbox: ReturnTyp
)}
<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>
<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">
<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>
@@ -83,22 +101,50 @@ function Entry({ entry, inbox }: { entry: MailIngestInboxEntry; inbox: ReturnTyp
{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)} />;
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)}>
<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')} />
<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 }) {
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">
@@ -106,9 +152,19 @@ function TripPicker({ trips, onPick, onCancel }: { trips: InboxTrip[]; onPick: (
<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
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>
))}
@@ -135,7 +191,11 @@ export default function MailInboxDialog(): ReactElement | null {
const header = (
<DialogHeader
tile={<DialogTile><Inbox size={18} strokeWidth={2} /></DialogTile>}
tile={
<DialogTile>
<Inbox size={18} strokeWidth={2} />
</DialogTile>
}
tint={NEUTRAL_TINT}
labelId={titleId}
onClose={inbox.close}
@@ -145,13 +205,22 @@ export default function MailInboxDialog(): ReactElement | null {
);
return (
<DialogShell onClose={inbox.close} labelledBy={titleId} width="editor" align="top" header={header} blocked={!!inbox.picking}>
<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>
<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>
@@ -164,10 +233,14 @@ export default function MailInboxDialog(): ReactElement | null {
</div>
) : (
<ul className="flex flex-col gap-2">
{inbox.entries.map((entry) => <Entry key={entry.id} entry={entry} inbox={inbox} />)}
{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>
<DialogButton onClick={inbox.loadMore} disabled={inbox.loading}>
{t('mailInbox.loadMore')}
</DialogButton>
</li>
)}
</ul>
@@ -1,6 +1,6 @@
import { mailIngestAddressResponseSchema, type MailIngestAddress } from '@trek/shared';
import { useEffect, useState, type ReactElement } from 'react';
import { Copy, Mail, Plus } from 'lucide-react';
import { useEffect, useState, type ReactElement } from 'react';
import { mailIngestApi } from '../../api/mailIngest';
import { useTranslation } from '../../i18n';
import { useMailIngestStore } from '../../store/mailIngestStore';
@@ -68,7 +68,10 @@ export default function TripMailForward({ tripId }: { tripId: number }): ReactEl
<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">
<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
@@ -5,7 +5,10 @@ import { describe, expect, it } from 'vitest';
import { actionsOf, canUndo, entryDates, entryTitle, reasonText } from './mailInboxModel';
function entry(over: Partial<MailIngestInboxEntry> = {}, message: Partial<MailIngestInboxEntry['message']> = {}): MailIngestInboxEntry {
function entry(
over: Partial<MailIngestInboxEntry> = {},
message: Partial<MailIngestInboxEntry['message']> = {}
): MailIngestInboxEntry {
return {
id: 1,
message_id: 10,
@@ -57,13 +60,21 @@ describe('mailInboxModel', () => {
});
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 }] });
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']);
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', () => {
@@ -11,7 +11,14 @@ import type { MailIngestInboxEntry, MailIngestReason } from '@trek/shared';
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']);
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']);
@@ -119,5 +126,9 @@ export function entryDates(entry: MailIngestInboxEntry): { start: string; end: s
/** 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;
return (
(entry.resolution === 'applied' || entry.resolution === 'auto_applied') &&
!!entry.undo_until &&
Date.parse(entry.undo_until) > now
);
}
@@ -38,7 +38,7 @@ export function useMailImportSettings() {
setSaving(key);
try {
const parsed = mailIngestSettingsResponseSchema.parse(
await mailIngestApi.updateSettings({ [key]: !settings.prefs[key] }),
await mailIngestApi.updateSettings({ [key]: !settings.prefs[key] })
);
setSettings(parsed);
} catch {
@@ -1,4 +1,8 @@
import { mailIngestMessagePreviewResponseSchema, type MailIngestInboxEntry, type MailIngestMessagePreviewResponse } from '@trek/shared';
import {
mailIngestMessagePreviewResponseSchema,
type MailIngestInboxEntry,
type MailIngestMessagePreviewResponse,
} from '@trek/shared';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { tripsApi } from '../../api/client';
@@ -6,8 +10,8 @@ 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';
import { closeMailInbox, useMailInboxOpen } from './mailInboxOpener';
export interface InboxTrip {
id: number;
@@ -32,7 +36,9 @@ export function useMailInbox() {
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 [picking, setPicking] = useState<{ entry: MailIngestInboxEntry; action: 'apply' | 'file' | 'manual' } | null>(
null
);
const [preview, setPreview] = useState<MailIngestMessagePreviewResponse | null>(null);
useEffect(() => {
@@ -41,11 +47,18 @@ export function useMailInbox() {
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 }))))
.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) => {
const run = async (
entry: MailIngestInboxEntry,
action: MailIngestAction,
body: Record<string, unknown>,
done: string
) => {
setBusy(entry.id);
try {
await act(entry.id, action, body);
@@ -65,7 +78,9 @@ export function useMailInbox() {
case 'choose':
return setPicking({ entry, action: 'apply' });
case 'file':
return tripId ? run(entry, 'file', { trip_id: tripId }, t('mailInbox.filed')) : setPicking({ entry, action: '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':
@@ -1,4 +1,8 @@
import { isTransportReservationType, mailIngestPrefillResponseSchema, type BookingImportPreviewItem } from '@trek/shared';
import {
isTransportReservationType,
mailIngestPrefillResponseSchema,
type BookingImportPreviewItem,
} from '@trek/shared';
import { useEffect, useRef } from 'react';
import type { SetURLSearchParams } from 'react-router';
import { mailIngestApi } from '../../api/mailIngest';
@@ -33,7 +37,7 @@ export function useMailPrefillLink({
next.delete('mailPrefill');
return next;
},
{ replace: true },
{ replace: true }
);
const id = Number(requested);
if (!Number.isInteger(id) || id <= 0) return;
@@ -1,12 +1,19 @@
import { useRef, type ReactElement } from 'react';
import { ChevronRight, Copy, FileUp, Inbox, Loader2, Mail, RefreshCw } from 'lucide-react';
import { useRef, type ReactElement } from 'react';
import { useTranslation } from '../../i18n';
import { useMailImportSettings } from '../MailIngest/useMailImportSettings';
import { openMailInbox } from '../MailIngest/mailInboxOpener';
import { useMailImportSettings } from '../MailIngest/useMailImportSettings';
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';
import {
SETTINGS_BUTTON,
SETTINGS_ICON_BUTTON,
SettingRow,
SettingRows,
SettingsHint,
StatusPill,
} from './settingsKit';
/**
* Settings → Integrations → Booking mail import: the person's forwarding
@@ -26,7 +33,10 @@ export default function MailImportSection(): ReactElement | null {
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" />}>
<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>
}
@@ -44,7 +54,12 @@ export default function MailImportSection(): ReactElement | null {
{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}>
<button
type="button"
onClick={() => void s.copyAddress()}
aria-label={t('mailInbox.settings.copy')}
className={SETTINGS_ICON_BUTTON}
>
<Copy size={14} strokeWidth={2} />
</button>
</Tooltip>
@@ -63,7 +78,11 @@ export default function MailImportSection(): ReactElement | null {
<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" />
<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">
@@ -79,7 +98,14 @@ export default function MailImportSection(): ReactElement | null {
<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')} />}
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')}
@@ -114,10 +140,23 @@ export default function MailImportSection(): ReactElement | null {
<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>}
{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} />}
<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