385 lines
18 KiB
TypeScript
385 lines
18 KiB
TypeScript
import React, { useCallback, useEffect, useRef, useState } from "react";
|
|
|
|
import {
|
|
Box,
|
|
Alert,
|
|
Button,
|
|
Checkbox,
|
|
FormControl,
|
|
FormControlLabel,
|
|
InputLabel,
|
|
MenuItem,
|
|
Select,
|
|
Tab,
|
|
Tabs,
|
|
Typography,
|
|
} from "@mui/material";
|
|
|
|
import { useNavigate } from "react-router-dom";
|
|
|
|
import { JobTableColumns } from "./JobTable";
|
|
import ImportExportJobs from "./ImportExportJobs";
|
|
import RulesSettingsCard, { RULE_FIELDS, RuleDraft, RuleField, RuleSettings } from "./RulesSettingsCard";
|
|
import BackupCard from "./BackupCard";
|
|
import QuickCaptureCard from "./QuickCaptureCard";
|
|
import AiUsageCard from "./AiUsageCard";
|
|
import AiPrivacySettingsCard from "./AiPrivacySettingsCard";
|
|
import { ThemeModePref } from "../themePrefs";
|
|
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;
|
|
onPageSizeChange: (n: 15 | 20 | 25) => void;
|
|
columns: JobTableColumns;
|
|
onColumnsChange: (next: JobTableColumns) => void;
|
|
themeMode: ThemeModePref;
|
|
onThemeModeChange: (v: ThemeModePref) => void;
|
|
}
|
|
|
|
function TabPanel({ value, index, label, children }: { value: number; index: number; label: string; children: React.ReactNode }) {
|
|
if (value !== index) return null;
|
|
return <Box role="tabpanel" id={`settings-panel-${index}`} aria-labelledby={`settings-tab-${index}`} aria-label={label} sx={{ mt: "var(--app-section-gap)", minWidth: 0 }}>{children}</Box>;
|
|
}
|
|
|
|
type NotificationPrefs = {
|
|
emailFollowUpRemindersEnabled: boolean;
|
|
};
|
|
|
|
function ruleDraft(settings: RuleSettings): RuleDraft {
|
|
return Object.fromEntries(RULE_FIELDS.map(field => [field, String(settings[field])])) as RuleDraft;
|
|
}
|
|
|
|
export default function SettingsView({
|
|
pageSize,
|
|
onPageSizeChange,
|
|
columns,
|
|
onColumnsChange,
|
|
themeMode,
|
|
onThemeModeChange,
|
|
}: Props) {
|
|
const navigate = useNavigate();
|
|
const [tab, setTab] = useState(0);
|
|
const { language, setLanguage, t } = useI18n();
|
|
const { toast } = useToast();
|
|
const [notificationPrefs, setNotificationPrefs] = useState<NotificationPrefs | 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<{ 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;
|
|
notifications.mounted = true;
|
|
return () => {
|
|
session.mounted = false;
|
|
notifications.mounted = false;
|
|
notifications.generation += 1;
|
|
notifications.loading = false;
|
|
notifications.saving = false;
|
|
};
|
|
}, []);
|
|
|
|
const loadRules = async () => {
|
|
const session = rulesSession.current;
|
|
if (rulesDraft || session.loading) return;
|
|
session.loading = true;
|
|
setRulesLoadError(null);
|
|
try {
|
|
const { data } = await api.get<RuleSettings>("/rules");
|
|
if (!session.mounted) return;
|
|
setSavedRules(data);
|
|
setRulesDraft(ruleDraft(data));
|
|
} catch (error) {
|
|
if (session.mounted) setRulesLoadError({ cause: error });
|
|
} finally { session.loading = false; }
|
|
};
|
|
|
|
const selectSection = (next: number) => {
|
|
setTab(next);
|
|
if (next === 1) void loadRules();
|
|
};
|
|
|
|
const saveRules = async () => {
|
|
const session = rulesSession.current;
|
|
if (!rulesDraft || !savedRules || session.saving) return;
|
|
const invalid = RULE_FIELDS.filter(field => !rulesDraft[field].trim() || !Number.isInteger(Number(rulesDraft[field])) || Number(rulesDraft[field]) < 1 || Number(rulesDraft[field]) > 365);
|
|
setInvalidRules(invalid);
|
|
if (invalid.length) return;
|
|
const submittedDraft = rulesDraft;
|
|
const submitted = { id: savedRules.id, ...Object.fromEntries(RULE_FIELDS.map(field => [field, Number(submittedDraft[field])])) } as RuleSettings;
|
|
session.saving = true;
|
|
setSavingRules(true);
|
|
setRulesSaveError(false);
|
|
try {
|
|
await api.put("/rules", submitted);
|
|
if (!session.mounted) return;
|
|
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(currentTranslation.current("rulesSaved"), "success");
|
|
} catch {
|
|
if (session.mounted) setRulesSaveError(true);
|
|
} finally {
|
|
session.saving = false;
|
|
if (session.mounted) setSavingRules(false);
|
|
}
|
|
};
|
|
|
|
const discardRules = () => {
|
|
if (!savedRules || savingRules) return;
|
|
setRulesDraft(ruleDraft(savedRules));
|
|
setInvalidRules([]);
|
|
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(() => {
|
|
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 () => {
|
|
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", 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 }}>
|
|
<InputLabel id="settings-section-label">{t("settingsNavigation")}</InputLabel>
|
|
<Select
|
|
labelId="settings-section-label"
|
|
value={tab}
|
|
label={t("settingsNavigation")}
|
|
onChange={(event) => selectSection(Number(event.target.value))}
|
|
>
|
|
<MenuItem value={0}>{t("settingsTabGeneral")}</MenuItem>
|
|
<MenuItem value={1}>{t("settingsTabFollowUps")}</MenuItem>
|
|
<MenuItem value={2}>{t("settingsTabNotifications")}</MenuItem>
|
|
<MenuItem value={3}>{t("settingsTabBackup")}</MenuItem>
|
|
</Select>
|
|
</FormControl>
|
|
|
|
<Tabs aria-label={t("settings")} value={tab} onChange={(_, v) => selectSection(v)} variant="scrollable" scrollButtons="auto" sx={{ display: { xs: "none", sm: "flex" }, mb: 1 }}>
|
|
<Tab id="settings-tab-0" aria-controls="settings-panel-0" label={t("settingsTabGeneral")} />
|
|
<Tab id="settings-tab-1" aria-controls="settings-panel-1" label={t("settingsTabFollowUps")} />
|
|
<Tab id="settings-tab-2" aria-controls="settings-panel-2" label={t("settingsTabNotifications")} />
|
|
<Tab id="settings-tab-3" aria-controls="settings-panel-3" label={t("settingsTabBackup")} />
|
|
</Tabs>
|
|
|
|
{rulesDirty ? <Typography role="status" variant="body2" sx={{ mt: 1, color: "text.secondary" }}>{t("assetsUnsavedChanges")}. {t("rulesDraftScope")}</Typography> : null}
|
|
|
|
<TabPanel value={tab} index={0} label={t("settingsTabGeneral")}>
|
|
<Box sx={{ display: "grid", gap: "var(--app-section-gap)", minWidth: 0 }}>
|
|
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "minmax(0, 1fr)", md: "repeat(2, minmax(0, 1fr))" }, gap: "var(--app-section-gap)" }}>
|
|
<PageSection surface title={t("settingsAppearance")}>
|
|
<FormControl fullWidth>
|
|
<InputLabel id="theme-mode-label">{t("settingsTheme")}</InputLabel>
|
|
<Select
|
|
labelId="theme-mode-label"
|
|
value={themeMode}
|
|
label={t("settingsTheme")}
|
|
onChange={(e) => onThemeModeChange(e.target.value as ThemeModePref)}
|
|
>
|
|
<MenuItem value="system">{t("settingsThemeSystem")}</MenuItem>
|
|
<MenuItem value="dark">{t("settingsThemeDark")}</MenuItem>
|
|
<MenuItem value="light">{t("settingsThemeLight")}</MenuItem>
|
|
</Select>
|
|
</FormControl>
|
|
</PageSection>
|
|
|
|
<PageSection surface title={t("settingsLanguageTitle")} description={t("settingsLanguageBody")}>
|
|
<FormControl fullWidth>
|
|
<InputLabel id="language-label">{t("settingsPreferredLanguage")}</InputLabel>
|
|
<Select
|
|
labelId="language-label"
|
|
value={language}
|
|
label={t("settingsPreferredLanguage")}
|
|
onChange={(e) => setLanguage(e.target.value as "en" | "nb")}
|
|
>
|
|
<MenuItem value="en">{t("settingsEnglish")}</MenuItem>
|
|
<MenuItem value="nb">{t("settingsNorwegian")}</MenuItem>
|
|
</Select>
|
|
</FormControl>
|
|
</PageSection>
|
|
</Box>
|
|
|
|
<PageSection surface title={t("settingsJobs")}>
|
|
<Box sx={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
|
|
<Box sx={{ flex: "1 1 15rem", minWidth: 0 }}>
|
|
<Typography component="h3" variant="subtitle2" sx={{ mb: 1, fontWeight: 700 }}>
|
|
{t("settingsPagination")}
|
|
</Typography>
|
|
<FormControl fullWidth>
|
|
<InputLabel id="page-size-label">{t("settingsRowsPerPage")}</InputLabel>
|
|
<Select
|
|
labelId="page-size-label"
|
|
value={pageSize}
|
|
label={t("settingsRowsPerPage")}
|
|
onChange={(e) => onPageSizeChange(e.target.value as 15 | 20 | 25)}
|
|
>
|
|
<MenuItem value={15}>15</MenuItem>
|
|
<MenuItem value={20}>20</MenuItem>
|
|
<MenuItem value={25}>25</MenuItem>
|
|
</Select>
|
|
</FormControl>
|
|
</Box>
|
|
|
|
<Box sx={{ flex: "1 1 15rem", minWidth: 0 }}>
|
|
<Typography component="h3" variant="subtitle2" sx={{ mb: 1, fontWeight: 700 }}>
|
|
{t("settingsColumns")}
|
|
</Typography>
|
|
{(
|
|
[
|
|
["status", t("settingsColumnStatus")],
|
|
["dateApplied", t("settingsColumnDateApplied")],
|
|
["daysSince", t("settingsColumnDays")],
|
|
["jobUrl", t("settingsColumnJobUrl")],
|
|
] as const
|
|
).map(([key, label]) => (
|
|
<FormControlLabel
|
|
key={key}
|
|
control={<Checkbox checked={columns[key]} onChange={() => onColumnsChange({ ...columns, [key]: !columns[key] })} />}
|
|
label={label}
|
|
/>
|
|
))}
|
|
</Box>
|
|
</Box>
|
|
|
|
<Box sx={{ mt: 2 }}>
|
|
<ImportExportJobs />
|
|
</Box>
|
|
</PageSection>
|
|
|
|
<AiPrivacySettingsCard />
|
|
<AiUsageCard />
|
|
<QuickCaptureCard />
|
|
<PageSection surface title={t("connectedAccounts")} description={t("settingsConnectedAccountsBody")}
|
|
actions={<Button variant="outlined" onClick={() => navigate("/settings/connected-accounts")}>{t("settingsManageConnectedAccounts")}</Button>} />
|
|
</Box>
|
|
</TabPanel>
|
|
|
|
<TabPanel value={tab} index={1} label={t("settingsTabFollowUps")}>
|
|
<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);
|
|
setInvalidRules(current => current.filter(key => key !== field));
|
|
}} />
|
|
</TabPanel>
|
|
|
|
<TabPanel value={tab} index={2} label={t("settingsTabNotifications")}>
|
|
<PageSection surface title={t("settingsNotificationsTitle")} description={t("settingsNotificationsBody")}>
|
|
<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 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>
|
|
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap", mt: 1.5 }}>
|
|
<Button variant="outlined" onClick={() => navigate("/reminders")}>{t("settingsOpenReminderInbox")}</Button>
|
|
</Box>
|
|
</PageSection>
|
|
</TabPanel>
|
|
|
|
<TabPanel value={tab} index={3} label={t("settingsTabBackup")}>
|
|
<BackupCard />
|
|
</TabPanel>
|
|
</Box>
|
|
);
|
|
}
|