feat(settings): preserve drafts and connection recovery
CI and Deploy / test (push) Failing after 4m27s
CI and Deploy / deploy (push) Has been skipped

This commit is contained in:
cesnimda
2026-10-17 10:50:40 +02:00
parent dac29278db
commit e7dba9a2f7
20 changed files with 3337 additions and 141 deletions
@@ -1,13 +1,27 @@
import React, { useCallback, useEffect, useRef, useState } from "react";
import { Box, Button, Checkbox, Chip, Divider, FormControlLabel, Paper, Stack, TextField, Typography } from "@mui/material";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import { Alert, Box, Button, Checkbox, Divider, FormControlLabel, Stack, TextField, Typography } from "@mui/material";
import { api, getApiErrorMessage } from "../api";
import { useI18n } from "../i18n/I18nProvider";
import { useToast } from "../toast";
import type { GmailStatus, ImapStatus, MicrosoftGraphStatus } from "../types";
import { emailOAuthCallbackOrigin, emailOAuthMessage, type EmailOAuthAttempt, type EmailOAuthProvider } from "../emailOAuth";
import { PageSection } from "../layout/PageLayout";
type Provider = EmailOAuthProvider | "imap";
type ConnectionStatus = GmailStatus & MicrosoftGraphStatus & ImapStatus;
type ProviderState = {
status: ConnectionStatus | null;
loading: boolean;
readFailed: boolean;
refreshRequired: boolean;
busy: "connect" | "disconnect" | null;
error: { kind: "disconnect" | "imap"; cause: unknown } | null;
};
const providerPaths = { gmail: "/gmail", microsoft: "/microsoft-graph", imap: "/imap" };
const initialProvider = (): ProviderState => ({ status: null, loading: true, readFailed: false, refreshRequired: false, busy: null, error: null });
const providerWork = () => ({ reading: false, writing: false, refreshRequired: false, sequence: 0, controller: null as AbortController | null, status: null as ConnectionStatus | null });
// Settings > Account: connect/disconnect each linked-mailbox provider. Gmail and Microsoft use
// the same OAuth-popup + postMessage handshake (mirrored server-side in GmailController /
@@ -17,49 +31,74 @@ export default function EmailProviderConnections() {
const { toast } = useToast();
const { t } = useI18n();
const [gmailStatus, setGmailStatus] = useState<GmailStatus | null>(null);
const [microsoftStatus, setMicrosoftStatus] = useState<MicrosoftGraphStatus | null>(null);
const [imapStatus, setImapStatus] = useState<ImapStatus | null>(null);
const [imapForm, setImapForm] = useState({ host: "", port: 993, useSsl: true, username: "", password: "" });
const [imapConnecting, setImapConnecting] = useState(false);
const [providers, setProviders] = useState({ gmail: initialProvider(), microsoft: initialProvider(), imap: initialProvider() });
const work = useRef({ gmail: providerWork(), microsoft: providerWork(), imap: providerWork() });
const headings = useRef<Partial<Record<Provider, HTMLHeadingElement | null>>>({});
const panels = useRef<Partial<Record<Provider, HTMLElement | null>>>({});
const pendingFocus = useRef<{ provider: Provider; element: HTMLElement } | null>(null);
const [imapForm, setImapForm] = useState({ host: "", port: "993", useSsl: true, username: "", password: "" });
const [invalidPort, setInvalidPort] = useState(false);
const oauth = useRef({ mounted: true, generation: 0, starting: new Set<EmailOAuthProvider>(), attempts: new Map<EmailOAuthProvider, EmailOAuthAttempt>() });
const startupTranslation = useRef(t);
useEffect(() => { startupTranslation.current = t; }, [t]);
const updateProvider = useCallback((provider: Provider, patch: Partial<ProviderState>) => {
setProviders(current => ({ ...current, [provider]: { ...current[provider], ...patch } }));
}, []);
const rememberFocus = (provider: Provider) => {
const element = document.activeElement;
if (element instanceof HTMLElement && panels.current[provider]?.contains(element)) pendingFocus.current = { provider, element };
};
useEffect(() => {
const pending = pendingFocus.current;
if (!pending) return;
pendingFocus.current = null;
const active = document.activeElement;
if (active === document.body || active === pending.element && (pending.element.matches(":disabled") || !pending.element.isConnected)) headings.current[pending.provider]?.focus();
}, [providers]);
useEffect(() => {
const session = oauth.current;
const providerSessions = work.current;
session.mounted = true;
return () => { session.mounted = false; session.generation += 1; session.starting.clear(); session.attempts.clear(); };
return () => {
session.mounted = false; session.generation += 1; session.starting.clear(); session.attempts.clear();
for (const provider of Object.values(providerSessions)) { provider.sequence += 1; provider.controller?.abort(); provider.reading = false; }
};
}, []);
const loadGmailStatus = useCallback(async () => {
const loadStatus = useCallback(async (provider: Provider, afterWrite = false): Promise<ConnectionStatus | null> => {
const session = oauth.current;
const current = work.current[provider];
if (!session.mounted || current.reading || current.writing && !afterWrite) return null;
current.reading = true;
const sequence = ++current.sequence;
const generation = session.generation;
const controller = new AbortController();
current.controller = controller;
updateProvider(provider, { loading: true, readFailed: false });
const active = () => session.mounted && generation === session.generation && sequence === current.sequence;
try {
const res = await api.get<GmailStatus>("/gmail/status");
setGmailStatus(res.data);
const { data } = await api.get<ConnectionStatus>(`${providerPaths[provider]}/status`, { signal: controller.signal });
if (!active()) return null;
if (typeof data?.connected !== "boolean") throw new Error("Invalid connection status");
current.status = data;
current.refreshRequired = false;
updateProvider(provider, { status: data, readFailed: false, refreshRequired: false });
return data;
} catch {
setGmailStatus({ connected: false });
if (active()) updateProvider(provider, { readFailed: true });
return null;
} finally {
if (active()) { current.reading = false; current.controller = null; updateProvider(provider, { loading: false }); }
}
}, []);
const loadMicrosoftStatus = useCallback(async () => {
try {
const res = await api.get<MicrosoftGraphStatus>("/microsoft-graph/status");
setMicrosoftStatus(res.data);
} catch {
setMicrosoftStatus({ connected: false });
}
}, []);
const loadImapStatus = useCallback(async () => {
try {
const res = await api.get<ImapStatus>("/imap/status");
setImapStatus(res.data);
} catch {
setImapStatus({ connected: false });
}
}, []);
}, [updateProvider]);
const loadGmailStatus = useCallback(async () => { await loadStatus("gmail"); }, [loadStatus]);
const loadMicrosoftStatus = useCallback(async () => { await loadStatus("microsoft"); }, [loadStatus]);
const loadImapStatus = useCallback(async () => { await loadStatus("imap"); }, [loadStatus]);
useEffect(() => {
void loadGmailStatus();
@@ -90,11 +129,14 @@ export default function EmailProviderConnections() {
const connectViaPopup = async (provider: EmailOAuthProvider, connectUrlPath: string, popupName: string, providerLabel: string) => {
const session = oauth.current;
if (!session.mounted || session.starting.has(provider)) return;
const current = work.current[provider];
if (!session.mounted || session.starting.has(provider) || current.reading || current.writing || current.refreshRequired || !current.status || current.status.connected) return;
const previous = session.attempts.get(provider);
if (previous && !previous.popup.closed) { previous.popup.focus(); return; }
session.attempts.delete(provider);
session.starting.add(provider);
rememberFocus(provider);
updateProvider(provider, { busy: "connect", error: null });
const generation = session.generation;
try {
const res = await api.get<{ url: string }>(connectUrlPath);
@@ -107,75 +149,115 @@ export default function EmailProviderConnections() {
} catch (error) {
if (session.mounted && generation === session.generation) toast(getApiErrorMessage(error, startupTranslation.current("emailConnectionsStartFailed", { provider: providerLabel })), "error");
} finally {
if (generation === session.generation) session.starting.delete(provider);
if (session.mounted && generation === session.generation) { session.starting.delete(provider); updateProvider(provider, { busy: null }); }
}
};
const disconnect = async (path: string, reload: () => Promise<void>, providerLabel: string) => {
const disconnect = async (provider: Provider, providerLabel: string) => {
const session = oauth.current;
const current = work.current[provider];
if (!session.mounted || current.reading || current.writing || current.refreshRequired || !current.status?.connected || provider !== "imap" && session.starting.has(provider)) return;
current.writing = true;
const generation = session.generation;
rememberFocus(provider);
updateProvider(provider, { busy: "disconnect", error: null });
try {
await api.delete(path);
await reload();
toast(t("emailConnectionsDisconnected", { provider: providerLabel }), "success");
await api.delete(`${providerPaths[provider]}/connection`);
if (!session.mounted || generation !== session.generation) return;
current.status = null;
current.refreshRequired = true;
updateProvider(provider, { status: null, refreshRequired: true });
const status = await loadStatus(provider, true);
if (session.mounted && generation === session.generation && status && !status.connected) toast(startupTranslation.current("emailConnectionsDisconnected", { provider: providerLabel }), "success");
} catch (error) {
toast(getApiErrorMessage(error, t("emailConnectionsDisconnectFailed", { provider: providerLabel })), "error");
if (session.mounted && generation === session.generation) updateProvider(provider, { error: { kind: "disconnect", cause: error } });
} finally {
if (session.mounted && generation === session.generation) { current.writing = false; updateProvider(provider, { busy: null }); }
}
};
const connectImap = async () => {
const session = oauth.current;
const current = work.current.imap;
if (!session.mounted || current.reading || current.writing || current.refreshRequired || !current.status || current.status.connected) return;
if (!imapForm.host.trim() || !imapForm.username.trim() || !imapForm.password) {
toast(t("emailConnectionsRequired"), "error");
return;
}
setImapConnecting(true);
const port = Number(imapForm.port);
if (!imapForm.port.trim() || !Number.isInteger(port) || port < 1 || port > 65535) { setInvalidPort(true); return; }
const submitted = { ...imapForm };
current.writing = true;
const generation = session.generation;
rememberFocus("imap");
updateProvider("imap", { busy: "connect", error: null });
try {
await api.post("/imap/connect", imapForm);
setImapForm((prev) => ({ ...prev, password: "" }));
await loadImapStatus();
toast(t("emailConnectionsImapConnected"), "success");
await api.post("/imap/connect", { ...submitted, port });
if (!session.mounted || generation !== session.generation) return;
rememberFocus("imap");
// A completed submission must not clear credentials edited for another attempt.
setImapForm(previous => Object.keys(submitted).every(key => previous[key as keyof typeof previous] === submitted[key as keyof typeof submitted]) ? { ...previous, password: "" } : previous);
current.status = null;
current.refreshRequired = true;
updateProvider("imap", { status: null, refreshRequired: true });
const status = await loadStatus("imap", true);
if (session.mounted && generation === session.generation && status?.connected) toast(startupTranslation.current("emailConnectionsImapConnected"), "success");
} catch (error) {
toast(getApiErrorMessage(error, t("emailConnectionsImapFailed")), "error");
if (session.mounted && generation === session.generation) updateProvider("imap", { error: { kind: "imap", cause: error } });
} finally {
setImapConnecting(false);
if (session.mounted && generation === session.generation) { current.writing = false; updateProvider("imap", { busy: null }); }
}
};
return (
<Paper sx={{ p: 2 }}>
<Typography sx={{ fontWeight: 950, mb: 0.5 }}>{t("emailConnectionsTitle")}</Typography>
<Typography sx={{ color: "text.secondary", mb: 2 }}>
{t("emailConnectionsBody")}
</Typography>
const providerFeedback = (provider: Provider, providerLabel: string) => {
const state = providers[provider];
return <>
{state.loading ? <Typography role="status" variant="body2" color="text.secondary">{t("emailConnectionsLoading")}</Typography> : null}
{state.readFailed ? <Alert severity="error" action={<Button color="inherit" onClick={() => { rememberFocus(provider); void loadStatus(provider); }}>{t("retry")}</Button>}>
{t(state.refreshRequired ? "emailConnectionsRefreshRequired" : "emailConnectionsStatusFailed")}
</Alert> : null}
{state.error ? <Alert severity="error">{getApiErrorMessage(state.error.cause, t(state.error.kind === "imap" ? "emailConnectionsImapFailed" : "emailConnectionsDisconnectFailed", { provider: providerLabel }))}</Alert> : null}
</>;
};
return (
<PageSection surface title={t("emailConnectionsTitle")} description={t("emailConnectionsBody")}>
<Stack spacing={2}>
<ProviderRow
label="Gmail"
connected={Boolean(gmailStatus?.connected)}
address={gmailStatus?.gmailAddress ?? null}
state={providers.gmail}
address={providers.gmail.status?.gmailAddress ?? null}
panelRef={node => { panels.current.gmail = node; }}
headingRef={node => { headings.current.gmail = node; }}
onConnect={() => void connectViaPopup("gmail", "/gmail/connect-url", "jobtracker-gmail-connect", "Gmail")}
onDisconnect={() => void disconnect("/gmail/connection", loadGmailStatus, "Gmail")}
/>
onDisconnect={() => void disconnect("gmail", "Gmail")}
>{providerFeedback("gmail", "Gmail")}</ProviderRow>
<Divider />
<ProviderRow
label="Outlook / Microsoft 365"
connected={Boolean(microsoftStatus?.connected)}
address={microsoftStatus?.mailAddress ?? null}
state={providers.microsoft}
address={providers.microsoft.status?.mailAddress ?? null}
panelRef={node => { panels.current.microsoft = node; }}
headingRef={node => { headings.current.microsoft = node; }}
onConnect={() => void connectViaPopup("microsoft", "/microsoft-graph/connect-url", "jobtracker-microsoft-connect", "Outlook")}
onDisconnect={() => void disconnect("/microsoft-graph/connection", loadMicrosoftStatus, "Outlook")}
/>
onDisconnect={() => void disconnect("microsoft", "Outlook")}
>{providerFeedback("microsoft", "Outlook")}</ProviderRow>
<Divider />
<Box>
<ProviderRow
<ProviderRow
label={t("emailConnectionsOtherImap")}
connected={Boolean(imapStatus?.connected)}
address={imapStatus?.username ?? null}
onDisconnect={() => void disconnect("/imap/connection", loadImapStatus, "IMAP")}
/>
{!imapStatus?.connected && (
<Box sx={{ mt: 1.5, display: "grid", gap: 1.25, gridTemplateColumns: { xs: "1fr", sm: "2fr 1fr" }, maxWidth: 520 }}>
state={providers.imap}
address={providers.imap.status?.username ?? null}
panelRef={node => { panels.current.imap = node; }}
headingRef={node => { headings.current.imap = node; }}
onDisconnect={() => void disconnect("imap", "IMAP")}
>
{providerFeedback("imap", "IMAP")}
{providers.imap.status && !providers.imap.status.connected && !providers.imap.readFailed && !providers.imap.refreshRequired && (
<Box sx={{ display: "grid", gap: 1.5, gridTemplateColumns: { xs: "minmax(0, 1fr)", sm: "minmax(0, 2fr) minmax(0, 1fr)" }, maxWidth: 640 }}>
<TextField
size="small"
label={t("emailConnectionsImapHost")}
@@ -188,7 +270,10 @@ export default function EmailProviderConnections() {
label={t("emailConnectionsPort")}
type="number"
value={imapForm.port}
onChange={(e) => setImapForm((prev) => ({ ...prev, port: Number(e.target.value) || 993 }))}
error={invalidPort}
helperText={invalidPort ? t("emailConnectionsPortInvalid") : undefined}
slotProps={{ htmlInput: { min: 1, max: 65535, step: 1 } }}
onChange={(e) => { setImapForm((prev) => ({ ...prev, port: e.target.value })); setInvalidPort(false); }}
/>
<TextField
size="small"
@@ -213,55 +298,57 @@ export default function EmailProviderConnections() {
<Button
variant="contained"
onClick={connectImap}
disabled={imapConnecting}
sx={{ gridColumn: "1 / -1", justifySelf: "start" }}
disabled={providers.imap.loading || providers.imap.busy !== null}
sx={{ gridColumn: "1 / -1", justifySelf: "start", maxWidth: "100%", whiteSpace: "normal", minHeight: 40 }}
>
{imapConnecting ? t("emailConnectionsConnecting") : t("emailConnectionsConnectImap")}
{providers.imap.busy === "connect" ? t("emailConnectionsConnecting") : t("emailConnectionsConnectImap")}
</Button>
</Box>
)}
</Box>
</ProviderRow>
</Stack>
</Paper>
</PageSection>
);
}
function ProviderRow({
label,
connected,
state,
address,
panelRef,
headingRef,
onConnect,
onDisconnect,
children,
}: {
label: string;
connected: boolean;
state: ProviderState;
address: string | null;
panelRef: (node: HTMLElement | null) => void;
headingRef: (node: HTMLHeadingElement | null) => void;
onConnect?: () => void;
onDisconnect: () => void;
children: React.ReactNode;
}) {
const { t } = useI18n();
return (
<Stack direction="row" alignItems="center" justifyContent="space-between" flexWrap="wrap" gap={1}>
<Box>
<Typography sx={{ fontWeight: 700 }}>{label}</Typography>
{connected ? (
<Chip
size="small"
icon={<CheckCircleIcon fontSize="small" />}
color="success"
variant="outlined"
label={address || t("emailConnectionsConnected")}
sx={{ mt: 0.5 }}
/>
) : (
<Typography variant="caption" sx={{ color: "text.secondary" }}>{t("emailConnectionsNotConnected")}</Typography>
)}
</Box>
{connected ? (
<Button size="small" variant="outlined" color="error" onClick={onDisconnect}>{t("emailConnectionsDisconnect")}</Button>
) : (
onConnect && <Button size="small" variant="outlined" onClick={onConnect}>{t("emailConnectionsConnect")}</Button>
)}
</Stack>
<Box component="section" aria-label={label} ref={panelRef} aria-busy={state.loading || state.busy !== null} sx={{ display: "grid", gap: 1.5, minWidth: 0 }}>
<Stack direction="row" alignItems="center" justifyContent="space-between" flexWrap="wrap" gap={1} sx={{ minWidth: 0 }}>
<Box sx={{ flex: "1 1 12rem", minWidth: 0 }}>
<Typography component="h3" variant="subtitle1" ref={headingRef} tabIndex={-1} sx={{ fontWeight: 700, overflowWrap: "anywhere" }}>{label}</Typography>
{state.status && !state.loading && !state.readFailed && !state.refreshRequired ? <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5, overflowWrap: "anywhere" }}>
{state.status.connected ? address || t("emailConnectionsConnected") : t("emailConnectionsNotConnected")}
</Typography> : null}
</Box>
{state.status && !state.readFailed && !state.refreshRequired ? state.status.connected ? (
<Button variant="outlined" color="error" disabled={state.loading || state.busy !== null} onClick={onDisconnect} sx={{ minHeight: 40, maxWidth: "100%", whiteSpace: "normal" }}>
{state.busy === "disconnect" ? t("emailConnectionsDisconnecting") : t("emailConnectionsDisconnect")}
</Button>
) : onConnect ? <Button variant="outlined" disabled={state.loading || state.busy !== null} onClick={onConnect} sx={{ minHeight: 40, maxWidth: "100%", whiteSpace: "normal" }}>
{state.busy === "connect" ? t("emailConnectionsConnecting") : t("emailConnectionsConnect")}
</Button> : null : null}
</Stack>
{children}
</Box>
);
}
+98 -24
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState } from "react";
import React, { useCallback, useEffect, useRef, useState } from "react";
import {
Box,
@@ -10,7 +10,6 @@ import {
InputLabel,
MenuItem,
Select,
Skeleton,
Tab,
Tabs,
Typography,
@@ -30,6 +29,7 @@ import { useI18n } from "../i18n/I18nProvider";
import { api, getApiErrorMessage } from "../api";
import { useToast } from "../toast";
import { PageSection } from "../layout/PageLayout";
import ViewStateNotice from "./ViewStateNotice";
interface Props {
pageSize: 15 | 20 | 25;
@@ -66,21 +66,38 @@ export default function SettingsView({
const { language, setLanguage, t } = useI18n();
const { toast } = useToast();
const [notificationPrefs, setNotificationPrefs] = useState<NotificationPrefs | null>(null);
const [notificationError, setNotificationError] = useState<string | null>(null);
const [savedNotificationPrefs, setSavedNotificationPrefs] = useState<NotificationPrefs | null>(null);
const [notificationError, setNotificationError] = useState<{ cause: unknown; action: boolean } | null>(null);
const [loadingNotifications, setLoadingNotifications] = useState(true);
const [savingNotifications, setSavingNotifications] = useState(false);
const [savedRules, setSavedRules] = useState<RuleSettings | null>(null);
const [rulesDraft, setRulesDraft] = useState<RuleDraft | null>(null);
const [rulesLoadError, setRulesLoadError] = useState<string | null>(null);
const [rulesLoadError, setRulesLoadError] = useState<{ cause: unknown } | null>(null);
const [rulesSaveError, setRulesSaveError] = useState(false);
const [invalidRules, setInvalidRules] = useState<RuleField[]>([]);
const [savingRules, setSavingRules] = useState(false);
const rulesSession = useRef({ mounted: true, loading: false, saving: false });
const notificationSession = useRef({ mounted: true, loading: false, saving: false, generation: 0 });
const notificationBody = useRef<HTMLDivElement>(null);
const notificationRetryFocus = useRef<HTMLElement | null>(null);
const currentTranslation = useRef(t);
const rulesDirty = Boolean(rulesDraft && savedRules && RULE_FIELDS.some(field => rulesDraft[field] !== String(savedRules[field])));
const notificationsDirty = Boolean(notificationPrefs && savedNotificationPrefs && notificationPrefs.emailFollowUpRemindersEnabled !== savedNotificationPrefs.emailFollowUpRemindersEnabled);
useEffect(() => { currentTranslation.current = t; }, [t]);
useEffect(() => {
const session = rulesSession.current;
const notifications = notificationSession.current;
session.mounted = true;
return () => { session.mounted = false; };
notifications.mounted = true;
return () => {
session.mounted = false;
notifications.mounted = false;
notifications.generation += 1;
notifications.loading = false;
notifications.saving = false;
};
}, []);
const loadRules = async () => {
@@ -94,7 +111,7 @@ export default function SettingsView({
setSavedRules(data);
setRulesDraft(ruleDraft(data));
} catch (error) {
if (session.mounted) setRulesLoadError(getApiErrorMessage(error, t("rulesLoadFailed")));
if (session.mounted) setRulesLoadError({ cause: error });
} finally { session.loading = false; }
};
@@ -120,7 +137,7 @@ export default function SettingsView({
setSavedRules(submitted);
// A completed save acknowledges its snapshot, not edits made while it was pending.
setRulesDraft(current => current && RULE_FIELDS.every(field => current[field] === submittedDraft[field]) ? ruleDraft(submitted) : current);
toast(t("rulesSaved"), "success");
toast(currentTranslation.current("rulesSaved"), "success");
} catch {
if (session.mounted) setRulesSaveError(true);
} finally {
@@ -136,27 +153,74 @@ export default function SettingsView({
setRulesSaveError(false);
};
const loadNotifications = useCallback(async () => {
const session = notificationSession.current;
if (!session.mounted || session.loading) return;
const generation = session.generation;
session.loading = true;
setLoadingNotifications(true);
setNotificationError(null);
try {
const { data } = await api.get<NotificationPrefs>("/notification-settings");
if (!session.mounted || generation !== session.generation) return;
setNotificationPrefs(data);
setSavedNotificationPrefs(data);
} catch (cause) {
if (session.mounted && generation === session.generation) setNotificationError({ cause, action: false });
} finally {
if (generation === session.generation) {
session.loading = false;
if (session.mounted) setLoadingNotifications(false);
}
}
}, []);
useEffect(() => { void loadNotifications(); }, [loadNotifications]);
const retryNotifications = () => {
const active = document.activeElement;
if (active instanceof HTMLElement && notificationBody.current?.contains(active)) notificationRetryFocus.current = active;
void loadNotifications();
};
useEffect(() => {
let active = true;
api.get<NotificationPrefs>("/notification-settings")
.then(({ data }) => { if (active) setNotificationPrefs(data); })
.catch((error) => { if (active) setNotificationError(getApiErrorMessage(error, t("settingsNotificationsLoadFailed"))); });
return () => { active = false; };
}, [t]);
const target = notificationRetryFocus.current;
if (loadingNotifications || !target) return;
notificationRetryFocus.current = null;
if (!target.isConnected && document.activeElement === document.body) notificationBody.current?.focus();
}, [loadingNotifications, notificationError, notificationPrefs]);
const saveNotifications = async () => {
if (!notificationPrefs) return;
const session = notificationSession.current;
if (!session.mounted || !notificationPrefs || session.saving) return;
const submitted = { emailFollowUpRemindersEnabled: notificationPrefs.emailFollowUpRemindersEnabled };
const generation = session.generation;
session.saving = true;
setSavingNotifications(true);
setNotificationError(null);
try {
const { data } = await api.put<NotificationPrefs>("/notification-settings", notificationPrefs);
setNotificationPrefs(data);
toast(t("settingsNotificationsSaved"), "success");
} catch (error) {
setNotificationError(getApiErrorMessage(error, t("settingsNotificationsSaveFailed")));
} finally { setSavingNotifications(false); }
const { data } = await api.put<NotificationPrefs>("/notification-settings", submitted);
if (!session.mounted || generation !== session.generation) return;
setSavedNotificationPrefs(data);
setNotificationPrefs(current => current?.emailFollowUpRemindersEnabled === submitted.emailFollowUpRemindersEnabled ? data : current);
toast(currentTranslation.current("settingsNotificationsSaved"), "success");
} catch (cause) {
if (session.mounted && generation === session.generation) setNotificationError({ cause, action: true });
} finally {
if (generation === session.generation) {
session.saving = false;
if (session.mounted) setSavingNotifications(false);
}
}
};
const discardNotifications = () => {
if (!savedNotificationPrefs || notificationSession.current.saving) return;
setNotificationPrefs(savedNotificationPrefs);
setNotificationError(null);
};
const notificationReadStatus = (notificationError?.cause as { response?: { status?: number } } | undefined)?.response?.status;
return (
<Box sx={{ minWidth: 0 }}>
<FormControl fullWidth sx={{ display: { xs: "flex", sm: "none" }, mb: 1 }}>
@@ -274,7 +338,7 @@ export default function SettingsView({
</TabPanel>
<TabPanel value={tab} index={1} label={t("settingsTabFollowUps")}>
<RulesSettingsCard draft={rulesDraft} loadError={rulesLoadError} saveError={rulesSaveError} invalid={invalidRules}
<RulesSettingsCard draft={rulesDraft} loadError={rulesLoadError ? getApiErrorMessage(rulesLoadError.cause, t("rulesLoadFailed")) : null} saveError={rulesSaveError} invalid={invalidRules}
saving={savingRules} dirty={rulesDirty} onSave={() => void saveRules()} onRetry={() => void loadRules()} onDiscard={discardRules}
onChange={(field, value) => {
setRulesDraft(current => current ? { ...current, [field]: value } : current);
@@ -284,15 +348,25 @@ export default function SettingsView({
<TabPanel value={tab} index={2} label={t("settingsTabNotifications")}>
<PageSection surface title={t("settingsNotificationsTitle")} description={t("settingsNotificationsBody")}>
{notificationError ? <Alert severity="error" sx={{ mb: 1.5 }}>{notificationError}</Alert> : null}
{!notificationPrefs ? <Skeleton variant="rounded" height={70} /> : <Box sx={{ display: "grid", gap: 1 }}>
<Box ref={notificationBody} role="group" aria-label={t("settingsNotificationsTitle")} tabIndex={-1} aria-busy={loadingNotifications || savingNotifications} sx={{ minWidth: 0 }}>
{!notificationPrefs ? <ViewStateNotice compact loading={loadingNotifications} title={t("settingsNotificationsLoadFailed")} error={notificationError ? {
kind: notificationReadStatus === 401 || notificationReadStatus === 403 ? "unauthorized" : "error",
message: getApiErrorMessage(notificationError.cause, t("settingsNotificationsLoadFailed")),
retryable: notificationReadStatus !== 401 && notificationReadStatus !== 403,
} : null} onRetry={retryNotifications} /> : <Box sx={{ display: "grid", gap: 1 }}>
{notificationError?.action ? <Alert severity="error" sx={{ mb: 1.5, overflowWrap: "anywhere" }}>{getApiErrorMessage(notificationError.cause, t("settingsNotificationsSaveFailed"))}</Alert> : null}
{notificationsDirty ? <Typography role="status" variant="body2" color="text.secondary">{t("assetsUnsavedChanges")}. {t("settingsNotificationsDraftScope")}</Typography> : null}
<FormControlLabel
control={<Checkbox checked={notificationPrefs.emailFollowUpRemindersEnabled} onChange={(e) => setNotificationPrefs({ emailFollowUpRemindersEnabled: e.target.checked })} />}
label={t("settingsNotificationsFollowUpReminders")}
/>
<Typography variant="caption" color="text.secondary">{t("settingsNotificationsEmailBody")}</Typography>
<Box><Button variant="contained" disabled={savingNotifications} onClick={() => void saveNotifications()}>{savingNotifications ? t("settingsSaving") : t("settingsNotificationsSave")}</Button></Box>
<Box sx={{ display: "flex", flexWrap: "wrap", gap: 1 }}>
<Button disabled={!notificationsDirty || savingNotifications} onClick={discardNotifications}>{t("assetsDiscardChanges")}</Button>
<Button variant="contained" disabled={savingNotifications} onClick={() => void saveNotifications()}>{savingNotifications ? t("settingsSaving") : t("settingsNotificationsSave")}</Button>
</Box>
</Box>}
</Box>
<Typography variant="caption" sx={{ color: "text.secondary", display: "block", mt: 1.5 }}>
{t("settingsNotificationsDelivery")}
</Typography>
@@ -62,6 +62,8 @@ describe("EmailProviderConnections", () => {
beforeEach(() => {
jest.clearAllMocks();
mockedApi.get.mockReset();
mockedApi.post.mockReset();
mockedApi.delete.mockReset();
window.localStorage.clear();
});
@@ -108,13 +110,14 @@ describe("EmailProviderConnections", () => {
await userEvent.type(screen.getByLabelText("IMAP host"), "imap.example.test");
await userEvent.type(screen.getByLabelText("Username"), "user@example.test");
await userEvent.type(screen.getByLabelText("Password"), "secret");
await userEvent.click(screen.getByRole("button", { name: /connect imap account/i }));
await act(async () => { await userEvent.click(screen.getByRole("button", { name: /connect imap account/i })); });
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledWith("/imap/connect", expect.objectContaining({
host: "imap.example.test",
username: "user@example.test",
password: "secret",
})));
await waitFor(() => expect(statusReads()).toHaveLength(4));
});
it("[P7-09 OAuth] unsolicited success and error messages cannot announce or refresh any connection", async () => {
@@ -221,4 +224,207 @@ describe("EmailProviderConnections", () => {
expect(window.open).toHaveBeenCalledTimes(outcome === "blocked" ? 1 : 0);
expect(mockedApi.post).not.toHaveBeenCalled(); expect(mockedApi.delete).not.toHaveBeenCalled();
});
it("[P7-09 Connections] unknown and failed provider reads remain truthful and Retry reads only that provider once", async () => {
const initial = deferred<any>(); const retry = deferred<any>(); let gmailReads = 0;
mockedApi.get.mockImplementation((url: string) => url === "/gmail/status"
? (++gmailReads === 1 ? initial.promise : retry.promise)
: Promise.resolve({ data: { connected: false } } as any));
renderComponent(); await screen.findByLabelText("IMAP host");
const gmail = screen.getByRole("region", { name: "Gmail" });
expect(within(gmail).getByText(translations.en.emailConnectionsLoading)).toBeVisible();
expect(within(gmail).queryByText("Not connected")).not.toBeInTheDocument();
expect(within(gmail).queryByRole("button", { name: "Connect" })).not.toBeInTheDocument();
await act(async () => initial.reject(new Error("offline")));
expect(within(gmail).getByRole("alert")).toHaveTextContent(translations.en.emailConnectionsStatusFailed);
expect(within(gmail).queryByText("Not connected")).not.toBeInTheDocument();
const button = within(gmail).getByRole("button", { name: translations.en.retry });
act(() => { fireEvent.click(button); fireEvent.click(button); });
expect(mockedApi.get.mock.calls.filter(([url]) => url === "/gmail/status")).toHaveLength(2);
expect(mockedApi.get.mock.calls.filter(([url]) => url === "/microsoft-graph/status")).toHaveLength(1);
expect(mockedApi.get.mock.calls.filter(([url]) => url === "/imap/status")).toHaveLength(1);
await act(async () => retry.resolve({ data: { connected: false } }));
expect(within(gmail).getByText("Not connected")).toBeVisible();
expect(within(gmail).getByRole("button", { name: "Connect" })).toBeEnabled();
expect(mockedApi.post).not.toHaveBeenCalled(); expect(mockedApi.delete).not.toHaveBeenCalled();
});
it("[P7-09 Connections] a held status read follows the current language without a locale refetch", async () => {
const pending = deferred<any>();
mockedApi.get.mockImplementation((url: string) => url === "/gmail/status" ? pending.promise : Promise.resolve({ data: { connected: false } } as any));
renderComponent(); await screen.findByLabelText("IMAP host");
await act(async () => { window.dispatchEvent(new StorageEvent("storage", { key: "uiLanguage", newValue: "nb" })); });
await act(async () => pending.reject(new Error("offline")));
expect(within(screen.getByRole("region", { name: "Gmail" })).getByRole("alert")).toHaveTextContent(translations.nb.emailConnectionsStatusFailed);
expect(screen.queryByText(translations.en.emailConnectionsStatusFailed)).not.toBeInTheDocument();
expect(statusReads()).toHaveLength(3);
});
it("[P7-09 Connections] a committed disconnect with failed refresh blocks writes until GET-only recovery", async () => {
const pending = deferred<any>(); let reads = 0;
mockedApi.get.mockImplementation((url: string) => {
if (url !== "/gmail/status") return Promise.resolve({ data: { connected: false } } as any);
reads += 1;
return reads === 1 ? Promise.resolve({ data: { connected: true, gmailAddress: "owner@example.test" } } as any)
: reads === 2 ? Promise.reject(new Error("refresh offline")) : Promise.resolve({ data: { connected: false } } as any);
});
mockedApi.delete.mockReturnValue(pending.promise);
renderComponent(); await screen.findByText("owner@example.test");
const gmail = screen.getByRole("region", { name: "Gmail" });
const disconnect = within(gmail).getByRole("button", { name: "Disconnect" });
act(() => { fireEvent.click(disconnect); fireEvent.click(disconnect); });
expect(mockedApi.delete).toHaveBeenCalledTimes(1);
expect(mockedApi.delete).toHaveBeenCalledWith("/gmail/connection");
await act(async () => pending.resolve({ status: 204 }));
expect(within(gmail).getByRole("alert")).toHaveTextContent(translations.en.emailConnectionsRefreshRequired);
expect(within(gmail).queryByText("Not connected")).not.toBeInTheDocument();
expect(within(gmail).queryByRole("button", { name: "Connect" })).not.toBeInTheDocument();
const repeated = within(gmail).queryByRole("button", { name: "Disconnect" });
if (repeated) { expect(repeated).toBeDisabled(); fireEvent.click(repeated); }
expect(mockedApi.delete).toHaveBeenCalledTimes(1);
await act(async () => { window.dispatchEvent(new StorageEvent("storage", { key: "uiLanguage", newValue: "nb" })); });
expect(within(gmail).getByRole("alert")).toHaveTextContent(translations.nb.emailConnectionsRefreshRequired);
fireEvent.click(within(gmail).getByRole("button", { name: translations.nb.retry }));
await waitFor(() => expect(within(gmail).getByText(translations.nb.emailConnectionsNotConnected)).toBeVisible());
expect(mockedApi.delete).toHaveBeenCalledTimes(1); expect(reads).toBe(3);
expect(statusReads().filter(([url]) => url !== "/gmail/status")).toHaveLength(2);
});
it("[P7-09 Connections] failed disconnect preserves its known status and uses current-language explicit retry", async () => {
const pending = deferred<any>();
mockedApi.get.mockImplementation((url: string) => Promise.resolve({ data: url === "/gmail/status" ? { connected: true, gmailAddress: "still-connected@example.test" } : { connected: false } } as any));
mockedApi.delete.mockReturnValueOnce(pending.promise).mockResolvedValueOnce({ status: 204 } as any);
renderComponent(); await screen.findByText("still-connected@example.test");
const gmail = screen.getByRole("region", { name: "Gmail" });
fireEvent.click(within(gmail).getByRole("button", { name: "Disconnect" }));
await act(async () => { window.dispatchEvent(new StorageEvent("storage", { key: "uiLanguage", newValue: "nb" })); });
await act(async () => pending.reject(new Error("offline")));
expect(within(gmail).getByRole("alert")).toHaveTextContent(translations.nb.emailConnectionsDisconnectFailed.replace("{provider}", "Gmail"));
expect(within(gmail).getByText("still-connected@example.test")).toBeVisible();
expect(statusReads()).toHaveLength(3);
fireEvent.click(within(gmail).getByRole("button", { name: translations.nb.emailConnectionsDisconnect }));
await waitFor(() => expect(mockedApi.delete).toHaveBeenCalledTimes(2));
await waitFor(() => expect(statusReads()).toHaveLength(4));
});
it("[P7-09 Connections] IMAP submits one captured snapshot and a late success cannot clear a newer password", async () => {
disconnectedProviderReads(); const pending = deferred<any>(); mockedApi.post.mockReturnValue(pending.promise);
renderComponent(); await screen.findByLabelText("IMAP host");
fireEvent.change(screen.getByLabelText("IMAP host"), { target: { value: "imap.example.test" } });
fireEvent.change(screen.getByLabelText("Username"), { target: { value: "owner@example.test" } });
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "submitted-secret" } });
const button = screen.getByRole("button", { name: "Connect IMAP account" });
act(() => { fireEvent.click(button); fireEvent.click(button); });
expect(mockedApi.post).toHaveBeenCalledTimes(1);
expect(mockedApi.post).toHaveBeenCalledWith("/imap/connect", { host: "imap.example.test", port: 993, useSsl: true, username: "owner@example.test", password: "submitted-secret" });
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "newer-secret" } });
await act(async () => pending.resolve({ data: { username: "owner@example.test" } }));
await waitFor(() => expect(statusReads()).toHaveLength(4));
expect(screen.getByLabelText("Password")).toHaveValue("newer-secret");
expect(screen.getByLabelText("IMAP host")).toHaveValue("imap.example.test");
expect(mockedApi.post).toHaveBeenCalledTimes(1);
});
it("[P7-09 Connections] failed IMAP save retains credentials for an explicit retry and current fallback", async () => {
disconnectedProviderReads(); const pending = deferred<any>(); mockedApi.post.mockReturnValueOnce(pending.promise).mockResolvedValueOnce({ data: {} } as any);
renderComponent(); await screen.findByLabelText("IMAP host");
fireEvent.change(screen.getByLabelText("IMAP host"), { target: { value: "imap.example.test" } });
fireEvent.change(screen.getByLabelText("Username"), { target: { value: "owner@example.test" } });
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "retained-secret" } });
fireEvent.click(screen.getByRole("button", { name: "Connect IMAP account" }));
await act(async () => { window.dispatchEvent(new StorageEvent("storage", { key: "uiLanguage", newValue: "nb" })); });
await act(async () => pending.reject(new Error("offline")));
expect(within(screen.getByRole("region", { name: translations.nb.emailConnectionsOtherImap })).getByRole("alert")).toHaveTextContent(translations.nb.emailConnectionsImapFailed);
expect(screen.getByLabelText("IMAP-vert")).toHaveValue("imap.example.test");
expect(screen.getByLabelText("Brukernavn")).toHaveValue("owner@example.test");
expect(screen.getByLabelText("Passord")).toHaveValue("retained-secret");
expect(statusReads()).toHaveLength(3);
fireEvent.click(screen.getByRole("button", { name: translations.nb.emailConnectionsConnectImap }));
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledTimes(2));
expect(mockedApi.post.mock.calls[1]).toEqual(["/imap/connect", { host: "imap.example.test", port: 993, useSsl: true, username: "owner@example.test", password: "retained-secret" }]);
await waitFor(() => expect(screen.getByLabelText("Passord")).toHaveValue(""));
});
it("[P7-09 Connections] disposed reads and writes cannot refresh, toast or clear a new panel", async () => {
const oldRead = deferred<any>(); const oldWrite = deferred<any>(); let first = true;
mockedApi.get.mockImplementation((url: string) => first && url === "/gmail/status" ? oldRead.promise : Promise.resolve({ data: { connected: false } } as any));
mockedApi.post.mockReturnValue(oldWrite.promise);
const old = renderComponent(); await screen.findByLabelText("IMAP host");
fireEvent.change(screen.getByLabelText("IMAP host"), { target: { value: "imap.old.test" } });
fireEvent.change(screen.getByLabelText("Username"), { target: { value: "old@example.test" } });
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "old-secret" } });
fireEvent.click(screen.getByRole("button", { name: "Connect IMAP account" }));
old.unmount(); first = false;
renderComponent(); await screen.findByLabelText("IMAP host");
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "new-panel-secret" } });
const reads = statusReads().length;
await act(async () => { oldRead.resolve({ data: { connected: true, gmailAddress: "disposed@example.test" } }); oldWrite.resolve({ data: {} }); });
expect(statusReads()).toHaveLength(reads);
expect(screen.queryByText("disposed@example.test")).not.toBeInTheDocument();
expect(screen.queryByText(translations.en.emailConnectionsImapConnected)).not.toBeInTheDocument();
expect(screen.getByLabelText("Password")).toHaveValue("new-panel-secret");
});
it("[P7-09 Connections] invalid IMAP ports remain visible and prevent sending a silently substituted port", async () => {
disconnectedProviderReads(); renderComponent(); await screen.findByLabelText("IMAP host");
fireEvent.change(screen.getByLabelText("IMAP host"), { target: { value: "imap.example.test" } });
fireEvent.change(screen.getByLabelText("Username"), { target: { value: "owner@example.test" } });
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "secret" } });
const port = screen.getByLabelText("Port");
for (const value of ["", "0", "1.5", "65536"]) {
fireEvent.change(port, { target: { value } });
fireEvent.click(screen.getByRole("button", { name: "Connect IMAP account" }));
expect(port).toHaveValue(value ? Number(value) : null);
expect(port).toHaveAttribute("aria-invalid", "true");
expect(port).toHaveAccessibleDescription(translations.en.emailConnectionsPortInvalid);
}
expect(mockedApi.post).not.toHaveBeenCalled();
});
it("[P7-09 Connections] removed Retry restores meaningful focus without stealing deliberate field focus", async () => {
let attempt = 0; const pending = deferred<any>();
mockedApi.get.mockImplementation((url: string) => url !== "/gmail/status" ? Promise.resolve({ data: { connected: false } } as any)
: ++attempt === 1 ? Promise.reject(new Error("offline")) : pending.promise);
const first = renderComponent(); await screen.findByLabelText("IMAP host");
const gmail = screen.getByRole("region", { name: "Gmail" });
const retry = await within(gmail).findByRole("button", { name: translations.en.retry });
act(() => { retry.focus(); fireEvent.click(retry); });
await act(async () => pending.resolve({ data: { connected: false } }));
expect(gmail).toContainElement(document.activeElement as HTMLElement);
expect(document.body).not.toBe(document.activeElement);
// A later explicit field move while a retry is pending must remain authoritative.
let read = 0; const later = deferred<any>();
mockedApi.get.mockImplementation((url: string) => url !== "/gmail/status" ? Promise.resolve({ data: { connected: false } } as any)
: ++read === 1 ? Promise.reject(new Error("offline")) : later.promise);
// A new mounted panel is an independent read session.
first.unmount();
const current = renderComponent();
const panels = screen.getAllByRole("region", { name: "Gmail" }); const newest = panels[panels.length - 1];
const nextRetry = await within(newest).findByRole("button", { name: translations.en.retry });
act(() => { nextRetry.focus(); fireEvent.click(nextRetry); });
const fields = screen.getAllByLabelText("Password"); const field = fields[fields.length - 1]; act(() => field.focus());
await act(async () => later.resolve({ data: { connected: false } }));
expect(field).toHaveFocus(); current.unmount();
});
it("[P7-09 Connections] an IMAP field removed after commit has a meaningful fallback while refresh is pending", async () => {
const saved = deferred<any>(); const refreshed = deferred<any>(); let imapReads = 0;
mockedApi.get.mockImplementation((url: string) => url === "/imap/status" && ++imapReads > 1 ? refreshed.promise : Promise.resolve({ data: { connected: false } } as any));
mockedApi.post.mockReturnValue(saved.promise);
renderComponent(); await screen.findByLabelText("IMAP host");
fireEvent.change(screen.getByLabelText("IMAP host"), { target: { value: "imap.example.test" } });
fireEvent.change(screen.getByLabelText("Username"), { target: { value: "owner@example.test" } });
const password = screen.getByLabelText("Password");
fireEvent.change(password, { target: { value: "secret" } });
const button = screen.getByRole("button", { name: "Connect IMAP account" });
act(() => { button.focus(); fireEvent.click(button); });
act(() => password.focus());
await act(async () => saved.resolve({ data: {} }));
expect(password).not.toBeInTheDocument();
const imap = screen.getByRole("region", { name: translations.en.emailConnectionsOtherImap });
expect(within(imap).getByRole("heading", { name: translations.en.emailConnectionsOtherImap })).toHaveFocus();
const other = connectButton("Gmail"); act(() => other.focus());
await act(async () => refreshed.resolve({ data: { connected: true, username: "owner@example.test" } }));
expect(other).toHaveFocus(); expect(mockedApi.post).toHaveBeenCalledTimes(1);
});
});
+13 -1
View File
@@ -456,6 +456,11 @@ export const translations = {
connectedAccountsBody: "Connect the inboxes Jobbjakt may use to identify recruiter correspondence. Connecting an inbox never sends a message on your behalf.",
connectedAccountsBack: "Back to settings",
emailConnectionsTitle: "Linked email accounts",
emailConnectionsLoading: "Checking connection…",
emailConnectionsStatusFailed: "Connection status could not be checked.",
emailConnectionsRefreshRequired: "The action completed, but the connection status could not be refreshed. Refresh before taking another action.",
emailConnectionsDisconnecting: "Disconnecting…",
emailConnectionsPortInvalid: "Enter a whole port number from 1 to 65535.",
emailConnectionsBody: "Connect a mailbox so recruiter correspondence can be linked to jobs automatically.",
emailConnectionsGmailConnected: "Gmail connected.",
emailConnectionsGmailFailed: "Gmail connection failed.",
@@ -1291,6 +1296,7 @@ export const translations = {
settingsQuickCaptureManual: "Or copy the bookmarklet code",
settingsNotificationsBody: "Choose which reminders should show up in your workflow. SMTP delivery can be checked from the system page.",
settingsNotificationsDelivery: "SMTP delivery and test mail live under Admin → System → Settings.",
settingsNotificationsDraftScope: "Notification changes stay while you switch Settings sections. Save or discard them before leaving Settings; leaving discards unsaved changes.",
settingsNotificationsFollowUpReminders: "Email reminders for follow-ups",
settingsNotificationsGhostedJobs: "Email alerts for ghosted jobs",
settingsNotificationsInAppReminders: "Highlight reminders in the app",
@@ -3210,9 +3216,14 @@ export const translations = {
operationsFailed: "Mislyktes: {category}",
gmailReviewQueue: "Gmail-gjennomgang",
connectedAccounts: "Tilkoblede kontoer",
connectedAccountsBody: "Koble til innboksene Jobbjakt kan bruke til å identifisere korrespondanse med rekrutterere. En tilkoblet innboks sender aldri meldinger på dine vegne.",
connectedAccountsBody: "Koble til innboksene Jobbjakt kan bruke til å identifisere korrespondanse med rekrutterere. Å koble til en innboks sender ikke meldinger på dine vegne.",
connectedAccountsBack: "Tilbake til innstillinger",
emailConnectionsTitle: "Tilkoblede e-postkontoer",
emailConnectionsLoading: "Kontrollerer tilkoblingen…",
emailConnectionsStatusFailed: "Tilkoblingsstatusen kunne ikke kontrolleres.",
emailConnectionsRefreshRequired: "Handlingen er fullført, men tilkoblingsstatusen kunne ikke oppdateres. Oppdater før du utfører en ny handling.",
emailConnectionsDisconnecting: "Kobler fra…",
emailConnectionsPortInvalid: "Angi et helt portnummer fra 1 til 65535.",
emailConnectionsBody: "Koble til en innboks slik at korrespondanse med rekrutterere automatisk kan knyttes til jobber.",
emailConnectionsGmailConnected: "Gmail er koblet til.",
emailConnectionsGmailFailed: "Tilkobling til Gmail mislyktes.",
@@ -4048,6 +4059,7 @@ export const translations = {
settingsQuickCaptureManual: "Eller kopier bokmerkekoden",
settingsNotificationsBody: "Velg hvilke påminnelser som skal vises i arbeidsflyten din. SMTP-levering kan kontrolleres fra systemsiden.",
settingsNotificationsDelivery: "SMTP-levering og test-epost ligger under Admin → System → Innstillinger.",
settingsNotificationsDraftScope: "Varslingsendringer beholdes når du bytter del i Innstillinger. Lagre eller forkast dem før du går ut; ulagrede endringer går tapt når du forlater Innstillinger.",
settingsNotificationsFollowUpReminders: "E-postpåminnelser for oppfølginger",
settingsNotificationsGhostedJobs: "E-postvarsler for ghostede jobber",
settingsNotificationsInAppReminders: "Fremhev påminnelser i appen",
+134 -1
View File
@@ -1,12 +1,13 @@
import React from 'react';
import '@testing-library/jest-dom';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import SettingsView from './components/SettingsView';
import { I18nProvider } from './i18n/I18nProvider';
import { ToastProvider } from './toast';
import { api } from './api';
import { translations, type TranslationKey } from './i18n/translations';
jest.mock('./api', () => ({
api: {
@@ -316,3 +317,135 @@ test('[PRES-S03] Rules draft updates do not refetch an unrelated notification pr
await act(async () => undefined);
expect(mockedApi.get.mock.calls.filter(([url]) => url === '/notification-settings')).toHaveLength(reads);
});
function preferenceCopy(key: TranslationKey) { return translations[document.documentElement.lang === 'nb-NO' ? 'nb' : 'en'][key]; }
function notificationPanel() { return within(screen.getByRole('tabpanel', { name: preferenceCopy('settingsTabNotifications') })); }
function notificationReads() { return mockedApi.get.mock.calls.filter(([url]) => url === '/notification-settings'); }
function notificationWrites() { return mockedApi.put.mock.calls.filter(([url]) => url === '/notification-settings'); }
async function openNotifications() {
fireEvent.click(screen.getByRole('tab', { name: preferenceCopy('settingsTabNotifications') }));
return notificationPanel().findByRole('checkbox', { name: preferenceCopy('settingsNotificationsFollowUpReminders') });
}
async function preferenceLanguage(language: 'en' | 'nb') {
await act(async () => { window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: language })); });
}
function preferenceDeferred() {
let resolve!: (value: any) => void;
const promise = new Promise<any>(yes => { resolve = yes; });
return { promise, resolve };
}
test('[P7-09 preferences] initial notification failure offers a single GET Retry and recovers its vanished focused action', async () => {
const pending = preferenceDeferred(); const ordinaryGet = mockedApi.get.getMockImplementation()!; let reads = 0;
mockedApi.get.mockImplementation((url: string, config?: any) => url === '/notification-settings'
? ++reads === 1 ? Promise.reject(new Error('offline')) : pending.promise : ordinaryGet(url, config));
renderView(); fireEvent.click(screen.getByRole('tab', { name: 'Notifications' }));
expect(await notificationPanel().findByRole('alert')).toHaveTextContent(translations.en.settingsNotificationsLoadFailed);
const retry = notificationPanel().getByRole('button', { name: 'Retry' });
act(() => { retry.focus(); fireEvent.click(retry); fireEvent.click(retry); });
expect(notificationReads()).toHaveLength(2); expect(mockedApi.put).not.toHaveBeenCalled();
await act(async () => pending.resolve({ data: { emailFollowUpRemindersEnabled: false } }));
expect(await notificationPanel().findByRole('checkbox', { name: translations.en.settingsNotificationsFollowUpReminders })).not.toBeChecked();
expect(notificationPanel().queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument();
expect(notificationPanel().getByRole('group', { name: translations.en.settingsNotificationsTitle })).toHaveFocus();
expect(notificationReads()).toHaveLength(2); expect(mockedApi.put).not.toHaveBeenCalled();
});
test('[P7-09 preferences] notification drafts survive internal sections and locale changes without a GET or save', async () => {
renderView(); const checkbox = await openNotifications(); expect(checkbox).toBeChecked(); fireEvent.click(checkbox);
const reads = notificationReads().length;
fireEvent.click(screen.getByRole('tab', { name: 'Follow-ups' })); await screen.findByLabelText('Applied: follow-up days');
fireEvent.click(screen.getByRole('tab', { name: 'General' })); await preferenceLanguage('nb');
const retained = await openNotifications();
expect(retained).not.toBeChecked(); expect(notificationReads()).toHaveLength(reads);
expect(notificationPanel().getByRole('status')).toHaveTextContent(translations.nb.settingsNotificationsDraftScope);
await preferenceLanguage('en'); expect(notificationPanel().getByRole('checkbox', { name: translations.en.settingsNotificationsFollowUpReminders })).not.toBeChecked();
expect(notificationReads()).toHaveLength(reads); expect(mockedApi.put).not.toHaveBeenCalled();
});
test('[P7-09 preferences] one held notification save acknowledges its snapshot and preserves later edits across sections', async () => {
const pending = preferenceDeferred(); mockedApi.put.mockImplementationOnce(() => pending.promise);
renderView(); const checkbox = await openNotifications(); fireEvent.click(checkbox);
const save = notificationPanel().getByRole('button', { name: translations.en.settingsNotificationsSave });
act(() => { fireEvent.click(save); fireEvent.click(save); });
expect(notificationWrites()).toEqual([['/notification-settings', { emailFollowUpRemindersEnabled: false }]]);
fireEvent.click(checkbox); expect(checkbox).toBeChecked();
fireEvent.click(screen.getByRole('tab', { name: 'Follow-ups' })); await screen.findByLabelText('Applied: follow-up days');
await act(async () => pending.resolve({ data: { emailFollowUpRemindersEnabled: false } }));
expect(await openNotifications()).toBeChecked();
expect(notificationPanel().getByRole('status')).toHaveTextContent(translations.en.assetsUnsavedChanges);
fireEvent.click(notificationPanel().getByRole('button', { name: translations.en.assetsDiscardChanges }));
expect(notificationPanel().getByRole('checkbox', { name: translations.en.settingsNotificationsFollowUpReminders })).not.toBeChecked();
expect(notificationPanel().queryByText(translations.en.settingsNotificationsDraftScope)).not.toBeInTheDocument();
expect(notificationReads()).toHaveLength(1); expect(notificationWrites()).toHaveLength(1);
});
test('[P7-09 preferences] failed notification save keeps its current-locale draft and retries only the original Save', async () => {
mockedApi.put.mockRejectedValueOnce(new Error('offline'));
renderView(); fireEvent.click(await openNotifications());
fireEvent.click(notificationPanel().getByRole('button', { name: translations.en.settingsNotificationsSave }));
expect(await notificationPanel().findByRole('alert')).toHaveTextContent(translations.en.settingsNotificationsSaveFailed);
const reads = notificationReads().length; await preferenceLanguage('nb');
expect(notificationPanel().getByRole('alert')).toHaveTextContent(translations.nb.settingsNotificationsSaveFailed);
expect(notificationPanel().getByRole('checkbox', { name: translations.nb.settingsNotificationsFollowUpReminders })).not.toBeChecked();
expect(notificationPanel().queryByRole('button', { name: translations.nb.retry })).not.toBeInTheDocument();
fireEvent.click(notificationPanel().getByRole('button', { name: translations.nb.settingsNotificationsSave }));
await waitFor(() => expect(notificationPanel().queryByRole('alert')).not.toBeInTheDocument());
expect(notificationWrites()).toEqual([
['/notification-settings', { emailFollowUpRemindersEnabled: false }],
['/notification-settings', { emailFollowUpRemindersEnabled: false }],
]);
expect(notificationReads()).toHaveLength(reads);
expect(await screen.findByText(translations.nb.settingsNotificationsSaved)).toBeVisible();
});
test('[P7-09 preferences] discarding a notification draft leaves the independent Rules draft untouched', async () => {
renderView(); fireEvent.change(await openRules(), { target: { value: '5' } });
fireEvent.click(await openNotifications());
fireEvent.click(notificationPanel().getByRole('button', { name: translations.en.assetsDiscardChanges }));
expect(notificationPanel().getByRole('checkbox', { name: translations.en.settingsNotificationsFollowUpReminders })).toBeChecked();
expect(notificationPanel().queryByText(translations.en.settingsNotificationsDraftScope)).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('tab', { name: 'Follow-ups' }));
expect(screen.getByLabelText('Applied: follow-up days')).toHaveValue(5);
expect(screen.getByRole('status')).toHaveTextContent(translations.en.rulesDraftScope);
expect(mockedApi.put).not.toHaveBeenCalled();
});
test('[P7-09 preferences] a disposed notification save cannot publish into surviving providers or a new Settings session', async () => {
const pending = preferenceDeferred(); mockedApi.put.mockImplementationOnce(() => pending.promise);
function Session() {
const [visible, setVisible] = React.useState(true);
return <MemoryRouter><ToastProvider><I18nProvider>
<button onClick={() => setVisible(value => !value)}>Toggle Settings session</button>
{visible ? <SettingsView pageSize={20} onPageSizeChange={() => undefined} columns={{ status: true, dateApplied: true, daysSince: true, jobUrl: false }} onColumnsChange={() => undefined} themeMode="dark" onThemeModeChange={() => undefined} /> : null}
</I18nProvider></ToastProvider></MemoryRouter>;
}
render(<Session />); fireEvent.click(await openNotifications());
fireEvent.click(notificationPanel().getByRole('button', { name: translations.en.settingsNotificationsSave }));
expect(notificationWrites()).toHaveLength(1); fireEvent.click(screen.getByRole('button', { name: 'Toggle Settings session' }));
await act(async () => pending.resolve({ data: { emailFollowUpRemindersEnabled: false } }));
expect(screen.queryByText(translations.en.settingsNotificationsSaved)).not.toBeInTheDocument();
expect(notificationReads()).toHaveLength(1);
fireEvent.click(screen.getByRole('button', { name: 'Toggle Settings session' }));
expect(await openNotifications()).toBeChecked(); expect(notificationReads()).toHaveLength(2);
expect(notificationPanel().queryByText(translations.en.settingsNotificationsDraftScope)).not.toBeInTheDocument();
expect(notificationWrites()).toHaveLength(1);
});
test('[P7-09 preferences] Rules load failure follows locale without reloading and Retry retains the six-field contract', async () => {
const ordinaryGet = mockedApi.get.getMockImplementation()!; let reads = 0;
mockedApi.get.mockImplementation((url: string, config?: any) => url === '/rules' && ++reads === 1 ? Promise.reject(new Error('offline')) : ordinaryGet(url, config));
renderView(); fireEvent.click(screen.getByRole('tab', { name: 'Follow-ups' }));
expect(await screen.findByRole('alert')).toHaveTextContent(translations.en.rulesLoadFailed);
await preferenceLanguage('nb');
expect(screen.getByRole('alert')).toHaveTextContent(translations.nb.rulesLoadFailed);
expect(mockedApi.get.mock.calls.filter(([url]) => url === '/rules')).toHaveLength(1);
fireEvent.click(screen.getByRole('button', { name: translations.nb.retry }));
const fields = [
['rulesAppliedFollowUpDays', 14], ['rulesAppliedGhostDays', 30], ['rulesOfferFollowUpDays', 7],
['rulesOfferGhostDays', 14], ['rulesFeedbackFollowUpDays', 7], ['rulesFeedbackGhostDays', 14],
] as const;
for (const [key, value] of fields) expect(await screen.findByLabelText(translations.nb[key])).toHaveValue(value);
expect(mockedApi.get.mock.calls.filter(([url]) => url === '/rules')).toHaveLength(2);
expect(mockedApi.put).not.toHaveBeenCalled();
});
@@ -1,24 +1,20 @@
import React from "react";
import { Box, Button, Paper, Typography } from "@mui/material";
import { Box, Button } from "@mui/material";
import { useNavigate } from "react-router-dom";
import EmailProviderConnections from "../components/EmailProviderConnections";
import { useI18n } from "../i18n/I18nProvider";
import { PageHeader } from "../layout/PageLayout";
export default function ConnectedAccountsPage() {
const navigate = useNavigate();
const { t } = useI18n();
return (
<Box sx={{ display: "grid", gap: 2 }}>
<Paper sx={{ p: 2.5, borderRadius: 4, boxShadow: "0px 8px 24px -12px rgba(15,23,42,0.12)" }}>
<Typography variant="h5" sx={{ fontWeight: 900, mb: 0.5 }}>{t("connectedAccounts")}</Typography>
<Typography sx={{ color: "text.secondary", maxWidth: 720 }}>
{t("connectedAccountsBody")}
</Typography>
<Button sx={{ mt: 1 }} onClick={() => navigate("/settings")}>{t("connectedAccountsBack")}</Button>
</Paper>
<Box sx={{ display: "grid", gap: "var(--app-section-gap)", minWidth: 0 }}>
<PageHeader level="h2" title={t("connectedAccounts")} description={t("connectedAccountsBody")}
actions={<Button variant="outlined" onClick={() => navigate("/settings")}>{t("connectedAccountsBack")}</Button>} />
<EmailProviderConnections />
</Box>
);