import { BasePage, ConfigBox, TextLink, Tabs, Tab } from "@/Components/design-elements"; import { Autocomplete, Select, Dialog } from "@/Components/inputs"; import { logger } from "@/Utils/logger"; import { LAYOUT } from "@/Utils/Theme/constants"; import { Stack, useTheme, MenuItem, Link, Alert, type SelectChangeEvent, } from "@mui/material"; import { useEffect, useMemo } from "react"; import { FormProvider, useForm, type FieldPath } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { useTranslation } from "react-i18next"; import { useSelector, useDispatch } from "react-redux"; import DummyChart from "@/Pages/Settings/DummyChart"; import { useGet, usePatch, usePost, useLazyGet } from "@/Hooks/UseApi"; import { useToast } from "@/Hooks/UseToast"; import { useSettingsForm } from "@/Hooks/useSettingsForm"; import { useIsAdmin } from "@/Hooks/useIsAdmin.js"; import type { SettingsFormData, SettingsFormInput } from "@/Validation/settings"; import { useState } from "react"; import { Button, FieldLabel } from "@/Components/inputs"; import { languageNames } from "@/Components/inputs/LanguageSelector"; import { Box, Typography } from "@mui/material"; import { useDelete } from "@/Hooks/UseApi"; import { setTimezone, setMode, setLanguage, setChartType, type ThemeMode, type ChartType, } from "@/Features/UI/uiSlice.js"; import { timezoneOptions } from "@/Utils/timezoneOptions"; import type { TimezoneOption } from "@/Utils/timezoneOptions"; import type { RootState } from "@/Types/state"; import { CHECK_TTL_SENTINEL } from "@/Types/Check"; import { FormTextField } from "@/Components/inputs/forms/FormTextField"; import { FormSliderField } from "@/Components/inputs/forms/FormSliderField"; import { FormSwitchField } from "@/Components/inputs/forms/FormSwitchField"; import { FormNumberField } from "@/Components/inputs/forms/FormNumberField"; import { FormSelectField } from "@/Components/inputs/forms/FormSelectField"; import type { ProxyResponse } from "@/Types/Proxy"; import type { AppSettingsResponse } from "@/Types/Settings"; import { useSearchParams } from "react-router-dom"; const SETTINGS_TABS = [ { key: "general", labelKey: "pages.settings.tabs.general" }, { key: "monitoring", labelKey: "pages.settings.tabs.monitoring", adminOnly: true }, { key: "email", labelKey: "pages.settings.tabs.email", adminOnly: true }, { key: "integrations", labelKey: "pages.settings.tabs.integrations", adminOnly: true }, { key: "data", labelKey: "pages.settings.tabs.data", adminOnly: true }, ] as const; type SettingsTabKey = (typeof SETTINGS_TABS)[number]["key"]; const FIELD_TAB: Record = { checkTTL: "monitoring", globalThresholds: "monitoring", pagespeedApiKey: "integrations", globalProxyEnabled: "integrations", globalProxyId: "integrations", showURL: "general", }; const tabForField = (field: string): SettingsTabKey => field.startsWith("systemEmail") ? "email" : (FIELD_TAB[field.split(".")[0]] ?? "general"); const FIELD_LABEL_KEY: Record = { checkTTL: "pages.settings.form.retention.option.days.label", "globalThresholds.cpu": "pages.settings.form.thresholds.option.cpu.label", "globalThresholds.memory": "pages.settings.form.thresholds.option.memory.label", "globalThresholds.disk": "pages.settings.form.thresholds.option.disk.label", "globalThresholds.temperature": "pages.settings.form.thresholds.option.temperature.label", pagespeedApiKey: "pages.settings.form.pagespeed.option.apiKey.label", globalProxyEnabled: "pages.settings.form.globalProxy.option.enabled.label", showURL: "pages.settings.form.url.option.showURL.label", systemEmailHost: "pages.settings.form.email.option.host.label", systemEmailPort: "pages.settings.form.email.option.port.label", systemEmailAddress: "pages.settings.form.email.option.address.label", systemEmailDisplayName: "pages.settings.form.email.option.displayName.label", systemEmailUser: "pages.settings.form.email.option.user.label", systemEmailPassword: "pages.settings.form.email.option.password.label", systemEmailTLSServername: "pages.settings.form.email.option.tlsServername.label", systemEmailConnectionHost: "pages.settings.form.email.option.connectionHost.label", systemEmailSecure: "pages.settings.form.email.option.secure.label", systemEmailPool: "pages.settings.form.email.option.pool.label", systemEmailIgnoreTLS: "pages.settings.form.email.option.ignoreTLS.label", systemEmailRequireTLS: "pages.settings.form.email.option.requireTLS.label", systemEmailRejectUnauthorized: "pages.settings.form.email.option.rejectUnauthorized.label", }; type FieldErrorLeaf = { path: string; message?: string }; const flattenFieldErrors = (errors: unknown, prefix = ""): FieldErrorLeaf[] => { if (typeof errors !== "object" || errors === null) { return []; } return Object.entries(errors).flatMap(([key, value]) => { if (key === "ref") { return []; } const path = prefix ? `${prefix}.${key}` : key; if (typeof value !== "object" || value === null) { return []; } const message = (value as { message?: unknown }).message; if (typeof message === "string") { return [{ path, message }]; } const nested = flattenFieldErrors(value, path); return nested.length > 0 ? nested : [{ path }]; }); }; export const SettingsPage = () => { const theme = useTheme(); const { t, i18n } = useTranslation(); const dispatch = useDispatch(); const isAdmin = useIsAdmin(); const { toastError } = useToast(); const [searchParams, setSearchParams] = useSearchParams(); const visibleTabs = useMemo( () => SETTINGS_TABS.filter((tab) => !("adminOnly" in tab) || isAdmin), [isAdmin] ); const requestedTab = searchParams.get("tab"); const firstVisibleTab: SettingsTabKey = visibleTabs[0]?.key ?? SETTINGS_TABS[0].key; const activeTab: SettingsTabKey = visibleTabs.find((tab) => tab.key === requestedTab)?.key ?? firstVisibleTab; const handleTabChange = (tab: SettingsTabKey) => { const updated = new URLSearchParams(searchParams); if (tab === firstVisibleTab) { updated.delete("tab"); } else { updated.set("tab", tab); } setSearchParams(updated, { replace: true }); }; // Drop a "tab" param that does not resolve to a rendered tab, or that names // the first tab, which is addressed with no param at all. useEffect(() => { if (requestedTab === null) { return; } if (requestedTab === activeTab && activeTab !== firstVisibleTab) { return; } const updated = new URLSearchParams(searchParams); updated.delete("tab"); setSearchParams(updated, { replace: true }); }, [requestedTab, activeTab, firstVisibleTab, searchParams, setSearchParams]); // Local state for demo monitors dialog const [isDemoMonitorsDialogOpen, setIsDemoMonitorsDialogOpen] = useState(false); const { post: postDemoMonitors, loading: isPostingDemoMonitors } = usePost(); const { deleteFn: deleteAllMonitors, loading: isDeletingAllMonitors } = useDelete(); // Import monitors functionality const { post: importMonitors, loading: isImportingMonitors } = usePost(); // Fetch settings data from API const { data: fetchedSettings } = useGet("/settings"); // Get proxies const { data: proxies } = useGet("/proxies"); const proxyOptions = useMemo( () => (proxies ?? []).map((proxy) => ({ value: proxy.id, label: `${proxy.name} (${proxy.host}:${proxy.port})`, })), [proxies] ); // Form submission const { patch, loading: isSaving } = usePatch(); // Local state for API key reset const [isApiKeySet, setIsApiKeySet] = useState( fetchedSettings?.pagespeedKeySet ?? false ); const [apiKeyHasBeenReset, setApiKeyHasBeenReset] = useState(false); // Local state for email password reset const [isEmailPasswordSet, setIsEmailPasswordSet] = useState( fetchedSettings?.emailPasswordSet ?? false ); const [emailPasswordHasBeenReset, setEmailPasswordHasBeenReset] = useState(false); // Test email functionality const { post: sendTestEmail, loading: isSendingTestEmail } = usePost(); // Local state for clear stats dialog const [isStatsDialogOpen, setIsStatsDialogOpen] = useState(false); const { deleteFn: deleteStats, loading: isDeletingStats } = useDelete(); // Export monitors functionality const { get: fetchMonitorsJson } = useLazyGet(); // Initialize form with schema and defaults const { schema, defaults } = useSettingsForm({ data: fetchedSettings?.settings }); const emailSwitches: { name: FieldPath; label: string }[] = [ { name: "systemEmailSecure", label: t("pages.settings.form.email.option.secure.label"), }, { name: "systemEmailPool", label: t("pages.settings.form.email.option.pool.label") }, { name: "systemEmailIgnoreTLS", label: t("pages.settings.form.email.option.ignoreTLS.label"), }, { name: "systemEmailRequireTLS", label: t("pages.settings.form.email.option.requireTLS.label"), }, { name: "systemEmailRejectUnauthorized", label: t("pages.settings.form.email.option.rejectUnauthorized.label"), }, ]; const form = useForm({ resolver: zodResolver(schema), defaultValues: defaults, mode: "onChange", }); const { watch } = form; // Reset form when defaults change useEffect(() => { form.reset(defaults); }, [defaults, form]); // Update isApiKeySet when fetchedSettings changes useEffect(() => { if (fetchedSettings) { setIsApiKeySet(fetchedSettings.pagespeedKeySet); setIsEmailPasswordSet(fetchedSettings.emailPasswordSet); } }, [fetchedSettings]); const { timezone: selectedTimezoneId, mode, language = "en", chartType = "histogram", } = useSelector((state: RootState) => state.ui); const user = useSelector((state: RootState) => state.auth.user); const selectedTimezone = timezoneOptions.find((tz) => tz.id === selectedTimezoneId) ?? null; const handleTimezoneChange = (newValue: TimezoneOption | null) => { if (!newValue?.id) return; dispatch(setTimezone({ timezone: newValue.id })); }; const handleModeChange = (e: SelectChangeEvent) => { dispatch(setMode(e.target.value)); }; const handleLanguageChange = (e: SelectChangeEvent) => { dispatch(setLanguage(e.target.value)); }; const handleChartTypeChange = (e: SelectChangeEvent) => { dispatch(setChartType(e.target.value)); }; const handleResetApiKey = () => { form.setValue("pagespeedApiKey", ""); setApiKeyHasBeenReset(true); }; const handleResetEmailPassword = () => { form.setValue("systemEmailPassword", ""); setEmailPasswordHasBeenReset(true); }; const handleSendTestEmail = async () => { const formValues = form.getValues(); if (!user) { alert("User not authenticated"); return; } if ( !formValues.systemEmailHost || !formValues.systemEmailPort || !formValues.systemEmailAddress || !formValues.systemEmailPassword ) { alert("Please fill in all required email fields before testing."); return; } await sendTestEmail("/settings/test-email", { to: user.email, systemEmailHost: formValues.systemEmailHost, systemEmailPort: formValues.systemEmailPort, systemEmailAddress: formValues.systemEmailAddress, systemEmailPassword: formValues.systemEmailPassword, systemEmailSecure: formValues.systemEmailSecure, systemEmailPool: formValues.systemEmailPool, systemEmailIgnoreTLS: formValues.systemEmailIgnoreTLS, systemEmailRequireTLS: formValues.systemEmailRequireTLS, systemEmailRejectUnauthorized: formValues.systemEmailRejectUnauthorized, ...(formValues.systemEmailUser && { systemEmailUser: formValues.systemEmailUser }), ...(formValues.systemEmailDisplayName && { systemEmailDisplayName: formValues.systemEmailDisplayName, }), ...(formValues.systemEmailTLSServername && { systemEmailTLSServername: formValues.systemEmailTLSServername, }), ...(formValues.systemEmailConnectionHost && { systemEmailConnectionHost: formValues.systemEmailConnectionHost, }), }); }; const handleClearStats = async () => { await deleteStats("/checks/team"); setIsStatsDialogOpen(false); }; const handleExportMonitors = async () => { const res = await fetchMonitorsJson("/monitors/export/json"); const json = res?.data ?? []; if (!json || json.length === 0) { return; } const blob = new Blob([JSON.stringify(json, null, 2)], { type: "application/json", }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = "monitors.json"; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); }; const handleFileSelect = async (event: React.ChangeEvent) => { const file = event.target.files?.[0]; if (!file) { return; } if (file.type !== "application/json") { toastError("Please select a valid JSON file"); event.target.value = ""; } try { const text = await file.text(); const monitors = JSON.parse(text); if (!Array.isArray(monitors)) { toastError("Invalid file format: expected an array of monitors"); event.target.value = ""; return; } await importMonitors("/monitors/import/json", { monitors }); event.target.value = ""; } catch (error) { toastError("Error parsing JSON file. Please check the file format."); event.target.value = ""; } }; const onSubmit = async (data: SettingsFormData) => { // Don't send pagespeedApiKey if it's already set and user hasn't clicked reset const dataToSend = { ...data }; if (isApiKeySet && !apiKeyHasBeenReset) { delete (dataToSend as any).pagespeedApiKey; } if (isEmailPasswordSet && !emailPasswordHasBeenReset) { delete (dataToSend as any).systemEmailPassword; } const result = await patch("/settings", dataToSend as SettingsFormData); if (result?.success) { // Update API key state from response if (result.data) { setIsApiKeySet(result.data.pagespeedKeySet); setApiKeyHasBeenReset(false); setIsEmailPasswordSet(result.data.emailPasswordSet); setEmailPasswordHasBeenReset(false); } } }; const onError = (errors: unknown) => { logger.debug("Form validation errors", errors); }; const revealField = (field: string) => { const target = tabForField(field); if (visibleTabs.some((tab) => tab.key === target)) { handleTabChange(target); } }; const languages = Object.keys(i18n.options.resources || {}); const globalProxyEnabled = watch("globalProxyEnabled"); // Enabling the proxy with nothing selected preselects the first proxy useEffect(() => { if ( globalProxyEnabled && !form.getValues("globalProxyId") && proxyOptions.length > 0 ) { form.setValue("globalProxyId", proxyOptions[0].value, { shouldValidate: true, }); } }, [globalProxyEnabled, proxyOptions, form]); return ( {visibleTabs.length > 1 && ( handleTabChange(value)} > {visibleTabs.map((tab) => ( ))} )} {/* general tab */} {activeTab === "general" && ( option.name} isOptionEqualToValue={(option: TimezoneOption, value: TimezoneOption) => option.id === value.id } onChange={(_, newValue: TimezoneOption | null) => { handleTimezoneChange(newValue); }} fieldLabel={t("pages.settings.form.timezone.option.timezone.label")} /> } /> } /> {/* URL Settings */} } /> {/* About */} {t("common.appName")} {__APP_VERSION__} {t("pages.settings.form.about.developedBy")} https://github.com/bluewave-labs/checkmate } /> )} {/* monitoring tab */} {activeTab === "monitoring" && ( {/* Global Thresholds */} {isAdmin && ( } /> )} {/* Check Retention */} {isAdmin && ( value >= CHECK_TTL_SENTINEL ? t("pages.settings.form.retention.option.days.unlimited") : `${value}` } formatDisplayValue={(value: number) => value >= CHECK_TTL_SENTINEL ? t("pages.settings.form.retention.option.days.unlimited") : `${value}` } /> } /> )} {/* Demo Monitors - Admin Only */} {isAdmin && ( } /> )} )} {/* email tab */} {activeTab === "email" && ( {/* Email Settings - Admin Only */} {isAdmin && ( {(() => { const address = form.watch("systemEmailAddress") || ""; const displayName = form.watch("systemEmailDisplayName")?.trim(); return ( <> {JSON.stringify( { host: form.watch("systemEmailHost") || "", port: form.watch("systemEmailPort") || "", secure: form.watch("systemEmailSecure") ?? false, auth: { user: form.watch("systemEmailUser") || address, pass: "", }, name: form.watch("systemEmailConnectionHost") || "localhost", pool: form.watch("systemEmailPool") ?? false, tls: { rejectUnauthorized: form.watch("systemEmailRejectUnauthorized") ?? true, ignoreTLS: form.watch("systemEmailIgnoreTLS") ?? false, requireTLS: form.watch("systemEmailRequireTLS") ?? false, servername: form.watch("systemEmailTLSServername") || "", }, }, null, 2 )} {address && ( {`From: ${displayName ? `"${displayName}" <${address}>` : address}`} )} ); })()} } rightContent={ {/* Email Host */} {/* Email Port */} {/* Email Address */} {/* Email Display Name (Optional) */} {/* Email User (Optional) */} {/* Email Password with Reset Pattern */} {isEmailPasswordSet && !emailPasswordHasBeenReset ? ( {t("pages.settings.form.email.option.password.labelSet")} ) : ( )} {/* TLS Servername (Optional) */} {/* Connection Host (Optional) */} {/* Boolean Switches */} {emailSwitches.map(({ name, label }) => ( ))} {/* Test Email Button */} } /> )} )} {/* integrations tab */} {activeTab === "integrations" && ( {isAdmin && ( 0 ? ( {globalProxyEnabled && ( )} ) : ( ) } /> )} {isAdmin && ( {(isApiKeySet === false || apiKeyHasBeenReset === true) && ( )} {isApiKeySet === true && apiKeyHasBeenReset === false && ( {t("pages.settings.form.pagespeed.option.apiKey.labelSet")} )} } /> )} )} {/* data tab */} {activeTab === "data" && ( {/* Export Monitors - Admin Only */} {isAdmin && ( } /> )} {/* Clear All Stats */} {isAdmin && ( setIsStatsDialogOpen(true)} > {t("common.buttons.clear")} } /> )} {/* Remove All Monitors - Admin Only */} {isAdmin && ( } /> )} )} {/* Clear Stats Confirmation Dialog */} setIsStatsDialogOpen(false)} onConfirm={handleClearStats} loading={isDeletingStats} /> {/* Delete All Monitors Confirmation Dialog */} setIsDemoMonitorsDialogOpen(false)} onConfirm={async () => { await deleteAllMonitors("/monitors/"); setIsDemoMonitorsDialogOpen(false); }} loading={isDeletingAllMonitors} confirmColor="error" confirmText={t("common.buttons.removeMonitors")} > {t("pages.settings.form.removeMonitors.dialog.paragraph")} {/* Validation Error Display */} {Object.keys(form.formState.errors).length > 0 && ( {t("pages.settings.form.validation.errorMessage")} {flattenFieldErrors(form.formState.errors).map(({ path, message }) => { const labelKey = FIELD_LABEL_KEY[path]; // Labels read "Name - explanation"; keep the name. const label = labelKey ? t(labelKey).split(" - ")[0] : path; return (
  • revealField(path)} > {label} {message ? `: ${message}` : ""}
  • ); })}
    )}
    ); }; export default SettingsPage;