mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 21:11:14 +00:00
feat(mail-ingest): admin card, review mark, inbox events and links, translations
- Admin settings (desktop and phone, self-hosted only): the instance switch,
how mail arrives (IMAP or a signed webhook) with its fields, the address
template, the AI allowance per person and day, a connection test and the
status in counts. Changed fields only are saved; secrets stay masked.
- The review mark of an imported booking takes its mark off: the pill in the
desktop dialog and a row in the phone's transport sheet ('Looks right'),
through the ordinary booking update. Its hint no longer speaks of airports.
- The inbox follows mailInbox:changed and mailInbox:settings, and
?inbox=mail (the 'bookings waiting' notification) opens it.
- mailIngestRepo: the online-only path the views take, answers parsed
against the shared contracts.
- Dropped 'read with AI' and the unused mail-review contract: the server
reads a passing AI failure again on its own.
- mailInbox, mailAdmin and the new reservation, settings and notification
strings in all 28 locales; the pending notice is a plural group.
- The live flight line on the booking cards is one of the card's fields,
full width on the phone; the phone's live card keeps its map to the middle.
- Admin flight and mail cards sit in the left column.
This commit is contained in:
@@ -9,9 +9,17 @@ import apiClient from './client';
|
||||
*/
|
||||
const data = (response: { data: unknown }) => response.data;
|
||||
|
||||
export type MailIngestAction = 'apply' | 'move' | 'file' | 'undo' | 'discard' | 'read-ai';
|
||||
export type MailIngestAction = 'apply' | 'move' | 'file' | 'undo' | 'discard';
|
||||
|
||||
export const mailIngestApi = {
|
||||
// The admin's view: how the import runs, in counts only, and whether the transport reaches its mail now.
|
||||
adminStatus: (): Promise<unknown> => apiClient.get('/admin/mail-ingest/status').then(data),
|
||||
adminTest: (): Promise<unknown> => apiClient.post('/admin/mail-ingest/test', {}).then(data),
|
||||
/** The stored transport fields, passwords masked, from the admin's app settings. */
|
||||
adminSettings: (): Promise<unknown> => apiClient.get('/auth/app-settings').then(data),
|
||||
saveAdminSettings: (patch: Record<string, string | boolean>): Promise<unknown> =>
|
||||
apiClient.put('/auth/app-settings', patch).then(data),
|
||||
|
||||
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),
|
||||
@@ -32,9 +40,6 @@ export const mailIngestApi = {
|
||||
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);
|
||||
|
||||
@@ -23,6 +23,9 @@ export const HANDLED_OUTSIDE_TRIP_STORE = [
|
||||
'tours:visits',
|
||||
// store/flightLiveStore (watchFlightLive, mounted by useFlightLiveSync) merges live flight states.
|
||||
'flight:live',
|
||||
// store/mailIngestStore (watchMailInbox, mounted by Navbar and MMailInboxHost): the open count and the settings card.
|
||||
'mailInbox:changed',
|
||||
'mailInbox:settings',
|
||||
// Collab — Collab/MCollab components + useTripWebSocket's collabFileSync
|
||||
'collab:note:created',
|
||||
'collab:note:updated',
|
||||
@@ -161,9 +164,6 @@ export const HANDLED_OUTSIDE_TRIP_STORE = [
|
||||
export const IGNORED_WS_EVENTS: Partial<Record<TrekWsEventName, string>> = {
|
||||
'todo:assignees':
|
||||
'No screen shows who looks after a todo category (todoApi.getCategoryAssignees has no caller), so there is nothing to refresh.',
|
||||
// The mail import's inbox and settings card come with its client screens, which move these to their listener.
|
||||
'mailInbox:changed': 'No screen shows the mail inbox or its open count yet, so there is nothing to refresh.',
|
||||
'mailInbox:settings': 'No screen shows the mail import settings card yet, so there is nothing to read again.',
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
import { CheckCircle, Copy, Loader2, Mail, PlugZap, Save, XCircle } from 'lucide-react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
import { copyText } from '../../../utils/clipboard';
|
||||
import { relativeTime } from '../../../utils/relativeTime';
|
||||
import {
|
||||
SETTINGS_BUTTON,
|
||||
SETTINGS_BUTTON_PRIMARY,
|
||||
SettingRow,
|
||||
SettingRows,
|
||||
SettingsCard,
|
||||
SettingsHint,
|
||||
StatusPill,
|
||||
} from '../../Settings/settingsKit';
|
||||
import ToggleSwitch from '../../Settings/ToggleSwitch';
|
||||
import CustomSelect from '../../shared/CustomSelect';
|
||||
import { EditorField, GRID_2, INPUT, READONLY_BOX } from '../../shared/dialogParts';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
import {
|
||||
TRANSPORTS,
|
||||
problemText,
|
||||
statusFacts,
|
||||
transportLabel,
|
||||
type MailAdminForm,
|
||||
type MailAdminProblem,
|
||||
} from './mailIngestAdminModel';
|
||||
import { useMailIngestAdmin, type MailIngestAdmin } from './useMailIngestAdmin';
|
||||
|
||||
type T = TranslationFn;
|
||||
|
||||
/** The address a mail service posts to, shown so the admin can paste it into the sender's settings. */
|
||||
function InboundUrl({ t }: { t: T }) {
|
||||
const toast = useToast();
|
||||
const url = `${window.location.origin}/api/mail-ingest/inbound`;
|
||||
return (
|
||||
<EditorField label={t('mailAdmin.inboundUrl')} hint={t('mailAdmin.inboundUrlHint')}>
|
||||
<div className="flex gap-2">
|
||||
<span className={READONLY_BOX}>{url}</span>
|
||||
<button
|
||||
type="button"
|
||||
className={SETTINGS_BUTTON}
|
||||
aria-label={t('mailAdmin.copyUrl')}
|
||||
onClick={() => void copyText(url).then((ok) => (ok ? toast.success(t('common.copied')) : undefined))}
|
||||
>
|
||||
<Copy size={14} strokeWidth={2} />
|
||||
</button>
|
||||
</div>
|
||||
</EditorField>
|
||||
);
|
||||
}
|
||||
|
||||
interface FieldsProps {
|
||||
admin: MailIngestAdmin;
|
||||
form: MailAdminForm;
|
||||
t: T;
|
||||
error: (p: MailAdminProblem) => ReactNode;
|
||||
}
|
||||
|
||||
function ImapFields({ admin, form, t, error }: FieldsProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className={GRID_2}>
|
||||
<EditorField label={t('mailAdmin.imap.host')} htmlFor="mail-imap-host">
|
||||
<input
|
||||
id="mail-imap-host"
|
||||
className={INPUT}
|
||||
value={form.imap_host}
|
||||
placeholder="imap.example.com"
|
||||
onChange={(e) => admin.set('imap_host', e.target.value)}
|
||||
/>
|
||||
</EditorField>
|
||||
<div className={GRID_2}>
|
||||
<EditorField label={t('mailAdmin.imap.port')} htmlFor="mail-imap-port" error={error('portInvalid')}>
|
||||
<input
|
||||
id="mail-imap-port"
|
||||
className={INPUT}
|
||||
inputMode="numeric"
|
||||
value={form.imap_port}
|
||||
onChange={(e) => admin.set('imap_port', e.target.value)}
|
||||
/>
|
||||
</EditorField>
|
||||
<EditorField label={t('mailAdmin.imap.tls')}>
|
||||
<CustomSelect
|
||||
value={form.imap_tls}
|
||||
onChange={(value) => admin.set('imap_tls', value === 'starttls' ? 'starttls' : 'tls')}
|
||||
options={[
|
||||
{ value: 'tls', label: 'TLS' },
|
||||
{ value: 'starttls', label: 'STARTTLS' },
|
||||
]}
|
||||
/>
|
||||
</EditorField>
|
||||
</div>
|
||||
</div>
|
||||
<div className={GRID_2}>
|
||||
<EditorField label={t('mailAdmin.imap.user')} htmlFor="mail-imap-user">
|
||||
<input
|
||||
id="mail-imap-user"
|
||||
className={INPUT}
|
||||
autoComplete="off"
|
||||
value={form.imap_user}
|
||||
onChange={(e) => admin.set('imap_user', e.target.value)}
|
||||
/>
|
||||
</EditorField>
|
||||
<EditorField label={t('mailAdmin.imap.pass')} htmlFor="mail-imap-pass">
|
||||
<input
|
||||
id="mail-imap-pass"
|
||||
className={INPUT}
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={form.imap_pass}
|
||||
onChange={(e) => admin.set('imap_pass', e.target.value)}
|
||||
/>
|
||||
</EditorField>
|
||||
</div>
|
||||
<EditorField
|
||||
label={t('mailAdmin.imap.mailbox')}
|
||||
htmlFor="mail-imap-mailbox"
|
||||
hint={t('mailAdmin.imap.mailboxHint')}
|
||||
>
|
||||
<input
|
||||
id="mail-imap-mailbox"
|
||||
className={INPUT}
|
||||
value={form.imap_mailbox}
|
||||
onChange={(e) => admin.set('imap_mailbox', e.target.value)}
|
||||
/>
|
||||
</EditorField>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WebhookFields({ admin, form, t, error }: FieldsProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<EditorField
|
||||
label={t('mailAdmin.webhook.secret')}
|
||||
htmlFor="mail-webhook-secret"
|
||||
hint={t('mailAdmin.webhook.secretHint')}
|
||||
error={error('secretShort')}
|
||||
>
|
||||
<input
|
||||
id="mail-webhook-secret"
|
||||
className={INPUT}
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={form.webhook_secret}
|
||||
onChange={(e) => admin.set('webhook_secret', e.target.value)}
|
||||
/>
|
||||
</EditorField>
|
||||
<InboundUrl t={t} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** How the import runs, in counts only: no subject, sender or content of a mail is ever shown here. */
|
||||
function StatusBlock({ admin, t, locale }: { admin: MailIngestAdmin; t: T; locale: string }) {
|
||||
const status = admin.status;
|
||||
if (!status) return null;
|
||||
const facts = statusFacts(status);
|
||||
const lastRead = status.last_ok_at
|
||||
? relativeTime(Date.parse(status.last_ok_at), locale)
|
||||
: t('mailAdmin.status.never');
|
||||
return (
|
||||
<div className="flex flex-col gap-2 rounded-[12px] border border-edge-faint bg-surface-secondary px-3.5 py-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-caption font-semibold uppercase tracking-[0.08em] text-content-faint">
|
||||
{t('mailAdmin.status.title')}
|
||||
</span>
|
||||
<StatusPill tone={status.last_error ? 'warning' : 'neutral'}>
|
||||
{t('mailAdmin.status.lastRead', { time: lastRead })}
|
||||
</StatusPill>
|
||||
</div>
|
||||
<div className="grid grid-cols-4 gap-2 max-sm:grid-cols-2">
|
||||
{[
|
||||
{ label: t('mailAdmin.status.mails'), value: facts.mails },
|
||||
{ label: t('mailAdmin.status.added'), value: facts.added },
|
||||
{ label: t('mailAdmin.status.waiting'), value: facts.waiting },
|
||||
{ label: t('mailAdmin.status.failed'), value: facts.failed },
|
||||
].map((f) => (
|
||||
<div key={f.label} className="min-w-0">
|
||||
<div className="truncate text-caption text-content-faint">{f.label}</div>
|
||||
<div className="text-body font-semibold tabular-nums text-content">{f.value}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{status.last_error && <SettingsHint className="text-warning">{status.last_error}</SettingsHint>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TestResult({ admin, t }: { admin: MailIngestAdmin; t: T }) {
|
||||
if (!admin.test) return null;
|
||||
return admin.test.ok ? (
|
||||
<StatusPill tone="success" icon={<CheckCircle size={12} strokeWidth={2.2} />}>
|
||||
{t('mailAdmin.test.ok')}
|
||||
</StatusPill>
|
||||
) : (
|
||||
<StatusPill tone="danger" icon={<XCircle size={12} strokeWidth={2.2} />}>
|
||||
{admin.test.error ?? t('mailAdmin.test.failed')}
|
||||
</StatusPill>
|
||||
);
|
||||
}
|
||||
|
||||
/** Everything under the switch: how mail arrives, its fields, then save, test and the status. */
|
||||
function Setup({ admin, form, t, locale }: { admin: MailIngestAdmin; form: MailAdminForm; t: T; locale: string }) {
|
||||
const error = (problem: MailAdminProblem) => (admin.problems.includes(problem) ? problemText(problem, t) : undefined);
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className={GRID_2}>
|
||||
<EditorField label={t('mailAdmin.transport.label')}>
|
||||
<CustomSelect
|
||||
value={form.transport}
|
||||
onChange={(value) => admin.set('transport', TRANSPORTS.find((x) => x === value) ?? 'off')}
|
||||
options={TRANSPORTS.map((x) => ({ value: x, label: transportLabel(x, t) }))}
|
||||
/>
|
||||
</EditorField>
|
||||
<EditorField
|
||||
label={t('mailAdmin.aiDaily')}
|
||||
htmlFor="mail-ai-daily"
|
||||
hint={t('mailAdmin.aiDailyHint')}
|
||||
error={error('dailyInvalid')}
|
||||
>
|
||||
<input
|
||||
id="mail-ai-daily"
|
||||
className={INPUT}
|
||||
inputMode="numeric"
|
||||
value={form.ai_per_user_daily}
|
||||
onChange={(e) => admin.set('ai_per_user_daily', e.target.value)}
|
||||
/>
|
||||
</EditorField>
|
||||
</div>
|
||||
<EditorField
|
||||
label={t('mailAdmin.template')}
|
||||
htmlFor="mail-template"
|
||||
hint={t('mailAdmin.templateHint', { token: '{token}' })}
|
||||
error={error('templateToken')}
|
||||
>
|
||||
<input
|
||||
id="mail-template"
|
||||
className={INPUT}
|
||||
value={form.address_template}
|
||||
placeholder="trek+{token}@example.com"
|
||||
onChange={(e) => admin.set('address_template', e.target.value)}
|
||||
/>
|
||||
</EditorField>
|
||||
{form.transport === 'imap' && <ImapFields admin={admin} form={form} t={t} error={error} />}
|
||||
{form.transport === 'webhook' && <WebhookFields admin={admin} form={form} t={t} error={error} />}
|
||||
<SettingsHint>{t('mailAdmin.envHint')}</SettingsHint>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className={SETTINGS_BUTTON_PRIMARY}
|
||||
disabled={!admin.dirty || admin.problems.length > 0 || admin.saving}
|
||||
onClick={admin.save}
|
||||
>
|
||||
{admin.saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} strokeWidth={2} />}
|
||||
{t('common.save')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={SETTINGS_BUTTON}
|
||||
disabled={admin.testing || admin.dirty || form.transport === 'off'}
|
||||
onClick={admin.runTest}
|
||||
>
|
||||
{admin.testing ? <Loader2 size={14} className="animate-spin" /> : <PlugZap size={14} strokeWidth={2} />}
|
||||
{t('mailAdmin.test.run')}
|
||||
</button>
|
||||
<TestResult admin={admin} t={t} />
|
||||
</div>
|
||||
<StatusBlock admin={admin} t={t} locale={locale} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The booking mail import in the admin settings of a self-hosted install: the
|
||||
* instance switch, how mail arrives (IMAP or a signed webhook), the forwarding
|
||||
* address template, the AI allowance per person and day, a connection test and
|
||||
* the status in counts. Not shown on a managed install, where the operator
|
||||
* runs the TREK Cloud relay.
|
||||
*/
|
||||
export default function MailIngestAdminCard() {
|
||||
const { t, locale } = useTranslation();
|
||||
const admin = useMailIngestAdmin(true);
|
||||
return (
|
||||
<SettingsCard icon={Mail} title={t('mailAdmin.title')} hint={t('mailAdmin.hint')}>
|
||||
<SettingRows>
|
||||
<SettingRow
|
||||
label={t('mailAdmin.enabled')}
|
||||
hint={t('mailAdmin.enabledHint')}
|
||||
control={
|
||||
<ToggleSwitch
|
||||
on={admin.enabled}
|
||||
label={t('mailAdmin.enabled')}
|
||||
disabled={!admin.loaded}
|
||||
onToggle={() => admin.toggle(!admin.enabled)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SettingRows>
|
||||
{admin.enabled && admin.form && <Setup admin={admin} form={admin.form} t={t} locale={locale} />}
|
||||
</SettingsCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// FE-ADMIN-MAILINGEST-001 to FE-ADMIN-MAILINGEST-006
|
||||
import type { MailIngestAdminStatusResponse } from '@trek/shared';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
MASKED,
|
||||
TRANSPORTS,
|
||||
changesOf,
|
||||
enabledOf,
|
||||
fieldsOf,
|
||||
formOf,
|
||||
problemText,
|
||||
problemsOf,
|
||||
statusFacts,
|
||||
transportLabel,
|
||||
} from './mailIngestAdminModel';
|
||||
|
||||
const t = (key: string, params?: Record<string, string | number | null>) =>
|
||||
params ? `${key} ${JSON.stringify(params)}` : key;
|
||||
|
||||
describe('mailIngestAdminModel', () => {
|
||||
it('FE-ADMIN-MAILINGEST-001: reads the stored settings, and the defaults for what the server left out', () => {
|
||||
expect(formOf({})).toEqual({
|
||||
transport: 'off',
|
||||
address_template: '',
|
||||
imap_host: '',
|
||||
imap_port: '993',
|
||||
imap_tls: 'tls',
|
||||
imap_user: '',
|
||||
imap_pass: '',
|
||||
imap_mailbox: 'INBOX',
|
||||
webhook_secret: '',
|
||||
ai_per_user_daily: '10',
|
||||
});
|
||||
const form = formOf({
|
||||
mail_ingest_transport: 'imap',
|
||||
mail_ingest_imap_port: 143,
|
||||
mail_ingest_imap_tls: 'starttls',
|
||||
mail_ingest_imap_pass: MASKED,
|
||||
});
|
||||
expect(form).toMatchObject({ transport: 'imap', imap_port: '143', imap_tls: 'starttls', imap_pass: MASKED });
|
||||
// The Cloud relay is the operator's, never a choice in this form.
|
||||
expect(formOf({ mail_ingest_transport: 'cloud' }).transport).toBe('off');
|
||||
expect(enabledOf({ mail_ingest_enabled: 'true' })).toBe(true);
|
||||
expect(enabledOf({})).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-MAILINGEST-002: a save carries only what changed, trimmed, under the stored keys', () => {
|
||||
const saved = formOf({ mail_ingest_imap_pass: MASKED });
|
||||
expect(changesOf(saved, saved)).toEqual({});
|
||||
const edited = { ...saved, transport: 'imap' as const, imap_host: ' imap.example.com ' };
|
||||
expect(changesOf(edited, saved)).toEqual({
|
||||
mail_ingest_transport: 'imap',
|
||||
mail_ingest_imap_host: 'imap.example.com',
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-ADMIN-MAILINGEST-003: each transport shows only its own fields', () => {
|
||||
expect(fieldsOf('off')).toEqual([]);
|
||||
expect(fieldsOf('webhook')).toEqual(['webhook_secret']);
|
||||
expect(fieldsOf('imap')).toContain('imap_pass');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-MAILINGEST-004: what stops a save is found before the server answers', () => {
|
||||
const base = formOf({});
|
||||
expect(problemsOf(base)).toEqual([]);
|
||||
expect(problemsOf({ ...base, transport: 'webhook', webhook_secret: 'short' })).toEqual(['secretShort']);
|
||||
// A stored secret comes back masked, and an empty one switches the webhook off: neither is a problem.
|
||||
expect(problemsOf({ ...base, transport: 'webhook', webhook_secret: MASKED })).toEqual([]);
|
||||
expect(problemsOf({ ...base, transport: 'webhook', webhook_secret: '' })).toEqual([]);
|
||||
expect(problemsOf({ ...base, transport: 'imap', imap_port: '70000' })).toEqual(['portInvalid']);
|
||||
expect(problemsOf({ ...base, address_template: 'trek@example.com' })).toEqual(['templateToken']);
|
||||
expect(problemsOf({ ...base, ai_per_user_daily: '2.5' })).toEqual(['dailyInvalid']);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-MAILINGEST-005: the status card adds up the last day in counts', () => {
|
||||
const status: MailIngestAdminStatusResponse = {
|
||||
transport: 'imap',
|
||||
last_ok_at: null,
|
||||
last_error: null,
|
||||
lease_until: null,
|
||||
last_day: { by_status: { processed: 7, failed: 2, queued: 1 }, by_reason: {} },
|
||||
auto_applied: 5,
|
||||
undone: 0,
|
||||
ai_calls_today: 3,
|
||||
backlog: [2, 4],
|
||||
};
|
||||
expect(statusFacts(status)).toEqual({ mails: 10, added: 5, waiting: 6, failed: 2 });
|
||||
});
|
||||
|
||||
it('FE-ADMIN-MAILINGEST-006: every transport and problem has its words, {token} kept literal', () => {
|
||||
expect(TRANSPORTS.map((x) => transportLabel(x, t))).toEqual([
|
||||
'mailAdmin.transport.off',
|
||||
'mailAdmin.transport.imap',
|
||||
'mailAdmin.transport.webhook',
|
||||
]);
|
||||
expect(problemText('templateToken', t)).toContain('"token":"{token}"');
|
||||
expect(problemText('secretShort', t)).toBe('mailAdmin.problem.secretShort');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import type { MailIngestAdminStatusResponse, MailIngestImapTls } from '@trek/shared';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
|
||||
/**
|
||||
* The admin form of the booking mail import, as plain data: which stored app
|
||||
* setting each field is, how the server's answer becomes the form, which
|
||||
* fields changed, and what the status card says. Shared by the desktop card
|
||||
* and the phone's admin section; no React here.
|
||||
*/
|
||||
|
||||
/** The transports an admin picks on a self-hosted install; the TREK Cloud relay is set by the operator. */
|
||||
type MailAdminTransport = 'off' | 'imap' | 'webhook';
|
||||
|
||||
export interface MailAdminForm {
|
||||
transport: MailAdminTransport;
|
||||
address_template: string;
|
||||
imap_host: string;
|
||||
imap_port: string;
|
||||
imap_tls: MailIngestImapTls;
|
||||
imap_user: string;
|
||||
/** "••••••••" while a stored password is untouched; the server keeps it then. */
|
||||
imap_pass: string;
|
||||
imap_mailbox: string;
|
||||
/** Masked like the password once stored. */
|
||||
webhook_secret: string;
|
||||
ai_per_user_daily: string;
|
||||
}
|
||||
|
||||
export type MailAdminField = keyof MailAdminForm;
|
||||
|
||||
/** What the server sends instead of a stored secret, and takes back as "unchanged". */
|
||||
export const MASKED = '••••••••';
|
||||
|
||||
/** The secret the webhook signs with: empty switches it off, else at least this long. */
|
||||
const WEBHOOK_SECRET_MIN = 32;
|
||||
|
||||
const KEY: Record<MailAdminField, string> = {
|
||||
transport: 'mail_ingest_transport',
|
||||
address_template: 'mail_ingest_address_template',
|
||||
imap_host: 'mail_ingest_imap_host',
|
||||
imap_port: 'mail_ingest_imap_port',
|
||||
imap_tls: 'mail_ingest_imap_tls',
|
||||
imap_user: 'mail_ingest_imap_user',
|
||||
imap_pass: 'mail_ingest_imap_pass',
|
||||
imap_mailbox: 'mail_ingest_imap_mailbox',
|
||||
webhook_secret: 'mail_ingest_webhook_secret',
|
||||
ai_per_user_daily: 'mail_ingest_ai_per_user_daily',
|
||||
};
|
||||
|
||||
export const ENABLED_KEY = 'mail_ingest_enabled';
|
||||
|
||||
const str = (value: unknown, fallback: string): string =>
|
||||
typeof value === 'string' || typeof value === 'number' ? String(value) : fallback;
|
||||
|
||||
/** The form from the admin's app settings; a key the server leaves out has its default. */
|
||||
export function formOf(settings: Record<string, unknown>): MailAdminForm {
|
||||
const transport = str(settings[KEY.transport], 'off');
|
||||
const tls = str(settings[KEY.imap_tls], 'tls');
|
||||
return {
|
||||
transport: transport === 'imap' || transport === 'webhook' ? transport : 'off',
|
||||
address_template: str(settings[KEY.address_template], ''),
|
||||
imap_host: str(settings[KEY.imap_host], ''),
|
||||
imap_port: str(settings[KEY.imap_port], '993'),
|
||||
imap_tls: tls === 'starttls' ? 'starttls' : 'tls',
|
||||
imap_user: str(settings[KEY.imap_user], ''),
|
||||
imap_pass: str(settings[KEY.imap_pass], ''),
|
||||
imap_mailbox: str(settings[KEY.imap_mailbox], 'INBOX'),
|
||||
webhook_secret: str(settings[KEY.webhook_secret], ''),
|
||||
ai_per_user_daily: str(settings[KEY.ai_per_user_daily], '10'),
|
||||
};
|
||||
}
|
||||
|
||||
export function enabledOf(settings: Record<string, unknown>): boolean {
|
||||
return String(settings[ENABLED_KEY] ?? 'false') === 'true';
|
||||
}
|
||||
|
||||
/** Only what changed, under the stored keys, so a save never touches a field the admin left alone. */
|
||||
export function changesOf(form: MailAdminForm, saved: MailAdminForm): Record<string, string> {
|
||||
const patch: Record<string, string> = {};
|
||||
for (const field of Object.keys(KEY) as MailAdminField[]) {
|
||||
if (form[field] !== saved[field]) patch[KEY[field]] = form[field].trim();
|
||||
}
|
||||
return patch;
|
||||
}
|
||||
|
||||
/** The fields the chosen transport shows, so the form never asks for what will not be used. */
|
||||
export function fieldsOf(transport: MailAdminTransport): MailAdminField[] {
|
||||
switch (transport) {
|
||||
case 'imap':
|
||||
return ['imap_host', 'imap_port', 'imap_tls', 'imap_user', 'imap_pass', 'imap_mailbox'];
|
||||
case 'webhook':
|
||||
return ['webhook_secret'];
|
||||
case 'off':
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export type MailAdminProblem = 'secretShort' | 'portInvalid' | 'templateToken' | 'dailyInvalid';
|
||||
|
||||
/** What stops a save, checked here so the admin hears it before the server answers. */
|
||||
export function problemsOf(form: MailAdminForm): MailAdminProblem[] {
|
||||
const problems: MailAdminProblem[] = [];
|
||||
const secret = form.webhook_secret.trim();
|
||||
if (form.transport === 'webhook' && secret !== MASKED && secret.length > 0 && secret.length < WEBHOOK_SECRET_MIN) {
|
||||
problems.push('secretShort');
|
||||
}
|
||||
const port = Number(form.imap_port);
|
||||
if (form.transport === 'imap' && !(Number.isInteger(port) && port > 0 && port < 65536)) problems.push('portInvalid');
|
||||
if (form.address_template.trim() && !form.address_template.includes('{token}')) problems.push('templateToken');
|
||||
const daily = Number(form.ai_per_user_daily);
|
||||
if (!(Number.isInteger(daily) && daily >= 0 && daily <= 1000)) problems.push('dailyInvalid');
|
||||
return problems;
|
||||
}
|
||||
|
||||
/** The status card in numbers: mails of the last day, added on their own, open entries. */
|
||||
export function statusFacts(status: MailIngestAdminStatusResponse): {
|
||||
mails: number;
|
||||
added: number;
|
||||
waiting: number;
|
||||
failed: number;
|
||||
} {
|
||||
const byStatus = status.last_day.by_status;
|
||||
const mails = Object.values(byStatus).reduce<number>((sum, n) => sum + (n ?? 0), 0);
|
||||
return {
|
||||
mails,
|
||||
added: status.auto_applied,
|
||||
waiting: status.backlog.reduce((sum, n) => sum + n, 0),
|
||||
failed: byStatus.failed ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** A problem in the admin's words; a switch of literal keys so the i18n check sees each one. */
|
||||
export function problemText(problem: MailAdminProblem, t: TranslationFn): string {
|
||||
switch (problem) {
|
||||
case 'secretShort':
|
||||
return t('mailAdmin.problem.secretShort');
|
||||
case 'portInvalid':
|
||||
return t('mailAdmin.problem.portInvalid');
|
||||
case 'templateToken':
|
||||
return t('mailAdmin.problem.templateToken', { token: '{token}' });
|
||||
case 'dailyInvalid':
|
||||
return t('mailAdmin.problem.dailyInvalid');
|
||||
}
|
||||
}
|
||||
|
||||
export const TRANSPORTS: MailAdminTransport[] = ['off', 'imap', 'webhook'];
|
||||
|
||||
export function transportLabel(transport: MailAdminTransport, t: TranslationFn): string {
|
||||
switch (transport) {
|
||||
case 'off':
|
||||
return t('mailAdmin.transport.off');
|
||||
case 'imap':
|
||||
return t('mailAdmin.transport.imap');
|
||||
case 'webhook':
|
||||
return t('mailAdmin.transport.webhook');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { MailIngestAdminStatusResponse, MailIngestAdminTestResponse } from '@trek/shared';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { mailIngestRepo } from '../../../repo/mailIngestRepo';
|
||||
import { getApiErrorMessage } from '../../../types';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
import {
|
||||
ENABLED_KEY,
|
||||
changesOf,
|
||||
enabledOf,
|
||||
formOf,
|
||||
problemsOf,
|
||||
type MailAdminField,
|
||||
type MailAdminForm,
|
||||
} from './mailIngestAdminModel';
|
||||
|
||||
/**
|
||||
* The admin card of the booking mail import, desktop and phone alike: the
|
||||
* instance switch (saved at once, as every switch in the admin settings), the
|
||||
* transport fields (saved together, only the changed ones), the connection
|
||||
* test and the status in counts. Loads once when shown.
|
||||
*/
|
||||
export function useMailIngestAdmin(active: boolean) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const [saved, setSaved] = useState<MailAdminForm | null>(null);
|
||||
const [form, setForm] = useState<MailAdminForm | null>(null);
|
||||
const [status, setStatus] = useState<MailIngestAdminStatusResponse | null>(null);
|
||||
const [test, setTest] = useState<MailIngestAdminTestResponse | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [testing, setTesting] = useState(false);
|
||||
|
||||
const loadStatus = useCallback(async () => {
|
||||
try {
|
||||
setStatus(await mailIngestRepo.adminStatus());
|
||||
} catch {
|
||||
setStatus(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
try {
|
||||
const raw = await mailIngestRepo.adminSettings();
|
||||
if (cancelled) return;
|
||||
const loaded = formOf(raw);
|
||||
setEnabled(enabledOf(raw));
|
||||
setSaved(loaded);
|
||||
setForm(loaded);
|
||||
} catch {
|
||||
if (!cancelled) toast.error(t('mailAdmin.loadError'));
|
||||
}
|
||||
if (!cancelled) await loadStatus();
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [active, loadStatus, t, toast]);
|
||||
|
||||
const toggle = async (on: boolean) => {
|
||||
setEnabled(on);
|
||||
try {
|
||||
await mailIngestRepo.saveAdminSettings({ [ENABLED_KEY]: on });
|
||||
void loadStatus();
|
||||
} catch (err: unknown) {
|
||||
setEnabled(!on);
|
||||
toast.error(getApiErrorMessage(err, t('common.error')));
|
||||
}
|
||||
};
|
||||
|
||||
const set = <K extends MailAdminField>(field: K, value: MailAdminForm[K]) =>
|
||||
setForm((current) => (current ? { ...current, [field]: value } : current));
|
||||
|
||||
const patch = form && saved ? changesOf(form, saved) : {};
|
||||
const problems = form ? problemsOf(form) : [];
|
||||
|
||||
const save = async () => {
|
||||
if (!form || Object.keys(patch).length === 0 || problems.length > 0) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await mailIngestRepo.saveAdminSettings(patch);
|
||||
setSaved(form);
|
||||
setTest(null);
|
||||
toast.success(t('common.saved'));
|
||||
void loadStatus();
|
||||
} catch (err: unknown) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const runTest = async () => {
|
||||
setTesting(true);
|
||||
try {
|
||||
setTest(await mailIngestRepo.adminTest());
|
||||
} catch (err: unknown) {
|
||||
setTest({ transport: form?.transport ?? 'off', ok: false, error: getApiErrorMessage(err, t('common.error')) });
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
loaded: form !== null,
|
||||
enabled,
|
||||
toggle: (on: boolean) => void toggle(on),
|
||||
form,
|
||||
set,
|
||||
dirty: Object.keys(patch).length > 0,
|
||||
problems,
|
||||
saving,
|
||||
save: () => void save(),
|
||||
status,
|
||||
test,
|
||||
testing,
|
||||
runTest: () => void runTest(),
|
||||
};
|
||||
}
|
||||
|
||||
export type MailIngestAdmin = ReturnType<typeof useMailIngestAdmin>;
|
||||
@@ -14,8 +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 { useMailIngestStore, watchMailInbox } from '../../store/mailIngestStore'
|
||||
import { openMailInbox } from '../MailIngest/mailInboxOpener'
|
||||
import { useMailInboxLink } from '../MailIngest/useMailInboxLink'
|
||||
import MailInboxDialog from '../MailIngest/MailInboxDialog'
|
||||
|
||||
const ADDON_ICONS: Record<string, LucideIcon> = { CalendarDays, Briefcase, Globe, Compass, Bookmark }
|
||||
@@ -50,9 +51,12 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
|
||||
const mailImport = useMailIngestStore(s => s.settings)
|
||||
const mailPending = useMailIngestStore(s => s.pending)
|
||||
const mailImportOn = !!mailImport?.available && mailImport.prefs.enabled
|
||||
useMailInboxLink(mailImportOn)
|
||||
const userId = user?.id
|
||||
useEffect(() => {
|
||||
if (userId) void useMailIngestStore.getState().loadSettings()
|
||||
if (!userId) return
|
||||
void useMailIngestStore.getState().loadSettings()
|
||||
return watchMailInbox()
|
||||
}, [userId])
|
||||
const darkMode = settings.dark_mode
|
||||
const dark = darkMode === true || darkMode === 'dark' || (darkMode === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)
|
||||
@@ -340,10 +344,10 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
|
||||
{/* 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">
|
||||
className="flex w-full items-center gap-2 px-4 py-2 text-body 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>}
|
||||
{mailPending > 0 && <span className="rounded-full bg-accent px-1.5 text-caption font-semibold text-accent-text">{mailPending}</span>}
|
||||
</button>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { MailIngestInboxEntry } from '@trek/shared';
|
||||
import { Copy, FilePlus2, FileText, Inbox, Loader2, Mail, PencilLine, Plus, Sparkles, Trash2 } from 'lucide-react';
|
||||
import { Copy, FilePlus2, FileText, Inbox, Loader2, Mail, PencilLine, Plus, Trash2 } from 'lucide-react';
|
||||
import { useId, type ReactElement } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { copyText } from '../../utils/clipboard';
|
||||
@@ -28,8 +28,6 @@ function actionLook(action: InboxAction, t: (key: string) => string): { icon: Re
|
||||
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') };
|
||||
}
|
||||
@@ -75,8 +73,8 @@ function Entry({ entry, inbox }: { entry: MailIngestInboxEntry; inbox: ReturnTyp
|
||||
<DialogIconButton
|
||||
label={t('mailInbox.settings.copy')}
|
||||
icon={<Copy size={13} strokeWidth={2} />}
|
||||
onClick={async () => {
|
||||
if (await copyText(code)) toast.success(t('common.copied'));
|
||||
onClick={() => {
|
||||
void copyText(code).then((ok) => ok && toast.success(t('common.copied')));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { mailIngestAddressResponseSchema, type MailIngestAddress } from '@trek/shared';
|
||||
import type { MailIngestAddress } from '@trek/shared';
|
||||
import { Copy, Mail, Plus } from 'lucide-react';
|
||||
import { useEffect, useState, type ReactElement } from 'react';
|
||||
import { mailIngestApi } from '../../api/mailIngest';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { mailIngestRepo } from '../../repo/mailIngestRepo';
|
||||
import { useMailIngestStore } from '../../store/mailIngestStore';
|
||||
import { copyText } from '../../utils/clipboard';
|
||||
import { useToast } from '../shared/Toast';
|
||||
@@ -30,13 +30,15 @@ export default function TripMailForward({ tripId }: { tripId: number }): ReactEl
|
||||
useEffect(() => {
|
||||
if (!on) return;
|
||||
let live = true;
|
||||
mailIngestApi
|
||||
mailIngestRepo
|
||||
.tripAddress(tripId)
|
||||
.then((raw) => {
|
||||
const parsed = mailIngestAddressResponseSchema.safeParse(raw);
|
||||
if (live && parsed.success) setAddress(parsed.data.address);
|
||||
.then((found) => {
|
||||
if (live) setAddress(found);
|
||||
})
|
||||
.catch(() => {});
|
||||
.catch(() => {
|
||||
// No address yet, or none readable: the card offers to create one instead.
|
||||
if (live) setAddress(null);
|
||||
});
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
@@ -47,7 +49,7 @@ export default function TripMailForward({ tripId }: { tripId: number }): ReactEl
|
||||
const create = async () => {
|
||||
setCreating(true);
|
||||
try {
|
||||
setAddress(mailIngestAddressResponseSchema.parse(await mailIngestApi.createTripAddress(tripId)).address);
|
||||
setAddress(await mailIngestRepo.createTripAddress(tripId));
|
||||
} catch {
|
||||
toast.error(t('mailInbox.settings.saveError'));
|
||||
} finally {
|
||||
|
||||
@@ -52,20 +52,19 @@ function entry(
|
||||
|
||||
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']);
|
||||
expect(actionsOf(entry())).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');
|
||||
expect(actionsOf(entry({ suggested_trip: null }))[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', () => {
|
||||
it('FE-MAILINBOX-MODEL-003: a mail without a booking offers the document and the form', () => {
|
||||
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']);
|
||||
expect(actionsOf(none)).toEqual(['file', 'manual', 'discard']);
|
||||
});
|
||||
|
||||
it('FE-MAILINBOX-MODEL-004: a forwarding confirmation or a newsletter only informs', () => {
|
||||
|
||||
@@ -8,107 +8,71 @@ import type { MailIngestInboxEntry, MailIngestReason } from '@trek/shared';
|
||||
*/
|
||||
|
||||
/** 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',
|
||||
]);
|
||||
export type InboxAction = 'add' | 'choose' | 'file' | 'manual' | 'discard';
|
||||
|
||||
/** 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[] {
|
||||
/**
|
||||
* A passing AI failure is read again by the server on its own; an allowance
|
||||
* used up leaves the form and the document, so there is no "read again" here.
|
||||
*/
|
||||
export function actionsOf(entry: MailIngestInboxEntry): 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;
|
||||
}
|
||||
|
||||
type Translate = (key: string) => string;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* A reason in the reader's words. A table of literal keys, so the i18n check
|
||||
* sees every key in use, and typed by the reason codes, so 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');
|
||||
}
|
||||
const REASON_TEXT: Record<MailIngestReason, (t: Translate) => string> = {
|
||||
forwarding_confirmation: (t) => t('mailInbox.reason.forwardingConfirmation'),
|
||||
newsletter: (t) => t('mailInbox.reason.newsletter'),
|
||||
auto_reply: (t) => t('mailInbox.reason.autoReply'),
|
||||
empty_mail: (t) => t('mailInbox.reason.emptyMail'),
|
||||
mail_unreadable: (t) => t('mailInbox.reason.mailUnreadable'),
|
||||
not_a_booking: (t) => t('mailInbox.reason.notABooking'),
|
||||
too_large: (t) => t('mailInbox.reason.tooLarge'),
|
||||
address_invalid: (t) => t('mailInbox.reason.addressInvalid'),
|
||||
address_daily_limit: (t) => t('mailInbox.reason.addressDailyLimit'),
|
||||
processing_failed: (t) => t('mailInbox.reason.processingFailed'),
|
||||
ai_quota_exhausted: (t) => t('mailInbox.reason.aiQuotaExhausted'),
|
||||
ai_disabled: (t) => t('mailInbox.reason.aiDisabled'),
|
||||
ai_user_cap: (t) => t('mailInbox.reason.aiUserCap'),
|
||||
ai_provider_error: (t) => t('mailInbox.reason.aiProviderError'),
|
||||
no_trip_in_range: (t) => t('mailInbox.reason.noTripInRange'),
|
||||
trip_ambiguous: (t) => t('mailInbox.reason.tripAmbiguous'),
|
||||
trip_without_dates: (t) => t('mailInbox.reason.tripWithoutDates'),
|
||||
no_edit_permission: (t) => t('mailInbox.reason.noEditPermission'),
|
||||
demo_mode: (t) => t('mailInbox.reason.demoMode'),
|
||||
outside_trip_dates: (t) => t('mailInbox.reason.outsideTripDates'),
|
||||
source_mismatch: (t) => t('mailInbox.reason.sourceMismatch'),
|
||||
implausible: (t) => t('mailInbox.reason.implausible'),
|
||||
not_in_text: (t) => t('mailInbox.reason.notInText'),
|
||||
image_only: (t) => t('mailInbox.reason.imageOnly'),
|
||||
missing_critical_field: (t) => t('mailInbox.reason.missingCriticalField'),
|
||||
missing_confirmation: (t) => t('mailInbox.reason.missingConfirmation'),
|
||||
too_many_bookings: (t) => t('mailInbox.reason.tooManyBookings'),
|
||||
change_or_cancellation: (t) => t('mailInbox.reason.changeOrCancellation'),
|
||||
cancelled: (t) => t('mailInbox.reason.cancelled'),
|
||||
possible_duplicate: (t) => t('mailInbox.reason.possibleDuplicate'),
|
||||
change_available: (t) => t('mailInbox.reason.changeAvailable'),
|
||||
conflict: (t) => t('mailInbox.reason.conflict'),
|
||||
ask_first: (t) => t('mailInbox.reason.askFirst'),
|
||||
};
|
||||
|
||||
export function reasonText(reason: MailIngestReason, t: Translate): string {
|
||||
return REASON_TEXT[reason](t);
|
||||
}
|
||||
|
||||
/** The entry's headline: the booking's title, else the mail's subject, else nothing to show. */
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { mailIngestSettingsResponseSchema, mailIngestUploadResponseSchema, type MailIngestPrefs } from '@trek/shared';
|
||||
import type { MailIngestPrefs } from '@trek/shared';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { mailIngestApi } from '../../api/mailIngest';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { mailIngestRepo } from '../../repo/mailIngestRepo';
|
||||
import { useMailIngestStore } from '../../store/mailIngestStore';
|
||||
import { copyText } from '../../utils/clipboard';
|
||||
import { useToast } from '../shared/Toast';
|
||||
@@ -37,10 +37,7 @@ export function useMailImportSettings() {
|
||||
if (!settings || saving) return;
|
||||
setSaving(key);
|
||||
try {
|
||||
const parsed = mailIngestSettingsResponseSchema.parse(
|
||||
await mailIngestApi.updateSettings({ [key]: !settings.prefs[key] })
|
||||
);
|
||||
setSettings(parsed);
|
||||
setSettings(await mailIngestRepo.updateSettings({ [key]: !settings.prefs[key] }));
|
||||
} catch {
|
||||
toast.error(t('mailInbox.settings.saveError'));
|
||||
} finally {
|
||||
@@ -64,7 +61,7 @@ export function useMailImportSettings() {
|
||||
setRenewArmed(false);
|
||||
setRenewing(true);
|
||||
try {
|
||||
await mailIngestApi.renewAddress();
|
||||
await mailIngestRepo.renewAddress();
|
||||
await loadSettings();
|
||||
toast.success(t('mailInbox.settings.renewed'));
|
||||
} catch {
|
||||
@@ -77,7 +74,7 @@ export function useMailImportSettings() {
|
||||
const upload = async (file: File) => {
|
||||
setUploading(true);
|
||||
try {
|
||||
const { duplicate } = mailIngestUploadResponseSchema.parse(await mailIngestApi.upload(file));
|
||||
const { duplicate } = await mailIngestRepo.upload(file);
|
||||
toast.success(duplicate ? t('mailInbox.settings.uploadDuplicate') : t('mailInbox.settings.uploaded'));
|
||||
} catch {
|
||||
toast.error(t('mailInbox.settings.uploadError'));
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import {
|
||||
mailIngestMessagePreviewResponseSchema,
|
||||
type MailIngestInboxEntry,
|
||||
type MailIngestMessagePreviewResponse,
|
||||
} from '@trek/shared';
|
||||
import type { MailIngestInboxEntry, 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 { useShallow } from 'zustand/react/shallow';
|
||||
import type { MailIngestAction } from '../../api/mailIngest';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { mailIngestRepo } from '../../repo/mailIngestRepo';
|
||||
import { tripRepo } from '../../repo/tripRepo';
|
||||
import { useMailIngestStore } from '../../store/mailIngestStore';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import { actionsOf, type InboxAction } from './mailInboxModel';
|
||||
@@ -32,7 +30,18 @@ export function useMailInbox() {
|
||||
const toast = useToast();
|
||||
const navigate = useNavigate();
|
||||
const open = useMailInboxOpen((s) => s.open);
|
||||
const { entries, pending, nextBefore, loadingInbox, settings, loadInbox, loadSettings, act } = useMailIngestStore();
|
||||
const { entries, pending, nextBefore, loadingInbox, settings, loadInbox, loadSettings, act } = useMailIngestStore(
|
||||
useShallow((s) => ({
|
||||
entries: s.entries,
|
||||
pending: s.pending,
|
||||
nextBefore: s.nextBefore,
|
||||
loadingInbox: s.loadingInbox,
|
||||
settings: s.settings,
|
||||
loadInbox: s.loadInbox,
|
||||
loadSettings: s.loadSettings,
|
||||
act: s.act,
|
||||
}))
|
||||
);
|
||||
const [trips, setTrips] = useState<InboxTrip[]>([]);
|
||||
const [busy, setBusy] = useState<number | null>(null);
|
||||
/** The entry and the action waiting for a trip to be picked. */
|
||||
@@ -45,10 +54,17 @@ export function useMailInbox() {
|
||||
if (!open) return;
|
||||
void loadInbox();
|
||||
if (!settings) void loadSettings();
|
||||
tripsApi
|
||||
tripRepo
|
||||
.list()
|
||||
.then((d: { trips?: InboxTrip[] }) =>
|
||||
setTrips((d.trips ?? []).map(({ id, title, start_date, end_date }) => ({ id, title, start_date, end_date })))
|
||||
.then(({ trips: active }) =>
|
||||
setTrips(
|
||||
active.map(({ id, title, start_date, end_date }) => ({
|
||||
id,
|
||||
title,
|
||||
start_date: start_date ?? null,
|
||||
end_date: end_date ?? null,
|
||||
}))
|
||||
)
|
||||
)
|
||||
.catch(() => setTrips([]));
|
||||
}, [open, loadInbox, loadSettings, settings]);
|
||||
@@ -81,8 +97,6 @@ export function useMailInbox() {
|
||||
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':
|
||||
@@ -100,7 +114,7 @@ export function useMailInbox() {
|
||||
|
||||
const openForm = (entry: MailIngestInboxEntry, tripId: number) => {
|
||||
closeMailInbox();
|
||||
navigate(`/trips/${tripId}?mailPrefill=${entry.id}`);
|
||||
void navigate(`/trips/${tripId}?mailPrefill=${entry.id}`);
|
||||
};
|
||||
|
||||
const fillIn = (entry: MailIngestInboxEntry) => {
|
||||
@@ -111,13 +125,12 @@ export function useMailInbox() {
|
||||
|
||||
const showMail = async (entry: MailIngestInboxEntry) => {
|
||||
try {
|
||||
setPreview(mailIngestMessagePreviewResponseSchema.parse(await mailIngestApi.preview(entry.message_id)));
|
||||
setPreview(await mailIngestRepo.preview(entry.message_id));
|
||||
} catch {
|
||||
toast.error(t('mailInbox.previewError'));
|
||||
}
|
||||
};
|
||||
|
||||
const aiAvailable = !!settings?.ai_available && !!settings.prefs.ai_enabled;
|
||||
return {
|
||||
open,
|
||||
close: closeMailInbox,
|
||||
@@ -128,7 +141,7 @@ export function useMailInbox() {
|
||||
loading: loadingInbox,
|
||||
trips,
|
||||
busy,
|
||||
actionsOf: (entry: MailIngestInboxEntry) => actionsOf(entry, aiAvailable),
|
||||
actionsOf,
|
||||
perform: (entry: MailIngestInboxEntry, action: InboxAction) => void perform(entry, action),
|
||||
picking,
|
||||
pick,
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router';
|
||||
import { openMailInbox } from './mailInboxOpener';
|
||||
|
||||
/** The query a link uses to open the inbox, e.g. the "bookings waiting" notification's `/dashboard?inbox=mail`. */
|
||||
const INBOX_PARAM = 'inbox';
|
||||
const INBOX_MAIL = 'mail';
|
||||
|
||||
/**
|
||||
* Opens the inbox of forwarded bookings when the address asks for it, then
|
||||
* takes the query off again so a reload or the back button does not reopen
|
||||
* it. Mounted where the inbox itself is mounted: the Navbar on the desktop,
|
||||
* MMailInboxHost on the phone.
|
||||
*/
|
||||
export function useMailInboxLink(enabled: boolean): void {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const params = new URLSearchParams(location.search);
|
||||
if (params.get(INBOX_PARAM) !== INBOX_MAIL) return;
|
||||
openMailInbox();
|
||||
params.delete(INBOX_PARAM);
|
||||
const search = params.toString();
|
||||
void navigate(
|
||||
{ pathname: location.pathname, search: search ? `?${search}` : '', hash: location.hash },
|
||||
{ replace: true }
|
||||
);
|
||||
}, [enabled, location.pathname, location.search, location.hash, navigate]);
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
import {
|
||||
isTransportReservationType,
|
||||
mailIngestPrefillResponseSchema,
|
||||
type BookingImportPreviewItem,
|
||||
} from '@trek/shared';
|
||||
import { isTransportReservationType, type BookingImportPreviewItem } from '@trek/shared';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import type { SetURLSearchParams } from 'react-router';
|
||||
import { mailIngestApi } from '../../api/mailIngest';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { mailIngestRepo } from '../../repo/mailIngestRepo';
|
||||
import { useToast } from '../shared/Toast';
|
||||
|
||||
/**
|
||||
* "Fill in yourself" from the mail inbox lands in the trip as ?mailPrefill=<id>:
|
||||
@@ -25,6 +23,8 @@ export function useMailPrefillLink({
|
||||
loaded: boolean;
|
||||
startImportReview: (items: BookingImportPreviewItem[], files?: File[], kind?: 'transports' | 'bookings') => void;
|
||||
}): void {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const requested = searchParams.get('mailPrefill');
|
||||
const handled = useRef<string | null>(null);
|
||||
|
||||
@@ -41,14 +41,14 @@ export function useMailPrefillLink({
|
||||
);
|
||||
const id = Number(requested);
|
||||
if (!Number.isInteger(id) || id <= 0) return;
|
||||
mailIngestApi
|
||||
mailIngestRepo
|
||||
.prefill(id)
|
||||
.then((raw) => {
|
||||
const { item } = mailIngestPrefillResponseSchema.parse(raw);
|
||||
.then(({ item }) => {
|
||||
startImportReview([item], [], isTransportReservationType(item.type) ? 'transports' : 'bookings');
|
||||
})
|
||||
.catch(() => {
|
||||
// An entry decided meanwhile has nothing to prefill; the trip simply stays open.
|
||||
// An entry decided meanwhile has nothing to prefill: the trip stays open, and the person hears why.
|
||||
toast.error(t('mailInbox.actionError'));
|
||||
});
|
||||
}, [requested, loaded, setSearchParams, startImportReview]);
|
||||
}, [requested, loaded, setSearchParams, startImportReview, t, toast]);
|
||||
}
|
||||
|
||||
@@ -41,6 +41,9 @@ const KIND_BY_TITLE: Record<string, NotificationKind> = {
|
||||
'notif.flight_departed.title': 'flight',
|
||||
'notif.flight_delayed.title': 'flight',
|
||||
'notif.flight_landed.title': 'flight',
|
||||
'notif.mail_booking_added.title': 'booking',
|
||||
'notif.mail_booking_pending.title': 'booking',
|
||||
'notif.mail_ingest_paused.title': 'alert',
|
||||
'notif.packing_tagged.title': 'packing',
|
||||
'notif.todo_due.title': 'todo',
|
||||
'notif.vacay_invite.title': 'vacay',
|
||||
|
||||
@@ -110,6 +110,15 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) {
|
||||
if (await copyText(r.confirmation_number || '')) toast.success(t('common.copied'))
|
||||
else toast.error(t('reservations.copyFailed'))
|
||||
}
|
||||
// "Looks right": the person checked what an import could not read for sure.
|
||||
const confirmReview = async () => {
|
||||
try {
|
||||
await updateReservation(p.tripId, r.id, { needs_review: 0 })
|
||||
toast.success(t('reservations.reviewConfirmed'))
|
||||
} catch {
|
||||
toast.error(t('reservations.toast.updateError'))
|
||||
}
|
||||
}
|
||||
const rename = async () => {
|
||||
const title = name.trim()
|
||||
setRenaming(false)
|
||||
@@ -143,7 +152,7 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) {
|
||||
{facts.day.date && !facts.isHotel && <span className="font-medium text-content-muted">{facts.day.date}</span>}
|
||||
</span>
|
||||
)}
|
||||
{!!r.needs_review && <ReviewPill pill />}
|
||||
{!!r.needs_review && <ReviewPill pill onConfirm={p.canEdit ? () => void confirmReview() : undefined} />}
|
||||
<AirTrailPill r={r} pill />
|
||||
<MailPill r={r} pill />
|
||||
{r.confirmation_number && (
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
// FE-PLANNER-BKPARTS-001 to FE-PLANNER-BKPARTS-004
|
||||
// FE-PLANNER-BKPARTS-001 to FE-PLANNER-BKPARTS-005
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildTripFile } from '../../../../tests/helpers/factories';
|
||||
import { downloadFile, openFile } from '../../../utils/fileDownload';
|
||||
import type { BookingFacts } from './bookingFacts';
|
||||
import { FileRows, WhenFields } from './bookingParts';
|
||||
import { FileRows, ReviewPill, WhenFields } from './bookingParts';
|
||||
|
||||
vi.mock('../../../utils/fileDownload', () => ({
|
||||
openFile: vi.fn(() => Promise.resolve()),
|
||||
@@ -88,4 +88,13 @@ describe('FileRows', () => {
|
||||
const { container } = render(<FileRows files={[]} />);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKPARTS-005: the review pill takes its mark off only for someone who may edit', () => {
|
||||
const onConfirm = vi.fn();
|
||||
const { rerender } = render(<ReviewPill pill />);
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument();
|
||||
rerender(<ReviewPill pill onConfirm={onConfirm} />);
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
expect(onConfirm).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -167,15 +167,33 @@ export function TypeTile({ type, size = 32, raised = false }: { type: string; si
|
||||
)
|
||||
}
|
||||
|
||||
/** The warning icon beside a booking's name on a card or row, or with `pill` a header pill in the detail dialog. */
|
||||
export function ReviewPill({ pill = false }: { pill?: boolean }) {
|
||||
/**
|
||||
* The warning icon beside a booking's name on a card or row, or with `pill` a
|
||||
* header pill in the detail dialog. With `onConfirm` (the right to edit) the
|
||||
* pill is the "looks right" switch that takes the mark off.
|
||||
*/
|
||||
export function ReviewPill({ pill = false, onConfirm }: { pill?: boolean; onConfirm?: () => void }) {
|
||||
const { t } = useTranslation()
|
||||
const content = (
|
||||
<>
|
||||
<AlertCircle size={13} strokeWidth={2.2} className="text-warning" />
|
||||
{t('reservations.needsReview')}
|
||||
</>
|
||||
)
|
||||
if (pill && onConfirm) {
|
||||
return (
|
||||
<Tooltip label={`${t('reservations.needsReviewHint')} ${t('reservations.reviewConfirmHint')}`}>
|
||||
<button type="button" onClick={onConfirm} aria-label={t('reservations.reviewConfirm')} className={`${PILL} hover:opacity-80`} style={fs(12, 'body')}>
|
||||
{content}
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<Tooltip label={t('reservations.needsReviewHint')}>
|
||||
{pill ? (
|
||||
<span className={PILL} style={fs(12, 'body')}>
|
||||
<AlertCircle size={13} strokeWidth={2.2} className="text-warning" />
|
||||
{t('reservations.needsReview')}
|
||||
{content}
|
||||
</span>
|
||||
) : (
|
||||
<span role="img" aria-label={t('reservations.needsReview')} className="grid flex-none place-items-center text-warning">
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import type { Reservation } from '../../../types';
|
||||
import type { DelayTone } from '../../../utils/flightLiveModel';
|
||||
import { BOX, Eyebrow } from '../bookings/bookingParts';
|
||||
import { useCurrentFlightLegIndex, useFlightLiveCard } from './useFlightLiveCard';
|
||||
|
||||
const DELAY_TEXT: Record<DelayTone, string> = { ok: 'text-success', minor: 'text-warning', major: 'text-danger' };
|
||||
@@ -13,8 +15,9 @@ interface FlightLiveStripProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* A flight's live state on the booking cards: what is happening in one line
|
||||
* with the delay, and a thin bar across the card while it flies. The full
|
||||
* A flight's live state on the booking cards, as one of the card's fields:
|
||||
* what is happening in one line with the delay, and a thin bar along the
|
||||
* field's foot while it flies. The full
|
||||
* picture is one click away in the booking dialog. Nothing far ahead of the
|
||||
* flight (the card shows its date already), nothing once it is long over.
|
||||
*/
|
||||
@@ -30,30 +33,30 @@ function Strip({
|
||||
legIndex,
|
||||
className,
|
||||
}: Omit<FlightLiveStripProps, 'type'> & { legIndex: number }) {
|
||||
const { t } = useTranslation();
|
||||
const card = useFlightLiveCard(tripId, reservationId, legIndex);
|
||||
if (!card || card.view.stage === 'upcoming') return null;
|
||||
const { view } = card;
|
||||
// The card's own field: the eyebrow over a framed value, like the booking code and the route under it.
|
||||
return (
|
||||
<div className={`flex min-w-0 flex-col gap-1.5 rounded-lg bg-surface-tertiary px-2.5 py-[7px] ${className}`}>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate text-caption font-semibold text-content">{card.line}</span>
|
||||
{card.delay && card.delay.tone !== 'ok' && (
|
||||
<span className={`flex-none text-caption font-semibold tabular-nums ${DELAY_TEXT[card.delay.tone]}`}>
|
||||
{card.delay.text}
|
||||
<div className={`min-w-0 ${className}`}>
|
||||
<Eyebrow className="mb-[3px]">{t('reservations.status')}</Eyebrow>
|
||||
<div className={`${BOX} relative overflow-hidden px-[10px] py-[7px]`}>
|
||||
<div className="flex min-w-0 items-center justify-center gap-2 text-body font-semibold text-content">
|
||||
<span className="min-w-0 truncate">{card.line}</span>
|
||||
{card.delay && card.delay.tone !== 'ok' && (
|
||||
<span className={`flex-none tabular-nums ${DELAY_TEXT[card.delay.tone]}`}>{card.delay.text}</span>
|
||||
)}
|
||||
</div>
|
||||
{view.stage === 'airborne' && (
|
||||
<span className="absolute inset-x-0 bottom-0 block h-[3px] bg-surface-tertiary" aria-hidden="true">
|
||||
<span
|
||||
className="block h-full bg-info transition-[width] duration-700 motion-reduce:transition-none"
|
||||
style={{ width: `${Math.round(view.progress * 100)}%` }}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{view.stage === 'airborne' && (
|
||||
<span
|
||||
className="block h-1 w-full overflow-hidden rounded-full bg-[color:var(--border-primary)]"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<span
|
||||
className="block h-full rounded-full bg-accent transition-[width] duration-700 motion-reduce:transition-none"
|
||||
style={{ width: `${Math.round(view.progress * 100)}%` }}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -90,3 +90,14 @@
|
||||
.flight-mini-map .leaflet-tooltip.flight-mini-code::before {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* A map kept to the middle of its pass (the phone): the edges still run out,
|
||||
but the route fills most of it instead of a third. */
|
||||
.flight-mini-map.flight-mini-map--narrow {
|
||||
-webkit-mask-image:
|
||||
linear-gradient(to right, transparent, #000 16%, #000 84%, transparent),
|
||||
linear-gradient(to bottom, transparent, #000 18%, #000 82%, transparent);
|
||||
mask-image:
|
||||
linear-gradient(to right, transparent, #000 16%, #000 84%, transparent),
|
||||
linear-gradient(to bottom, transparent, #000 18%, #000 82%, transparent);
|
||||
}
|
||||
|
||||
@@ -32,6 +32,9 @@ export const EVENT_LABEL_KEYS: Record<string, string> = {
|
||||
flight_departed: 'settings.notifyFlightDeparted',
|
||||
flight_delayed: 'settings.notifyFlightDelayed',
|
||||
flight_landed: 'settings.notifyFlightLanded',
|
||||
mail_booking_added: 'settings.notifyMailBookingAdded',
|
||||
mail_booking_pending: 'settings.notifyMailBookingPending',
|
||||
mail_ingest_paused: 'settings.notifyMailIngestPaused',
|
||||
}
|
||||
|
||||
/** Plugin channels have no i18n; the server sends their display name outright. */
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { useAdmin } from '../../../pages/admin/useAdmin'
|
||||
import MToggle from '../../components/MToggle'
|
||||
import { MBlockDisclosure, MProviderBlock, MTrekApiBlock } from './MApiProviderBlocks'
|
||||
import MAdminOidcCard from './MAdminOidcCard'
|
||||
import MMailIngestAdminCard from './MMailIngestAdminCard'
|
||||
import MSetPickerSheet from '../settings/MSetPickerSheet'
|
||||
import {
|
||||
MAdminButton,
|
||||
@@ -196,6 +197,9 @@ export default function MAdminSettingsSection({ admin, t }: MAdminSettingsSectio
|
||||
onChange={(v) => void handleToggleAuthSetting('flight_live_enabled', v, setFlightLive)}
|
||||
/>
|
||||
|
||||
{/* Booking mail import: self-hosted only, the operator runs the TREK Cloud relay (desktop parity). */}
|
||||
{!managed && <MMailIngestAdminCard />}
|
||||
|
||||
{/* Allowed file types */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead title={t('admin.fileTypes')} hint={t('admin.fileTypesHint')} />
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import {
|
||||
TRANSPORTS,
|
||||
problemText,
|
||||
statusFacts,
|
||||
transportLabel,
|
||||
type MailAdminForm,
|
||||
type MailAdminProblem,
|
||||
} from '../../../components/Admin/mailIngest/mailIngestAdminModel';
|
||||
import { useMailIngestAdmin, type MailIngestAdmin } from '../../../components/Admin/mailIngest/useMailIngestAdmin';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
import { relativeTime } from '../../../utils/relativeTime';
|
||||
import MSegmented from '../../components/MSegmented';
|
||||
import MToggle from '../../components/MToggle';
|
||||
import {
|
||||
MAdminButton,
|
||||
MAdminCard,
|
||||
MAdminCardHead,
|
||||
MAdminField,
|
||||
MAdminInput,
|
||||
MAdminRow,
|
||||
MAdminSecretInput,
|
||||
} from './MAdminUi';
|
||||
|
||||
interface PartProps {
|
||||
admin: MailIngestAdmin;
|
||||
form: MailAdminForm;
|
||||
t: TranslationFn;
|
||||
}
|
||||
|
||||
/** The problem under a field, in the danger colour, or nothing. */
|
||||
function Problem({ admin, problem, t }: { admin: MailIngestAdmin; problem: MailAdminProblem; t: TranslationFn }) {
|
||||
if (!admin.problems.includes(problem)) return null;
|
||||
return <p className="mt-1 text-caption text-[color:var(--m-st-danger)]">{problemText(problem, t)}</p>;
|
||||
}
|
||||
|
||||
function ImapFields({ admin, form, t }: PartProps) {
|
||||
return (
|
||||
<>
|
||||
<MAdminField label={t('mailAdmin.imap.host')}>
|
||||
<MAdminInput
|
||||
value={form.imap_host}
|
||||
placeholder="imap.example.com"
|
||||
onChange={(e) => admin.set('imap_host', e.target.value)}
|
||||
/>
|
||||
</MAdminField>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<MAdminField label={t('mailAdmin.imap.port')}>
|
||||
<MAdminInput
|
||||
inputMode="numeric"
|
||||
value={form.imap_port}
|
||||
onChange={(e) => admin.set('imap_port', e.target.value)}
|
||||
/>
|
||||
<Problem admin={admin} problem="portInvalid" t={t} />
|
||||
</MAdminField>
|
||||
<MAdminField label={t('mailAdmin.imap.tls')}>
|
||||
<MSegmented
|
||||
value={form.imap_tls}
|
||||
onChange={(value) => admin.set('imap_tls', value)}
|
||||
options={[
|
||||
{ value: 'tls', label: 'TLS' },
|
||||
{ value: 'starttls', label: 'STARTTLS' },
|
||||
]}
|
||||
/>
|
||||
</MAdminField>
|
||||
</div>
|
||||
<MAdminField label={t('mailAdmin.imap.user')}>
|
||||
<MAdminInput
|
||||
autoComplete="off"
|
||||
value={form.imap_user}
|
||||
onChange={(e) => admin.set('imap_user', e.target.value)}
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label={t('mailAdmin.imap.pass')}>
|
||||
<MAdminSecretInput
|
||||
autoComplete="new-password"
|
||||
value={form.imap_pass}
|
||||
onChange={(e) => admin.set('imap_pass', e.target.value)}
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label={t('mailAdmin.imap.mailbox')} hint={t('mailAdmin.imap.mailboxHint')}>
|
||||
<MAdminInput value={form.imap_mailbox} onChange={(e) => admin.set('imap_mailbox', e.target.value)} />
|
||||
</MAdminField>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function WebhookFields({ admin, form, t }: PartProps) {
|
||||
return (
|
||||
<>
|
||||
<MAdminField label={t('mailAdmin.webhook.secret')} hint={t('mailAdmin.webhook.secretHint')}>
|
||||
<MAdminSecretInput
|
||||
autoComplete="new-password"
|
||||
value={form.webhook_secret}
|
||||
onChange={(e) => admin.set('webhook_secret', e.target.value)}
|
||||
/>
|
||||
<Problem admin={admin} problem="secretShort" t={t} />
|
||||
</MAdminField>
|
||||
<MAdminField label={t('mailAdmin.inboundUrl')} hint={t('mailAdmin.inboundUrlHint')}>
|
||||
<p className="break-all font-geist text-caption text-m-muted">{`${window.location.origin}/api/mail-ingest/inbound`}</p>
|
||||
</MAdminField>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** How the import runs, in counts only. */
|
||||
function Status({ admin, t, locale }: { admin: MailIngestAdmin; t: TranslationFn; locale: string }) {
|
||||
const status = admin.status;
|
||||
if (!status) return null;
|
||||
const facts = statusFacts(status);
|
||||
const lastRead = status.last_ok_at
|
||||
? relativeTime(Date.parse(status.last_ok_at), locale)
|
||||
: t('mailAdmin.status.never');
|
||||
return (
|
||||
<div className="mt-3 rounded-[12px] bg-[color:var(--m-ic)] px-3 py-[10px]">
|
||||
<p className="text-caption font-semibold text-m-ink">{t('mailAdmin.status.lastRead', { time: lastRead })}</p>
|
||||
<div className="mt-2 grid grid-cols-2 gap-x-3 gap-y-[6px]">
|
||||
{[
|
||||
{ label: t('mailAdmin.status.mails'), value: facts.mails },
|
||||
{ label: t('mailAdmin.status.added'), value: facts.added },
|
||||
{ label: t('mailAdmin.status.waiting'), value: facts.waiting },
|
||||
{ label: t('mailAdmin.status.failed'), value: facts.failed },
|
||||
].map((f) => (
|
||||
<div key={f.label} className="flex items-baseline justify-between gap-2">
|
||||
<span className="truncate text-caption text-m-faint">{f.label}</span>
|
||||
<span className="font-geist text-body font-bold tabular-nums text-m-ink">{f.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{status.last_error && <p className="mt-2 text-caption text-[color:var(--m-st-pending)]">{status.last_error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Setup({ admin, form, t, locale }: PartProps & { locale: string }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-3 px-[14px] pb-[14px] pt-1">
|
||||
<MAdminField label={t('mailAdmin.transport.label')}>
|
||||
<MSegmented
|
||||
value={form.transport}
|
||||
onChange={(value) => admin.set('transport', value)}
|
||||
options={TRANSPORTS.map((x) => ({ value: x, label: transportLabel(x, t) }))}
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label={t('mailAdmin.template')} hint={t('mailAdmin.templateHint', { token: '{token}' })}>
|
||||
<MAdminInput
|
||||
value={form.address_template}
|
||||
placeholder="trek+{token}@example.com"
|
||||
onChange={(e) => admin.set('address_template', e.target.value)}
|
||||
/>
|
||||
<Problem admin={admin} problem="templateToken" t={t} />
|
||||
</MAdminField>
|
||||
{form.transport === 'imap' && <ImapFields admin={admin} form={form} t={t} />}
|
||||
{form.transport === 'webhook' && <WebhookFields admin={admin} form={form} t={t} />}
|
||||
<MAdminField label={t('mailAdmin.aiDaily')} hint={t('mailAdmin.aiDailyHint')}>
|
||||
<MAdminInput
|
||||
inputMode="numeric"
|
||||
value={form.ai_per_user_daily}
|
||||
onChange={(e) => admin.set('ai_per_user_daily', e.target.value)}
|
||||
/>
|
||||
<Problem admin={admin} problem="dailyInvalid" t={t} />
|
||||
</MAdminField>
|
||||
<p className="text-caption text-m-faint">{t('mailAdmin.envHint')}</p>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<MAdminButton busy={admin.saving} disabled={!admin.dirty || admin.problems.length > 0} onClick={admin.save}>
|
||||
{t('common.save')}
|
||||
</MAdminButton>
|
||||
<MAdminButton
|
||||
variant="ghost"
|
||||
busy={admin.testing}
|
||||
disabled={admin.dirty || form.transport === 'off'}
|
||||
onClick={admin.runTest}
|
||||
>
|
||||
{t('mailAdmin.test.run')}
|
||||
</MAdminButton>
|
||||
{admin.test && (
|
||||
<span
|
||||
className={`text-caption font-semibold ${admin.test.ok ? 'text-[color:var(--m-st-confirmed)]' : 'text-[color:var(--m-st-danger)]'}`}
|
||||
>
|
||||
{admin.test.ok ? t('mailAdmin.test.ok') : (admin.test.error ?? t('mailAdmin.test.failed'))}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Status admin={admin} t={t} locale={locale} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The booking mail import in the phone's admin settings, the same card as on
|
||||
* the desktop (useMailIngestAdmin): the switch, how mail arrives, the address
|
||||
* template, the AI allowance, the test and the status. Self-hosted only.
|
||||
*/
|
||||
export default function MMailIngestAdminCard() {
|
||||
const { t, locale } = useTranslation();
|
||||
const admin = useMailIngestAdmin(true);
|
||||
return (
|
||||
<MAdminCard>
|
||||
<MAdminCardHead title={t('mailAdmin.title')} hint={t('mailAdmin.hint')} />
|
||||
<MAdminRow
|
||||
title={t('mailAdmin.enabled')}
|
||||
hint={t('mailAdmin.enabledHint')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={admin.enabled}
|
||||
ariaLabel={t('mailAdmin.enabled')}
|
||||
disabled={!admin.loaded}
|
||||
onChange={admin.toggle}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{admin.enabled && admin.form && <Setup admin={admin} form={admin.form} t={t} locale={locale} />}
|
||||
</MAdminCard>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +1,24 @@
|
||||
import { useEffect, type ReactElement } from 'react';
|
||||
import { useMailInboxLink } from '../../../components/MailIngest/useMailInboxLink';
|
||||
import { useAuthStore } from '../../../store/authStore';
|
||||
import { useMailIngestStore } from '../../../store/mailIngestStore';
|
||||
import { useMailIngestStore, watchMailInbox } 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.
|
||||
* needs them), follows the server's inbox events, 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();
|
||||
if (!userId) return;
|
||||
void useMailIngestStore.getState().loadSettings();
|
||||
return watchMailInbox();
|
||||
}, [userId]);
|
||||
return settings?.available && settings.prefs.enabled ? <MMailInboxSheet /> : null;
|
||||
const on = !!settings?.available && settings.prefs.enabled;
|
||||
useMailInboxLink(on);
|
||||
return on ? <MMailInboxSheet /> : null;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { MailIngestInboxEntry } from '@trek/shared';
|
||||
import { ChevronLeft, Copy, FilePlus2, FileText, Inbox, Mail, PencilLine, Plus, Sparkles, Trash2 } from 'lucide-react';
|
||||
import { ChevronLeft, Copy, FilePlus2, FileText, Inbox, Mail, PencilLine, Plus, Trash2 } from 'lucide-react';
|
||||
import type { ReactElement } from 'react';
|
||||
import { entryDates, entryTitle, reasonText, type InboxAction } from '../../../components/MailIngest/mailInboxModel';
|
||||
import { useMailInbox } from '../../../components/MailIngest/useMailInbox';
|
||||
@@ -23,8 +23,6 @@ function icon(action: InboxAction): ReactElement {
|
||||
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} />;
|
||||
}
|
||||
@@ -40,8 +38,6 @@ function label(action: InboxAction, t: (key: string) => string): string {
|
||||
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');
|
||||
}
|
||||
@@ -97,8 +93,8 @@ function Entry({ entry, inbox }: { entry: MailIngestInboxEntry; inbox: ReturnTyp
|
||||
type="button"
|
||||
aria-label={t('mailInbox.settings.copy')}
|
||||
className={ROUND}
|
||||
onClick={async () => {
|
||||
if (await copyText(code)) toast.success(t('common.copied'));
|
||||
onClick={() => {
|
||||
void copyText(code).then((ok) => ok && toast.success(t('common.copied')));
|
||||
}}
|
||||
>
|
||||
<Copy size={15} strokeWidth={2} />
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useCurrentFlightLegIndex, useFlightLiveCard } from '../../../components/Planner/flightLive/useFlightLiveCard';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import type { DelayTone } from '../../../utils/flightLiveModel';
|
||||
import { Field } from './tabs/tabChrome';
|
||||
|
||||
const DELAY_COLOR: Record<DelayTone, string> = {
|
||||
ok: 'var(--m-st-confirmed)',
|
||||
@@ -18,8 +20,9 @@ interface MFlightLiveStripProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* A flight's live state on the phone's transport cards: what is happening in
|
||||
* one line with the delay, and a thin bar across the card while it flies. A
|
||||
* A flight's live state on the phone's transport cards, as one of the card's
|
||||
* fields: what is happening in one line with the delay, and a thin bar along
|
||||
* the field's foot while it flies. A
|
||||
* tap opens the transport sheet with the full card. Nothing far ahead of the
|
||||
* flight (the card shows its date already), nothing once it is long over.
|
||||
*/
|
||||
@@ -32,37 +35,31 @@ export default function MFlightLiveStrip({ tripId, reservationId, onOpen, classN
|
||||
}
|
||||
|
||||
function Strip({ tripId, reservationId, legIndex, onOpen, className }: MFlightLiveStripProps & { legIndex: number }) {
|
||||
const { t } = useTranslation();
|
||||
const card = useFlightLiveCard(tripId, reservationId, legIndex);
|
||||
if (!card || card.view.stage === 'upcoming') return null;
|
||||
const { view } = card;
|
||||
// One of the card's own fields, full width: the label over the framed value, like the booking code below it.
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className={`flex min-w-0 flex-col gap-[6px] rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-[7px] text-start ${className}`}
|
||||
>
|
||||
<span className="flex w-full min-w-0 items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate text-caption font-semibold text-m-ink">{card.line}</span>
|
||||
{card.delay && card.delay.tone !== 'ok' && (
|
||||
<span
|
||||
className="flex-none font-geist text-caption font-bold tabular-nums"
|
||||
style={{ color: DELAY_COLOR[card.delay.tone] }}
|
||||
>
|
||||
{card.delay.text}
|
||||
<button type="button" onClick={onOpen} className={`block text-start ${className}`}>
|
||||
<Field label={t('reservations.status')} className="w-full">
|
||||
<span className="inline-flex max-w-full items-center gap-2 align-middle">
|
||||
<span className="min-w-0 truncate">{card.line}</span>
|
||||
{card.delay && card.delay.tone !== 'ok' && (
|
||||
<span className="flex-none tabular-nums" style={{ color: DELAY_COLOR[card.delay.tone] }}>
|
||||
{card.delay.text}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{view.stage === 'airborne' && (
|
||||
<span className="-mx-[10px] -mb-[7px] mt-[6px] block h-[3px] bg-[color:var(--m-rowbr)]" aria-hidden="true">
|
||||
<span
|
||||
className="block h-full transition-[width] duration-700 motion-reduce:transition-none"
|
||||
style={{ width: `${Math.round(view.progress * 100)}%`, background: LIVE }}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{view.stage === 'airborne' && (
|
||||
<span
|
||||
className="block h-[3px] w-full overflow-hidden rounded-full bg-[color:var(--m-rowbr)]"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<span
|
||||
className="block h-full rounded-full transition-[width] duration-700 motion-reduce:transition-none"
|
||||
style={{ width: `${Math.round(view.progress * 100)}%`, background: LIVE }}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</Field>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -127,15 +127,12 @@ export default function MFlightLiveCard({ tripId, reservationId, legIndex, legLa
|
||||
showPlane={view.stage !== 'upcoming' && view.stage !== 'soon'}
|
||||
dimPlane={view.stale}
|
||||
credits={card.attribution ? [card.attribution, FLIGHT_MAP_CREDIT] : [FLIGHT_MAP_CREDIT]}
|
||||
inset={0.36}
|
||||
className="!absolute inset-0 [--fm-ahead:var(--m-muted)] [--fm-code:var(--m-muted)] [--fm-end:var(--m-inner)] [--fm-flown:var(--m-st-info)] [--fm-halo:var(--m-inner)] [--fm-plane:var(--m-st-info)]"
|
||||
inset={0.06}
|
||||
className="flight-mini-map--narrow !absolute inset-y-2 end-[25%] start-[25%] [--fm-ahead:var(--m-muted)] [--fm-code:var(--m-muted)] [--fm-end:var(--m-inner)] [--fm-flown:var(--m-st-info)] [--fm-halo:var(--m-inner)] [--fm-plane:var(--m-st-info)]"
|
||||
/>
|
||||
<End label={t('reservations.span.departure')} code={leg.origin.code} city={leg.origin.name} cell={card.dep} />
|
||||
<div className="relative z-[1] flex items-end justify-center">
|
||||
<span className="rounded-full bg-[color:var(--m-inner)] px-[7px] py-px font-geist text-caption font-bold tracking-[.06em] text-m-muted shadow-sm">
|
||||
{leg.flight_number}
|
||||
</span>
|
||||
</div>
|
||||
{/* The middle column keeps the map clear; the flight number is in the sheet's title already. */}
|
||||
<div aria-hidden="true" />
|
||||
<End
|
||||
label={t('reservations.span.arrival')}
|
||||
code={leg.destination.code}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { AlertCircle, Check } from 'lucide-react';
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
|
||||
interface MReviewNoticeProps {
|
||||
/** With the right to edit the booking: "Looks right" takes the mark off. */
|
||||
onConfirm?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone's counterpart of the review pill in the desktop dialog: an import
|
||||
* could not read every detail for sure, so the booking asks for a look. The
|
||||
* one action says it was checked; editing the booking works as always.
|
||||
*/
|
||||
export default function MReviewNotice({ onConfirm }: MReviewNoticeProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="mt-[14px] flex items-center gap-[10px] rounded-[14px] bg-[color-mix(in_srgb,var(--m-st-pending)_12%,transparent)] px-3 py-[10px]">
|
||||
<AlertCircle size={16} strokeWidth={2.2} className="flex-none text-[color:var(--m-st-pending)]" />
|
||||
<span className="min-w-0 flex-1 text-caption leading-snug text-m-ink">{t('reservations.needsReviewHint')}</span>
|
||||
{onConfirm && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onConfirm}
|
||||
className="flex h-[30px] flex-none items-center gap-1 rounded-full bg-[color:var(--m-inner)] px-[11px] font-geist text-caption font-bold text-m-ink shadow-sm"
|
||||
>
|
||||
<Check size={13} strokeWidth={2.4} />
|
||||
{t('reservations.reviewConfirm')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import { downloadAttachment, openAttachment } from '../../../../components/Plann
|
||||
import { flowText } from '../../../../utils/flowText'
|
||||
import { useFlightLiveLegs } from '../../../../store/flightLiveStore'
|
||||
import MFlightLiveCard from './MFlightLiveCard'
|
||||
import MReviewNotice from './MReviewNotice'
|
||||
|
||||
interface TransportSheetPayload {
|
||||
reservationId?: number
|
||||
@@ -231,6 +232,17 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
</div>
|
||||
|
||||
<div className="m-scroll-fade mt-2 min-h-0 flex-1 overflow-y-auto px-[18px] pb-[18px] pt-[14px]">
|
||||
{/* ── An import could not read every detail for sure ── */}
|
||||
{!!res.needs_review && (
|
||||
<MReviewNotice
|
||||
onConfirm={canEdit ? () => {
|
||||
planner.tripActions.updateReservation(planner.tripId, res.id, { needs_review: 0 })
|
||||
.then(() => planner.toast.success(t('reservations.reviewConfirmed')))
|
||||
.catch(() => planner.toast.error(t('reservations.toast.updateError')))
|
||||
} : undefined}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ── A stay: check-in, check-out, nights ── */}
|
||||
{hotelStats.length > 0 && (
|
||||
<div className="mt-[14px] flex gap-[6px]">
|
||||
|
||||
@@ -158,7 +158,7 @@ function TransportCard({ res, planner, shell, canEdit, compact }: {
|
||||
|
||||
{/* A flight TREK follows live: its moment in one line, on the compact card too. */}
|
||||
{res.type === 'flight' && (
|
||||
<MFlightLiveStrip tripId={planner.tripId} reservationId={res.id} onOpen={openDetail} className={compact ? 'mx-3 my-2' : 'mx-3 mt-[9px]'} />
|
||||
<MFlightLiveStrip tripId={planner.tripId} reservationId={res.id} onOpen={openDetail} className={compact ? 'mx-3 my-2 w-[calc(100%-24px)]' : 'mx-3 mt-[9px] w-[calc(100%-24px)]'} />
|
||||
)}
|
||||
|
||||
{/* Body — split around the booking code so the reveal can be its own
|
||||
|
||||
@@ -16,6 +16,7 @@ import GoogleOptions from './GoogleOptions'
|
||||
import GoogleDailyLimitRow from '../../components/Admin/GoogleDailyLimitRow'
|
||||
import ProviderBlock from './ProviderBlock'
|
||||
import TrekApiCard from './TrekApiCard'
|
||||
import MailIngestAdminCard from '../../components/Admin/mailIngest/MailIngestAdminCard'
|
||||
import PlaceContribPanel from '../../components/Admin/PlaceContribPanel'
|
||||
import { useAdminSettingsActions } from '../../components/Admin/useAdminSettingsActions'
|
||||
import { placesGoogleOnlyHint } from '../../utils/placeSource'
|
||||
@@ -391,6 +392,28 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R
|
||||
)}
|
||||
|
||||
{!managed && fileTypesCard}
|
||||
|
||||
{/* Live flight status: open ADS-B data, no key, on by default; the admin may keep it off. */}
|
||||
<SettingsCard icon={Plane} title={t('flightLive.adminTitle')} hint={managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')}>
|
||||
<SettingRows>
|
||||
<SettingRow
|
||||
label={t('flightLive.adminToggle')}
|
||||
hint={flightLiveLocked ? t('flightLive.envLocked') : undefined}
|
||||
control={
|
||||
<ToggleSwitch
|
||||
on={flightLive}
|
||||
label={t('flightLive.adminToggle')}
|
||||
disabled={flightLiveLocked}
|
||||
onToggle={() => void handleToggleAuthSetting('flight_live_enabled', !flightLive, setFlightLive)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SettingRows>
|
||||
</SettingsCard>
|
||||
|
||||
{/* Booking mail import: how forwarded booking mails reach this install. On a managed
|
||||
install the operator runs the TREK Cloud relay, so the card is not shown there. */}
|
||||
{!managed && <MailIngestAdminCard />}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
@@ -517,24 +540,6 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R
|
||||
</SettingsCard>
|
||||
)}
|
||||
|
||||
{/* Live flight status: open ADS-B data, no key, on by default; the admin may keep it off. */}
|
||||
<SettingsCard icon={Plane} title={t('flightLive.adminTitle')} hint={managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')}>
|
||||
<SettingRows>
|
||||
<SettingRow
|
||||
label={t('flightLive.adminToggle')}
|
||||
hint={flightLiveLocked ? t('flightLive.envLocked') : undefined}
|
||||
control={
|
||||
<ToggleSwitch
|
||||
on={flightLive}
|
||||
label={t('flightLive.adminToggle')}
|
||||
disabled={flightLiveLocked}
|
||||
onToggle={() => void handleToggleAuthSetting('flight_live_enabled', !flightLive, setFlightLive)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SettingRows>
|
||||
</SettingsCard>
|
||||
|
||||
{/* API Keys: only the keyed providers, Google, Unsplash and Amap. They are
|
||||
the operator's on a managed install, so the card is not shown there
|
||||
(server managed.ts), and neither is the provider pick in the card
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// FE-MAILINGEST-REPO-001 to FE-MAILINGEST-REPO-003
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../api/mailIngest', () => ({
|
||||
mailIngestApi: { inboxCount: vi.fn(), tripAddress: vi.fn(), adminSettings: vi.fn() },
|
||||
}));
|
||||
|
||||
import { mailIngestApi } from '../api/mailIngest';
|
||||
import { _resetNetworkMode, setForcedOffline } from '../sync/networkMode';
|
||||
import { mailIngestRepo } from './mailIngestRepo';
|
||||
import { OnlineOnlyError } from './onlineOnly';
|
||||
|
||||
afterEach(() => {
|
||||
_resetNetworkMode();
|
||||
vi.mocked(mailIngestApi.inboxCount).mockReset();
|
||||
});
|
||||
|
||||
describe('mailIngestRepo', () => {
|
||||
it('FE-MAILINGEST-REPO-001: answers parsed against the shared contract', async () => {
|
||||
vi.mocked(mailIngestApi.inboxCount).mockResolvedValue({ pending: 3 });
|
||||
vi.mocked(mailIngestApi.tripAddress).mockResolvedValue({ address: null });
|
||||
expect(await mailIngestRepo.inboxCount()).toBe(3);
|
||||
expect(await mailIngestRepo.tripAddress(7)).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-MAILINGEST-REPO-002: an answer of another shape fails here, not in the view', async () => {
|
||||
vi.mocked(mailIngestApi.inboxCount).mockResolvedValue({ pending: 'many' });
|
||||
await expect(mailIngestRepo.inboxCount()).rejects.toThrow();
|
||||
vi.mocked(mailIngestApi.adminSettings).mockResolvedValue(null);
|
||||
expect(await mailIngestRepo.adminSettings()).toEqual({});
|
||||
});
|
||||
|
||||
it('FE-MAILINGEST-REPO-003: offline nothing is asked, and the caller hears why', async () => {
|
||||
setForcedOffline(true);
|
||||
await expect(mailIngestRepo.inboxCount()).rejects.toBeInstanceOf(OnlineOnlyError);
|
||||
expect(mailIngestApi.inboxCount).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import {
|
||||
mailIngestAddressResponseSchema,
|
||||
mailIngestAdminStatusResponseSchema,
|
||||
mailIngestAdminTestResponseSchema,
|
||||
mailIngestCandidateResponseSchema,
|
||||
mailIngestInboxCountResponseSchema,
|
||||
mailIngestInboxResponseSchema,
|
||||
mailIngestMessagePreviewResponseSchema,
|
||||
mailIngestPrefillResponseSchema,
|
||||
mailIngestSettingsResponseSchema,
|
||||
mailIngestUploadResponseSchema,
|
||||
} from '@trek/shared';
|
||||
import { mailIngestApi, type MailIngestAction } from '../api/mailIngest';
|
||||
import { requireOnline } from './onlineOnly';
|
||||
|
||||
/**
|
||||
* The booking mail import: the person's settings and forwarding addresses,
|
||||
* the inbox of bookings read from forwarded mails, the actions on them, and
|
||||
* the admin's transport settings and status.
|
||||
*
|
||||
* **Deliberately online-only, and no Dexie table.** Every action asks the
|
||||
* server to decide (which trip, whether it is a duplicate, whether the mail
|
||||
* may still be undone), so there is nothing an offline copy could do.
|
||||
* Answers are parsed against the shared contracts rather than cast, so a
|
||||
* server that answered something else fails here, naming the field.
|
||||
*/
|
||||
export const mailIngestRepo = {
|
||||
async settings() {
|
||||
requireOnline();
|
||||
return mailIngestSettingsResponseSchema.parse(await mailIngestApi.settings());
|
||||
},
|
||||
|
||||
async updateSettings(body: { enabled?: boolean; ai_enabled?: boolean; auto_add?: boolean }) {
|
||||
requireOnline();
|
||||
return mailIngestSettingsResponseSchema.parse(await mailIngestApi.updateSettings(body));
|
||||
},
|
||||
|
||||
async renewAddress() {
|
||||
requireOnline();
|
||||
return mailIngestAddressResponseSchema.parse(await mailIngestApi.renewAddress());
|
||||
},
|
||||
|
||||
async tripAddress(tripId: number) {
|
||||
requireOnline();
|
||||
return mailIngestAddressResponseSchema.parse(await mailIngestApi.tripAddress(tripId)).address;
|
||||
},
|
||||
|
||||
async createTripAddress(tripId: number) {
|
||||
requireOnline();
|
||||
return mailIngestAddressResponseSchema.parse(await mailIngestApi.createTripAddress(tripId)).address;
|
||||
},
|
||||
|
||||
async inbox(before?: number) {
|
||||
requireOnline();
|
||||
return mailIngestInboxResponseSchema.parse(await mailIngestApi.inbox({ status: 'open', before }));
|
||||
},
|
||||
|
||||
async inboxCount() {
|
||||
requireOnline();
|
||||
return mailIngestInboxCountResponseSchema.parse(await mailIngestApi.inboxCount()).pending;
|
||||
},
|
||||
|
||||
async preview(messageId: number) {
|
||||
requireOnline();
|
||||
return mailIngestMessagePreviewResponseSchema.parse(await mailIngestApi.preview(messageId));
|
||||
},
|
||||
|
||||
async prefill(candidateId: number) {
|
||||
requireOnline();
|
||||
return mailIngestPrefillResponseSchema.parse(await mailIngestApi.prefill(candidateId));
|
||||
},
|
||||
|
||||
async act(candidateId: number, action: MailIngestAction, body: Record<string, unknown> = {}) {
|
||||
requireOnline();
|
||||
return mailIngestCandidateResponseSchema.parse(await mailIngestApi.act(candidateId, action, body)).candidate;
|
||||
},
|
||||
|
||||
async upload(file: File) {
|
||||
requireOnline();
|
||||
return mailIngestUploadResponseSchema.parse(await mailIngestApi.upload(file));
|
||||
},
|
||||
|
||||
async adminStatus() {
|
||||
requireOnline();
|
||||
return mailIngestAdminStatusResponseSchema.parse(await mailIngestApi.adminStatus());
|
||||
},
|
||||
|
||||
async adminTest() {
|
||||
requireOnline();
|
||||
return mailIngestAdminTestResponseSchema.parse(await mailIngestApi.adminTest());
|
||||
},
|
||||
|
||||
/** The admin's stored app settings (passwords masked), of which the mail form reads its own keys. */
|
||||
async adminSettings(): Promise<Record<string, unknown>> {
|
||||
requireOnline();
|
||||
const raw = await mailIngestApi.adminSettings();
|
||||
return raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
|
||||
},
|
||||
|
||||
async saveAdminSettings(patch: Record<string, string | boolean>) {
|
||||
requireOnline();
|
||||
await mailIngestApi.saveAdminSettings(patch);
|
||||
},
|
||||
};
|
||||
@@ -1,13 +1,18 @@
|
||||
// FE-STORE-MAILINGEST-001 to FE-STORE-MAILINGEST-004
|
||||
// FE-STORE-MAILINGEST-001 to FE-STORE-MAILINGEST-005
|
||||
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) }));
|
||||
const listeners = vi.hoisted(() => new Set<(event: Record<string, unknown>) => void>());
|
||||
vi.mock('../api/websocket', () => ({
|
||||
addListener: (fn: (event: Record<string, unknown>) => void) => listeners.add(fn),
|
||||
removeListener: (fn: (event: Record<string, unknown>) => void) => listeners.delete(fn),
|
||||
}));
|
||||
|
||||
import { mailIngestApi } from '../api/mailIngest';
|
||||
import { useMailIngestStore } from './mailIngestStore';
|
||||
import { useMailIngestStore, watchMailInbox } from './mailIngestStore';
|
||||
|
||||
const candidate = (id: number, resolution = 'pending') => ({
|
||||
id,
|
||||
@@ -79,8 +84,28 @@ describe('mailIngestStore', () => {
|
||||
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');
|
||||
await useMailIngestStore.getState().act(1, 'apply');
|
||||
expect(useMailIngestStore.getState().entries[0].reason).toBe('ai_provider_error');
|
||||
expect(useMailIngestStore.getState().pending).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-STORE-MAILINGEST-005: the server inbox events move the count, read the list again and reload the settings', async () => {
|
||||
vi.mocked(mailIngestApi.inbox).mockResolvedValue({ entries: [entry(3)], pending: 1, next_before: null });
|
||||
vi.mocked(mailIngestApi.settings).mockResolvedValue({ nope: true });
|
||||
const stop = watchMailInbox();
|
||||
const send = (event: Record<string, unknown>) => listeners.forEach((fn) => fn(event));
|
||||
|
||||
send({ type: 'mailInbox:changed', pending: 1 });
|
||||
expect(useMailIngestStore.getState().pending).toBe(1);
|
||||
await vi.waitFor(() => expect(useMailIngestStore.getState().entries.map((e) => e.id)).toEqual([3]));
|
||||
|
||||
send({ type: 'mailInbox:settings' });
|
||||
expect(mailIngestApi.settings).toHaveBeenCalled();
|
||||
|
||||
// A malformed event changes nothing, and after stopping nothing is heard.
|
||||
send({ type: 'mailInbox:changed', pending: 'many' });
|
||||
expect(useMailIngestStore.getState().pending).toBe(1);
|
||||
stop();
|
||||
expect(listeners.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
import {
|
||||
mailIngestCandidateResponseSchema,
|
||||
mailIngestInboxCountResponseSchema,
|
||||
mailIngestInboxResponseSchema,
|
||||
mailIngestSettingsResponseSchema,
|
||||
type MailIngestCandidate,
|
||||
type MailIngestInboxEntry,
|
||||
type MailIngestSettingsResponse,
|
||||
} from '@trek/shared';
|
||||
import type { MailIngestCandidate, MailIngestInboxEntry, MailIngestSettingsResponse } from '@trek/shared';
|
||||
import { create } from 'zustand';
|
||||
import { mailIngestApi, type MailIngestAction } from '../api/mailIngest';
|
||||
import type { MailIngestAction } from '../api/mailIngest';
|
||||
import { addListener, removeListener } from '../api/websocket';
|
||||
import { mailIngestRepo } from '../repo/mailIngestRepo';
|
||||
import { isEffectivelyOffline } from '../sync/networkMode';
|
||||
|
||||
/**
|
||||
@@ -43,16 +37,23 @@ export const useMailIngestStore = create<MailIngestState>((set, get) => ({
|
||||
|
||||
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 });
|
||||
try {
|
||||
const settings = await mailIngestRepo.settings();
|
||||
set({ settings, pending: settings.pending });
|
||||
} catch {
|
||||
// Without an answer the menus keep what they showed; the next sign-in or event reads it again.
|
||||
}
|
||||
},
|
||||
|
||||
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 });
|
||||
try {
|
||||
set({ pending: await mailIngestRepo.inboxCount() });
|
||||
} catch {
|
||||
// The badge keeps its last count until the next event brings a new one.
|
||||
}
|
||||
},
|
||||
|
||||
loadInbox: async (more = false) => {
|
||||
@@ -60,9 +61,7 @@ export const useMailIngestStore = create<MailIngestState>((set, get) => ({
|
||||
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;
|
||||
const { entries, pending, next_before } = await mailIngestRepo.inbox(before);
|
||||
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.
|
||||
@@ -72,7 +71,7 @@ export const useMailIngestStore = create<MailIngestState>((set, get) => ({
|
||||
},
|
||||
|
||||
act: async (candidateId, action, body = {}) => {
|
||||
const { candidate } = mailIngestCandidateResponseSchema.parse(await mailIngestApi.act(candidateId, action, body));
|
||||
const candidate = await mailIngestRepo.act(candidateId, action, body);
|
||||
set((state) => {
|
||||
const stillOpen = OPEN.has(candidate.resolution);
|
||||
const entries = state.entries.flatMap((entry) =>
|
||||
@@ -84,3 +83,24 @@ export const useMailIngestStore = create<MailIngestState>((set, get) => ({
|
||||
return candidate;
|
||||
},
|
||||
}));
|
||||
|
||||
/**
|
||||
* Keeps the inbox current while the app is open: the server says when the
|
||||
* person's open count changed (a mail read, an entry decided on another
|
||||
* device) and when their import settings did. The count moves at once; a
|
||||
* list already read is read again, so an open inbox shows the new entry
|
||||
* without a reload. Mounted once per signed-in shell (Navbar, MMailInboxHost).
|
||||
*/
|
||||
export function watchMailInbox(): () => void {
|
||||
const onEvent = (event: Record<string, unknown>) => {
|
||||
const store = useMailIngestStore.getState();
|
||||
if (event?.type === 'mailInbox:changed' && typeof event.pending === 'number') {
|
||||
useMailIngestStore.setState({ pending: event.pending });
|
||||
if (store.entries.length > 0 || event.pending > 0) void store.loadInbox();
|
||||
} else if (event?.type === 'mailInbox:settings') {
|
||||
void store.loadSettings();
|
||||
}
|
||||
};
|
||||
addListener(onEvent);
|
||||
return () => removeListener(onEvent);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user