import { BasePage, ConfigBox, TextLink } from "@/Components/design-elements"; import { Autocomplete, Select, Dialog, SwitchComponent } 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 } from "react"; import { useForm } 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 { Controller } from "react-hook-form"; import { TextField, Button, FieldLabel, SliderWithLabel } 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 timezones from "@/Utils/timezones.json"; import type { RootState } from "@/Types/state"; import { CHECK_TTL_SENTINEL } from "@/Types/Check"; interface Timezone { id: string; name: string; } interface SettingsResponse { settings: any; pagespeedKeySet: boolean; emailPasswordSet: boolean; } export const SettingsPage = () => { const theme = useTheme(); const { t, i18n } = useTranslation(); const dispatch = useDispatch(); const isAdmin = useIsAdmin(); const { toastError } = useToast(); // 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"); // 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 form = useForm({ resolver: zodResolver(schema), defaultValues: defaults, mode: "onChange", }); // 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); // Convert timezones to match AutoComplete format (id instead of _id) const timezoneOptions: Timezone[] = timezones.map((tz) => ({ id: tz._id, name: tz.name, })); const selectedTimezone = timezoneOptions.find((tz) => tz.id === selectedTimezoneId) ?? null; const handleTimezoneChange = (newValue: Timezone | 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 languages = Object.keys(i18n.options.resources || {}); return ( option.name} isOptionEqualToValue={(option: Timezone, value: Timezone) => option.id === value.id } onChange={(_, newValue) => { handleTimezoneChange(newValue as Timezone | null); }} fieldLabel={t("pages.settings.form.timezone.option.timezone.label")} /> } /> } /> {isAdmin && ( {(isApiKeySet === false || apiKeyHasBeenReset === true) && ( ( )} /> )} {isApiKeySet === true && apiKeyHasBeenReset === false && ( {t("pages.settings.form.pagespeed.option.apiKey.labelSet")} )} } /> )} {/* URL Settings */} ( )} /> } /> {/* Clear All Stats */} {isAdmin && ( setIsStatsDialogOpen(true)} > {t("common.buttons.clear")} } /> )} {/* Check Retention */} {isAdmin && ( ( field.onChange(value)} valueLabelDisplay="auto" valueLabelFormat={(value: number) => 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}` } /> )} /> } /> )} {/* Global Thresholds */} {isAdmin && ( ( field.onChange(value)} valueLabelDisplay="auto" /> )} /> ( field.onChange(value)} valueLabelDisplay="auto" /> )} /> ( field.onChange(value)} valueLabelDisplay="auto" /> )} /> ( field.onChange(value)} valueLabelDisplay="auto" /> )} /> } /> )} {/* 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 */} ( { const val = e.target.value; field.onChange(val === "" ? 0 : Number(val)); }} fieldLabel={t("pages.settings.form.email.option.port.label")} type="number" inputProps={{ min: 0 }} placeholder={t("pages.settings.form.email.option.port.placeholder")} error={!!fieldState.error} helperText={fieldState.error?.message} /> )} /> {/* 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 */} {[ { 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"), }, ].map(({ name, label }) => ( ( {label} ) => field.onChange(e.target.checked) } /> )} /> ))} {/* Test Email Button */} } /> )} {/* Demo Monitors - Admin Only */} {isAdmin && ( } /> )} {/* Remove All Monitors - Admin Only */} {isAdmin && ( } /> )} {/* Export Monitors - Admin Only */} {isAdmin && ( } /> )} {/* About */} {t("common.appName")} {__APP_VERSION__} {t("pages.settings.form.about.developedBy")} https://github.com/bluewave-labs/checkmate } /> {/* 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")} {Object.entries(form.formState.errors).map(([field, error]) => { const message = typeof error === "object" && error?.message ? error.message : "Invalid value"; return (
  • {field}: {message}
  • ); })}
    )}
    ); }; export default SettingsPage;