mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 03:50:30 +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:
@@ -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>;
|
||||
Reference in New Issue
Block a user