implement schema zod and validation on settings

This commit is contained in:
karenvicent committed 2026-02-16 00:09:08 -05:00
1 parent 6195650dc1
commit 93c15588a4
12 files changed
+343 -422

No files matched your search

+28 -26
View File
@@ -4,32 +4,34 @@ import type { Settings } from "@/Types/Settings";
import type { SettingsFormData } from "@/Validation/settings"; import type { SettingsFormData } from "@/Validation/settings";
interface UseSettingsFormOptions { interface UseSettingsFormOptions {
data?: Settings | null; data?: Settings | null;
} }
export const useSettingsForm = ({ data = null }: UseSettingsFormOptions = {}) => { export const useSettingsForm = ({ data = null }: UseSettingsFormOptions = {}) => {
return useMemo(() => { return useMemo(() => {
const defaults: SettingsFormData = { const defaults: SettingsFormData = {
systemEmailIgnoreTLS: data?.systemEmailIgnoreTLS || false, systemEmailIgnoreTLS: data?.systemEmailIgnoreTLS || false,
systemEmailRequireTLS: data?.systemEmailRequireTLS || false, systemEmailRequireTLS: data?.systemEmailRequireTLS || false,
systemEmailRejectUnauthorized: data?.systemEmailRejectUnauthorized || true, systemEmailRejectUnauthorized: data?.systemEmailRejectUnauthorized || true,
systemEmailConnectionHost: data?.systemEmailConnectionHost || "", systemEmailSecure: data?.systemEmailSecure || false,
systemEmailSecure: data?.systemEmailSecure || true, systemEmailPool: data?.systemEmailPool || false,
systemEmailPool: data?.systemEmailPool || false, showURL: data?.showURL || false,
showURL: data?.showURL || false, systemEmailHost: data?.systemEmailHost || "",
//timezone: data?.timezone || "UTC", systemEmailUser: data?.systemEmailUser || "",
language: data?.language || "en", systemEmailAddress: data?.systemEmailAddress || "",
//chartType: data?.chartType || "histogram", systemEmailConnectionHost: data?.systemEmailConnectionHost || "localhost",
checkTTL: data?.checkTTL || 30, systemEmailTLSServername: data?.systemEmailTLSServername || "",
pagespeedApiKey: data?.pagespeedApiKey || "", systemEmailPort: data?.systemEmailPort || "",
systemEmailHost: data?.systemEmailHost || "", globalThresholds: {
systemEmailPort: data?.systemEmailPort || "", cpu: data?.globalThresholds?.cpu || "",
systemEmailAddress: data?.systemEmailAddress || "", memory: data?.globalThresholds?.memory || "",
systemEmailUser: data?.systemEmailUser || "", disk: data?.globalThresholds?.disk || "",
systemEmailPassword: data?.systemEmailPassword || "", temperature: data?.globalThresholds?.temperature || "",
},
} checkTTL: data?.checkTTL || 30,
pagespeedApiKey: "",
systemEmailPassword: "",
};
return { schema: settingsSchema, defaults };
}, [data]);
} };
}
@@ -8,8 +8,9 @@ import { PropTypes } from "prop-types";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import Dialog from "@/Components/v1/Dialog/index.jsx"; import Dialog from "@/Components/v1/Dialog/index.jsx";
import { useState } from "react"; import { useState } from "react";
import { useDelete, usePost } from "@/Hooks/UseApi";
const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, handleChange, isLoading }) => { const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, isLoading }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const theme = useTheme(); const theme = useTheme();
// Local state // Local state
@@ -18,7 +19,8 @@ const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, handleChange, isLoading }) =
if (!isAdmin) { if (!isAdmin) {
return null; return null;
} }
const { post: postDemoMonitors } = usePost();
const { deleteFn: deleteAllMonitorsFn } = useDelete();
return ( return (
<> <>
<ConfigBox> <ConfigBox>
@@ -38,13 +40,8 @@ const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, handleChange, isLoading }) =
variant="contained" variant="contained"
color="accent" color="accent"
loading={isLoading} loading={isLoading}
onClick={() => { onClick={async () => {
const syntheticEvent = { await postDemoMonitors("/monitors/demo", {});
target: {
name: "demo",
},
};
handleChange(syntheticEvent);
}} }}
sx={{ mt: theme.spacing(4) }} sx={{ mt: theme.spacing(4) }}
> >
@@ -81,13 +78,8 @@ const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, handleChange, isLoading }) =
title={t("settingsPage.systemResetSettings.dialogTitle")} title={t("settingsPage.systemResetSettings.dialogTitle")}
onCancel={() => setIsOpen(false)} onCancel={() => setIsOpen(false)}
confirmationButtonLabel={t("settingsPage.systemResetSettings.dialogConfirm")} confirmationButtonLabel={t("settingsPage.systemResetSettings.dialogConfirm")}
onConfirm={() => { onConfirm={async () => {
const syntheticEvent = { await deleteAllMonitorsFn("/monitors/");
target: {
name: "deleteMonitors",
},
};
handleChange(syntheticEvent);
setIsOpen(false); setIsOpen(false);
}} }}
isLoading={isLoading} isLoading={isLoading}
@@ -99,7 +91,6 @@ const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, handleChange, isLoading }) =
SettingsDemoMonitors.propTypes = { SettingsDemoMonitors.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
handleChange: PropTypes.func,
HEADER_SX: PropTypes.object, HEADER_SX: PropTypes.object,
}; };
+117 -77
View File
@@ -15,16 +15,18 @@ import { PasswordEndAdornment } from "@/Components/v1/Inputs/TextInput/Adornment
import { usePost } from "@/Hooks/UseApi"; import { usePost } from "@/Hooks/UseApi";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { createToast } from "@/Utils/toastUtils.jsx"; import { createToast } from "@/Utils/toastUtils.jsx";
import { Controller } from "react-hook-form";
const SettingsEmail = ({ const SettingsEmail = ({
isAdmin, isAdmin,
HEADER_SX, HEADER_SX,
handleChange,
settingsData,
setSettingsData,
isEmailPasswordSet, isEmailPasswordSet,
emailPasswordHasBeenReset, emailPasswordHasBeenReset,
setEmailPasswordHasBeenReset, setEmailPasswordHasBeenReset,
control,
defaults,
formValues,
setValue,
}) => { }) => {
// Setup // Setup
const { t } = useTranslation(); const { t } = useTranslation();
@@ -44,22 +46,13 @@ const SettingsEmail = ({
systemEmailIgnoreTLS = false, systemEmailIgnoreTLS = false,
systemEmailRequireTLS = false, systemEmailRequireTLS = false,
systemEmailRejectUnauthorized = true, systemEmailRejectUnauthorized = true,
} = settingsData?.settings || {}; } = formValues || {};
// Local state
const [password, setPassword] = useState("");
// Network // Network
const { post: sendTestEmailFn, loading: isSending } = usePost(); const { post: sendTestEmailFn, loading: isSending } = usePost();
const user = useSelector((state) => state.auth.user); const user = useSelector((state) => state.auth.user);
// Handlers // Handlers
const handlePasswordChange = (e) => {
setPassword(e.target.value);
setSettingsData({
...settingsData,
settings: { ...settingsData.settings, systemEmailPassword: e.target.value },
});
};
/** /**
* Handle sending test email with current form values * Handle sending test email with current form values
@@ -70,7 +63,7 @@ const SettingsEmail = ({
!systemEmailHost || !systemEmailHost ||
!systemEmailPort || !systemEmailPort ||
!systemEmailAddress || !systemEmailAddress ||
!(password || systemEmailPassword) !systemEmailPassword
) { ) {
createToast({ createToast({
body: t("settingsPage.emailSettings.toastEmailRequiredFieldsError"), body: t("settingsPage.emailSettings.toastEmailRequiredFieldsError"),
@@ -117,52 +110,87 @@ const SettingsEmail = ({
<Box> <Box>
<Stack gap={theme.spacing(10)}> <Stack gap={theme.spacing(10)}>
<Box> <Box>
<TextInput <Controller
label={t("settingsPage.emailSettings.labelHost")}
name="systemEmailHost" name="systemEmailHost"
placeholder="smtp.gmail.com" control={control}
value={systemEmailHost} defaultValue={defaults.systemEmailHost}
onChange={handleChange} render={({ field, fieldState }) => (
<TextInput
{...field}
label={t("settingsPage.emailSettings.labelHost")}
placeholder="smtp.gmail.com"
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/> />
</Box> </Box>
<Box> <Box>
<TextInput <Controller
label={t("settingsPage.emailSettings.labelPort")}
name="systemEmailPort" name="systemEmailPort"
placeholder="425" control={control}
type="number" defaultValue={defaults.systemEmailPort}
value={systemEmailPort} render={({ field, fieldState }) => (
onChange={handleChange} <TextInput
{...field}
label={t("settingsPage.emailSettings.labelPort")}
placeholder="425"
type="number"
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/> />
</Box> </Box>
<Box> <Box>
<TextInput <Controller
label={t("settingsPage.emailSettings.labelUser")}
name="systemEmailUser" name="systemEmailUser"
placeholder={t("settingsPage.emailSettings.placeholderUser")} control={control}
value={systemEmailUser} defaultValue={defaults.systemEmailUser}
onChange={handleChange} render={({ field, fieldState }) => (
<TextInput
{...field}
label={t("settingsPage.emailSettings.labelUser")}
placeholder={t("settingsPage.emailSettings.placeholderUser")}
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/> />
</Box> </Box>
<Box> <Box>
<TextInput <Controller
label={t("settingsPage.emailSettings.labelAddress")}
name="systemEmailAddress" name="systemEmailAddress"
placeholder="uptime@bluewavelabs.ca" control={control}
value={systemEmailAddress} defaultValue={defaults.systemEmailAddress}
onChange={handleChange} render={({ field, fieldState }) => (
<TextInput
{...field}
label={t("settingsPage.emailSettings.labelAddress")}
placeholder="uptime@bluewavelabs.ca"
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/> />
</Box> </Box>
{(isEmailPasswordSet === false || emailPasswordHasBeenReset === true) && ( {(isEmailPasswordSet === false || emailPasswordHasBeenReset === true) && (
<Box> <Box>
<TextInput <Controller
label={t("settingsPage.emailSettings.labelPassword")}
name="systemEmailPassword" name="systemEmailPassword"
type="password" control={control}
placeholder="123 456 789 101112" defaultValue={defaults.systemEmailPassword}
value={password} render={({ field, fieldState }) => (
onChange={handlePasswordChange} <TextInput
endAdornment={<PasswordEndAdornment />} {...field}
label={t("settingsPage.emailSettings.labelPassword")}
type="password"
placeholder="123 456 789 101112"
endAdornment={<PasswordEndAdornment />}
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/> />
</Box> </Box>
)} )}
@@ -172,11 +200,6 @@ const SettingsEmail = ({
<Typography>{t("settingsPage.emailSettings.labelPasswordSet")}</Typography> <Typography>{t("settingsPage.emailSettings.labelPasswordSet")}</Typography>
<Button <Button
onClick={() => { onClick={() => {
setPassword("");
setSettingsData({
...settingsData,
settings: { ...settingsData.settings, systemEmailPassword: "" },
});
setEmailPasswordHasBeenReset(true); setEmailPasswordHasBeenReset(true);
}} }}
variant="contained" variant="contained"
@@ -188,21 +211,33 @@ const SettingsEmail = ({
</Box> </Box>
)} )}
<Box> <Box>
<TextInput <Controller
label={t("settingsPage.emailSettings.labelTLSServername")}
name="systemEmailTLSServername" name="systemEmailTLSServername"
placeholder="bluewavelabs.ca" control={control}
value={systemEmailTLSServername} defaultValue={defaults.systemEmailTLSServername}
onChange={handleChange} render={({ field, fieldState }) => (
<TextInput
{...field}
label={t("settingsPage.emailSettings.labelTLSServername")}
placeholder="bluewavelabs.ca"
/>
)}
/> />
</Box> </Box>
<Box> <Box>
<TextInput <Controller
label={t("settingsPage.emailSettings.labelConnectionHost")}
name="systemEmailConnectionHost" name="systemEmailConnectionHost"
placeholder="bluewavelabs.ca" control={control}
value={systemEmailConnectionHost} defaultValue={defaults.systemEmailConnectionHost}
onChange={handleChange} render={({ field, fieldState }) => (
<TextInput
{...field}
label={t("settingsPage.emailSettings.labelConnectionHost")}
placeholder="bluewavelabs.ca"
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/> />
</Box> </Box>
<Box <Box
@@ -239,21 +274,29 @@ const SettingsEmail = ({
systemEmailRejectUnauthorized, systemEmailRejectUnauthorized,
], ],
].map(([labelKey, name, value]) => ( ].map(([labelKey, name, value]) => (
<Box <Controller
key={name} key={name}
sx={{ name={name}
display: "flex", control={control}
alignItems: "center", defaultValue={defaults[name]}
justifyContent: "space-between", render={({ field }) => (
}} <Box
> key={name}
<Typography>{t(labelKey)}</Typography> sx={{
<Switch display: "flex",
name={name} alignItems: "center",
checked={value} justifyContent: "space-between",
onChange={handleChange} }}
/> >
</Box> <Typography>{t(labelKey)}</Typography>
<Switch
{...field}
checked={field.value}
/>
</Box>
)}
/>
))} ))}
<TextLink <TextLink
@@ -299,9 +342,9 @@ const SettingsEmail = ({
<pre> <pre>
{JSON.stringify({ {JSON.stringify({
systemEmailHost, systemEmailHost: systemEmailHost,
systemEmailAddress, systemEmailAddress: systemEmailAddress,
systemEmailPassword, systemEmailPassword: systemEmailPassword,
})} })}
</pre> </pre>
@@ -328,9 +371,6 @@ const SettingsEmail = ({
SettingsEmail.propTypes = { SettingsEmail.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
settingsData: PropTypes.object,
setSettingsData: PropTypes.func,
handleChange: PropTypes.func,
HEADER_SX: PropTypes.object, HEADER_SX: PropTypes.object,
isPasswordSet: PropTypes.bool, isPasswordSet: PropTypes.bool,
}; };
+26 -10
View File
@@ -8,8 +8,9 @@ import { PropTypes } from "prop-types";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import Dialog from "@/Components/v1/Dialog/index.jsx"; import Dialog from "@/Components/v1/Dialog/index.jsx";
import { useState } from "react"; import { useState } from "react";
import { useLazyGet } from "@/Hooks/UseApi";
const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, handleChange, isLoading }) => { const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, isLoading }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const theme = useTheme(); const theme = useTheme();
// Local state // Local state
@@ -18,6 +19,29 @@ const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, handleChange, isLoading }) =
if (!isAdmin) { if (!isAdmin) {
return null; return null;
} }
const { get: fetchJson } = useLazyGet();
const handleExport = async () => {
const res = await fetchJson("/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);
return;
};
return ( return (
<> <>
@@ -38,14 +62,7 @@ const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, handleChange, isLoading }) =
variant="contained" variant="contained"
color="accent" color="accent"
loading={isLoading} loading={isLoading}
onClick={() => { onClick={handleExport}
const syntheticEvent = {
target: {
name: "export",
},
};
handleChange(syntheticEvent);
}}
sx={{ mt: theme.spacing(4) }} sx={{ mt: theme.spacing(4) }}
> >
Export Monitors to JSON Export Monitors to JSON
@@ -58,7 +75,6 @@ const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, handleChange, isLoading }) =
SettingsDemoMonitors.propTypes = { SettingsDemoMonitors.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
handleChange: PropTypes.func,
HEADER_SX: PropTypes.object, HEADER_SX: PropTypes.object,
}; };
@@ -7,39 +7,18 @@ import TextInput from "@/Components/v1/Inputs/TextInput/index.jsx";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { PropTypes } from "prop-types"; import { PropTypes } from "prop-types";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Controller } from "react-hook-form";
const SettingsGlobalThresholds = ({ const SettingsGlobalThresholds = ({
isAdmin, isAdmin,
HEADING_SX, HEADING_SX,
settingsData,
setSettingsData, control,
defaults,
}) => { }) => {
const { t } = useTranslation(); // For language translation const { t } = useTranslation(); // For language translation
const theme = useTheme(); // MUI theme access const theme = useTheme(); // MUI theme access
// Handles input change and updates parent state
const handleChange = (e, min, max) => {
const { name, value } = e.target;
const numValue = parseFloat(value);
const isValidNumber =
value === "" ||
(!isNaN(numValue) && isFinite(numValue) && numValue >= min && numValue <= max);
if (isValidNumber) {
setSettingsData((prev) => ({
...prev,
settings: {
...prev.settings,
globalThresholds: {
...prev.settings?.globalThresholds,
[name]: value,
},
},
}));
}
};
// Only render this section for admins // Only render this section for admins
if (!isAdmin) return null; if (!isAdmin) return null;
@@ -69,14 +48,21 @@ const SettingsGlobalThresholds = ({
["Disk Threshold (%)", "disk", 1, 100], ["Disk Threshold (%)", "disk", 1, 100],
["Temperature Threshold (°C)", "temperature", 1, 150], ["Temperature Threshold (°C)", "temperature", 1, 150],
].map(([label, name, min, max]) => ( ].map(([label, name, min, max]) => (
<TextInput <Controller
key={name} key={name}
name={name} name={`globalThresholds.${name}`}
label={label} control={control}
placeholder={`${min} - ${max}`} defaultValue={defaults.globalThresholds?.[name]}
type="number" render={({ field, fieldState }) => (
value={settingsData?.settings?.globalThresholds?.[name] || ""} <TextInput
onChange={(e) => handleChange(e, min, max)} {...field}
label={label}
placeholder={`${min} - ${max}`}
type="number"
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/> />
))} ))}
</Stack> </Stack>
@@ -88,8 +74,6 @@ const SettingsGlobalThresholds = ({
SettingsGlobalThresholds.propTypes = { SettingsGlobalThresholds.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
HEADING_SX: PropTypes.object, HEADING_SX: PropTypes.object,
settingsData: PropTypes.object,
setSettingsData: PropTypes.func,
}; };
export default SettingsGlobalThresholds; export default SettingsGlobalThresholds;
+19 -25
View File
@@ -10,15 +10,17 @@ import { useTheme } from "@emotion/react";
import { PropTypes } from "prop-types"; import { PropTypes } from "prop-types";
import { useState } from "react"; import { useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Controller } from "react-hook-form";
const SettingsPagespeed = ({ const SettingsPagespeed = ({
isAdmin, isAdmin,
HEADING_SX, HEADING_SX,
settingsData,
setSettingsData,
isApiKeySet, isApiKeySet,
apiKeyHasBeenReset, apiKeyHasBeenReset,
setApiKeyHasBeenReset, setApiKeyHasBeenReset,
defaults,
control,
setValue,
}) => { }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const theme = useTheme(); const theme = useTheme();
@@ -26,15 +28,6 @@ const SettingsPagespeed = ({
// Local state // Local state
const [apiKey, setApiKey] = useState(""); const [apiKey, setApiKey] = useState("");
// Handler
const handleChange = (e) => {
setApiKey(e.target.value);
setSettingsData({
...settingsData,
settings: { ...settingsData.settings, pagespeedApiKey: e.target.value },
});
};
if (!isAdmin) { if (!isAdmin) {
return null; return null;
} }
@@ -54,14 +47,21 @@ const SettingsPagespeed = ({
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
{(isApiKeySet === false || apiKeyHasBeenReset === true) && ( {(isApiKeySet === false || apiKeyHasBeenReset === true) && (
<TextInput <Controller
name="pagespeedApiKey" name="pagespeedApiKey"
label={t("settingsPage.pageSpeedSettings.labelApiKey")} control={control}
value={apiKey} defaultValue={defaults.pagespeedApiKey}
type={"password"} render={({ field, fieldState }) => (
onChange={handleChange} <TextInput
optionalLabel="(Optional)" {...field}
endAdornment={<PasswordEndAdornment />} label={t("settingsPage.pageSpeedSettings.labelApiKey")}
type={"password"}
optionalLabel="(Optional)"
endAdornment={<PasswordEndAdornment />}
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/> />
)} )}
@@ -70,11 +70,7 @@ const SettingsPagespeed = ({
<Typography>{t("settingsPage.pageSpeedSettings.labelApiKeySet")}</Typography> <Typography>{t("settingsPage.pageSpeedSettings.labelApiKeySet")}</Typography>
<Button <Button
onClick={() => { onClick={() => {
setApiKey(""); setValue("pagespeedApiKey", "");
setSettingsData({
...settingsData,
settings: { ...settingsData.settings, pagespeedApiKey: "" },
});
setApiKeyHasBeenReset(true); setApiKeyHasBeenReset(true);
}} }}
variant="contained" variant="contained"
@@ -93,8 +89,6 @@ const SettingsPagespeed = ({
SettingsPagespeed.propTypes = { SettingsPagespeed.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
HEADING_SX: PropTypes.object, HEADING_SX: PropTypes.object,
settingsData: PropTypes.object,
setSettingsData: PropTypes.func,
isApiKeySet: PropTypes.bool, isApiKeySet: PropTypes.bool,
setIsApiKeySet: PropTypes.func, setIsApiKeySet: PropTypes.func,
apiKeyHasBeenReset: PropTypes.bool, apiKeyHasBeenReset: PropTypes.bool,
+6 -10
View File
@@ -11,8 +11,9 @@ import { useTheme } from "@emotion/react";
import { PropTypes } from "prop-types"; import { PropTypes } from "prop-types";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useState } from "react"; import { useState } from "react";
import { useDelete } from "@/Hooks/UseApi";
const SettingsStats = ({ isAdmin, HEADING_SX, handleChange, settingsData, errors }) => { const SettingsStats = ({ isAdmin, HEADING_SX, errors }) => {
const theme = useTheme(); const theme = useTheme();
const { t } = useTranslation(); const { t } = useTranslation();
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
@@ -20,6 +21,7 @@ const SettingsStats = ({ isAdmin, HEADING_SX, handleChange, settingsData, errors
if (!isAdmin) { if (!isAdmin) {
return null; return null;
} }
const { deleteFn: deleteMonitorStatsFn } = useDelete();
return ( return (
<ConfigBox> <ConfigBox>
@@ -59,13 +61,9 @@ const SettingsStats = ({ isAdmin, HEADING_SX, handleChange, settingsData, errors
confirmationButtonLabel={t( confirmationButtonLabel={t(
"settingsPage.statsSettings.clearAllStatsDialogConfirm" "settingsPage.statsSettings.clearAllStatsDialogConfirm"
)} )}
onConfirm={() => { onConfirm={async () => {
const syntheticEvent = { await deleteMonitorStatsFn("/checks/team");
target: {
name: "deleteStats",
},
};
handleChange(syntheticEvent);
setIsOpen(false); setIsOpen(false);
}} }}
isLoading={false} isLoading={false}
@@ -77,8 +75,6 @@ const SettingsStats = ({ isAdmin, HEADING_SX, handleChange, settingsData, errors
SettingsStats.propTypes = { SettingsStats.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
HEADING_SX: PropTypes.object, HEADING_SX: PropTypes.object,
handleChange: PropTypes.func,
settingsData: PropTypes.object,
errors: PropTypes.object, errors: PropTypes.object,
}; };
+10 -15
View File
@@ -7,31 +7,28 @@ import timezones from "@/Utils/timezones.json";
// Utils // Utils
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useSelector, useDispatch } from "react-redux";
import { setTimezone } from "@/Features/UI/uiSlice.js";
import { PropTypes } from "prop-types"; import { PropTypes } from "prop-types";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useCallback, useMemo, useState } from "react"; import { useCallback, useMemo, useState } from "react";
const SettingsTimeZone = ({ HEADING_SX, handleChange, timezone }) => { const SettingsTimeZone = ({ HEADING_SX }) => {
const theme = useTheme(); const theme = useTheme();
const { t } = useTranslation(); const { t } = useTranslation();
const [rawInput, setRawInput] = useState(""); const [rawInput, setRawInput] = useState("");
const dispatch = useDispatch();
const { timezone } = useSelector((state) => state.ui);
const selectedTimezone = useMemo( const selectedTimezone = useMemo(
() => timezones.find((tz) => tz._id === timezone) ?? null, () => timezones.find((tz) => tz._id === timezone) ?? null,
[timezone] [timezone]
); );
const handleTimezoneChange = useCallback( const handleTimezoneChange = (newValue) => {
(newValue) => { setRawInput("");
setRawInput(""); const newId = newValue?._id ?? "";
handleChange({ dispatch(setTimezone({ timezone: newId }));
target: { };
name: "timezone",
value: newValue?._id ?? "",
},
});
},
[handleChange]
);
return ( return (
<ConfigBox> <ConfigBox>
@@ -68,8 +65,6 @@ const SettingsTimeZone = ({ HEADING_SX, handleChange, timezone }) => {
SettingsTimeZone.propTypes = { SettingsTimeZone.propTypes = {
HEADING_SX: PropTypes.object, HEADING_SX: PropTypes.object,
handleChange: PropTypes.func,
timezone: PropTypes.string,
}; };
export default SettingsTimeZone; export default SettingsTimeZone;
+12 -8
View File
@@ -11,11 +11,19 @@ import { lightTheme, darkTheme } from "@/Utils/Theme/v2Theme";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { PropTypes } from "prop-types"; import { PropTypes } from "prop-types";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useSelector, useDispatch } from "react-redux";
import { setMode, setLanguage, setChartType } from "@/Features/UI/uiSlice.js";
const SettingsUI = ({ HEADING_SX, handleChange, mode, language, chartType }) => { const SettingsUI = ({ HEADING_SX }) => {
const {
mode,
language = "en",
chartType = "histogram",
} = useSelector((state) => state.ui);
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const theme = useTheme(); const theme = useTheme();
const languages = Object.keys(i18n.options.resources || {}); const languages = Object.keys(i18n.options.resources || {});
const dispatch = useDispatch();
const v2Theme = mode === "dark" ? darkTheme : lightTheme; const v2Theme = mode === "dark" ? darkTheme : lightTheme;
return ( return (
<ConfigBox> <ConfigBox>
@@ -35,7 +43,7 @@ const SettingsUI = ({ HEADING_SX, handleChange, mode, language, chartType }) =>
name="mode" name="mode"
label={t("settingsPage.uiSettings.labelTheme")} label={t("settingsPage.uiSettings.labelTheme")}
value={mode} value={mode}
onChange={handleChange} onChange={(e) => dispatch(setMode(e.target.value))}
items={[ items={[
{ _id: "light", name: "Light" }, { _id: "light", name: "Light" },
{ _id: "dark", name: "Dark" }, { _id: "dark", name: "Dark" },
@@ -45,14 +53,14 @@ const SettingsUI = ({ HEADING_SX, handleChange, mode, language, chartType }) =>
name="language" name="language"
label={t("settingsPage.uiSettings.labelLanguage")} label={t("settingsPage.uiSettings.labelLanguage")}
value={language} value={language}
onChange={handleChange} onChange={(e) => dispatch(setLanguage(e.target.value))}
items={languages.map((lang) => ({ _id: lang, name: lang.toUpperCase() }))} items={languages.map((lang) => ({ _id: lang, name: lang.toUpperCase() }))}
></Select> ></Select>
<Select <Select
name="chartType" name="chartType"
label={t("settingsPage.uiSettings.labelChartType")} label={t("settingsPage.uiSettings.labelChartType")}
value={chartType} value={chartType}
onChange={handleChange} onChange={(e) => dispatch(setChartType(e.target.value))}
items={[ items={[
{ _id: "histogram", name: t("settingsPage.uiSettings.chartTypeHistogram") }, { _id: "histogram", name: t("settingsPage.uiSettings.chartTypeHistogram") },
{ _id: "heatmap", name: t("settingsPage.uiSettings.chartTypeHeatmap") }, { _id: "heatmap", name: t("settingsPage.uiSettings.chartTypeHeatmap") },
@@ -68,10 +76,6 @@ const SettingsUI = ({ HEADING_SX, handleChange, mode, language, chartType }) =>
SettingsUI.propTypes = { SettingsUI.propTypes = {
HEADING_SX: PropTypes.object, HEADING_SX: PropTypes.object,
handleChange: PropTypes.func,
mode: PropTypes.string,
language: PropTypes.string,
chartType: PropTypes.string,
}; };
export default SettingsUI; export default SettingsUI;
+18 -12
View File
@@ -3,13 +3,14 @@ import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import ConfigBox from "@/Components/v1/ConfigBox/index.jsx"; import ConfigBox from "@/Components/v1/ConfigBox/index.jsx";
import Select from "@/Components/v1/Inputs/Select/index.jsx"; import Select from "@/Components/v1/Inputs/Select/index.jsx";
import { Controller } from "react-hook-form";
// Utils // Utils
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { PropTypes } from "prop-types"; import { PropTypes } from "prop-types";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
const SettingsURL = ({ HEADING_SX, handleChange, showURL = false }) => { const SettingsURL = ({ HEADING_SX, control, defaults }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const theme = useTheme(); const theme = useTheme();
return ( return (
@@ -26,16 +27,23 @@ const SettingsURL = ({ HEADING_SX, handleChange, showURL = false }) => {
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
<Select <Controller
name="showURL" name="showURL"
label={t("settingsPage.urlSettings.label")} control={control}
value={showURL === true} defaultValue={defaults.showURL}
onChange={handleChange} render={({ field, fieldState }) => (
items={[ <Select
{ _id: true, name: t("settingsPage.urlSettings.selectEnabled") }, {...field}
{ _id: false, name: t("settingsPage.urlSettings.selectDisabled") }, error={!!fieldState.error}
]} helperText={fieldState.error?.message}
></Select> label={t("settingsPage.urlSettings.label")}
items={[
{ _id: true, name: t("settingsPage.urlSettings.selectEnabled") },
{ _id: false, name: t("settingsPage.urlSettings.selectDisabled") },
]}
/>
)}
/>
</Stack> </Stack>
</ConfigBox> </ConfigBox>
); );
@@ -43,8 +51,6 @@ const SettingsURL = ({ HEADING_SX, handleChange, showURL = false }) => {
SettingsURL.propTypes = { SettingsURL.propTypes = {
HEADING_SX: PropTypes.object, HEADING_SX: PropTypes.object,
handleChange: PropTypes.func,
showURL: PropTypes.bool,
}; };
export default SettingsURL; export default SettingsURL;
+57 -180
View File
@@ -13,17 +13,14 @@ import SettingsExport from "./SettingsExport.jsx";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
// Utils // Utils
import { settingsValidation } from "@/Validation/validation.js"; import { settingsValidation } from "@/Validation/validation.js";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useSettingsForm } from "@/Hooks/useSettingsForm.js";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useSelector, useDispatch } from "react-redux"; import { useSelector, useDispatch } from "react-redux";
import {
setTimezone,
setMode,
setLanguage,
setShowURL,
setChartType,
} from "@/Features/UI/uiSlice.js";
import SettingsStats from "./SettingsStats.jsx"; import SettingsStats from "./SettingsStats.jsx";
import { useIsAdmin } from "@/Hooks/useIsAdmin.js"; import { useIsAdmin } from "@/Hooks/useIsAdmin.js";
@@ -32,31 +29,42 @@ import { useGet, usePost, useDelete, useLazyGet, usePatch } from "@/Hooks/UseApi
const BREADCRUMBS = [{ name: `Settings`, path: "/settings" }]; const BREADCRUMBS = [{ name: `Settings`, path: "/settings" }];
const Settings = () => { const Settings = () => {
// Redux state const { data: fetchedSettings, isLoading: isSettingsLoading } = useGet("/settings");
const {
mode,
language = "en",
timezone,
showURL,
chartType = "histogram",
} = useSelector((state) => state.ui);
// Local state // Local state
const [settingsData, setSettingsData] = useState({});
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const [isApiKeySet, setIsApiKeySet] = useState(settingsData?.pagespeedKeySet ?? false); const [isApiKeySet, setIsApiKeySet] = useState(
fetchedSettings?.pagespeedKeySet ?? false
);
const [apiKeyHasBeenReset, setApiKeyHasBeenReset] = useState(false); const [apiKeyHasBeenReset, setApiKeyHasBeenReset] = useState(false);
const [isEmailPasswordSet, setIsEmailPasswordSet] = useState( const [isEmailPasswordSet, setIsEmailPasswordSet] = useState(
settingsData?.emailPasswordSet ?? false fetchedSettings?.emailPasswordSet ?? false
); );
const [emailPasswordHasBeenReset, setEmailPasswordHasBeenReset] = useState(false); const [emailPasswordHasBeenReset, setEmailPasswordHasBeenReset] = useState(false);
// Network // Network
const { data: fetchedSettings, isLoading: isSettingsLoading } = useGet("/settings");
const { schema, defaults } = useSettingsForm({ data: fetchedSettings?.settings });
const form = useForm({
resolver: zodResolver(schema),
defaultValues: defaults,
});
const {
control,
watch,
reset,
handleSubmit,
clearErrors,
trigger,
getValues,
setValue,
formState: { dirtyFields },
} = form;
useEffect(() => {
reset(defaults);
}, [defaults, reset]);
useEffect(() => { useEffect(() => {
if (fetchedSettings) { if (fetchedSettings) {
setSettingsData(fetchedSettings);
setIsApiKeySet(fetchedSettings?.pagespeedKeySet); setIsApiKeySet(fetchedSettings?.pagespeedKeySet);
setIsEmailPasswordSet(fetchedSettings?.emailPasswordSet); setIsEmailPasswordSet(fetchedSettings?.emailPasswordSet);
} }
@@ -76,14 +84,24 @@ const Settings = () => {
if (data.emailPasswordSet === true) { if (data.emailPasswordSet === true) {
setEmailPasswordHasBeenReset(false); setEmailPasswordHasBeenReset(false);
} }
setSettingsData(data);
} }
}; };
const onSubmit = async (data) => {
const toSubmit = { ...data };
if (!form.formState.dirtyFields.systemEmailPassword) {
delete toSubmit.systemEmailPassword;
}
if (!form.formState.dirtyFields.pagespeedApiKey) {
delete toSubmit.pagespeedApiKey;
}
saveSettings(toSubmit);
};
// New API hooks to replace monitorHooks // New API hooks to replace monitorHooks
const { post: postDemoMonitors, loading: isAddingDemoMonitors } = usePost(); const { loading: isAddingDemoMonitors } = usePost();
const { deleteFn: deleteAllMonitorsFn, loading: isDeletingMonitors } = useDelete(); const { loading: isDeletingMonitors } = useDelete();
const { deleteFn: deleteMonitorStatsFn, loading: isDeletingMonitorStats } = useDelete(); const { loading: isDeletingMonitorStats } = useDelete();
const { get: fetchJson, loading: isFetchingJson } = useLazyGet(); const { get: fetchJson, loading: isFetchingJson } = useLazyGet();
// Setup // Setup
@@ -92,184 +110,43 @@ const Settings = () => {
const HEADING_SX = { mt: theme.spacing(2), mb: theme.spacing(2) }; const HEADING_SX = { mt: theme.spacing(2), mb: theme.spacing(2) };
const { t } = useTranslation(); const { t } = useTranslation();
const dispatch = useDispatch(); const dispatch = useDispatch();
// Handlers
const handleChange = async (e) => {
const { name, value, checked } = e.target;
let newValue;
if (
name === "systemEmailIgnoreTLS" ||
name === "systemEmailRequireTLS" ||
name === "systemEmailRejectUnauthorized" ||
name === "systemEmailSecure" ||
name === "systemEmailPool"
) {
newValue = checked;
}
// Ensure showURL is a proper boolean
if (name === "showURL") {
newValue = value === true || value === "true";
}
// Build next state early
const newSettingsData = {
...settingsData,
settings: { ...settingsData.settings, [name]: newValue ?? value },
};
if (name === "timezone") {
dispatch(setTimezone({ timezone: value }));
return;
}
if (name === "mode") {
dispatch(setMode(value));
return;
}
if (name === "language") {
dispatch(setLanguage(value));
return;
}
if (name === "chartType") {
dispatch(setChartType(value));
return;
}
if (name === "deleteStats") {
await deleteMonitorStatsFn("/checks/team");
return;
}
if (name === "demo") {
await postDemoMonitors("/monitors/demo", {});
return;
}
if (name === "deleteMonitors") {
await deleteAllMonitorsFn("/monitors/");
return;
}
if (name === "export") {
const res = await fetchJson("/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);
return;
}
setSettingsData(newSettingsData);
// Update Redux immediately for UI feedback
if (name === "showURL") {
dispatch(setShowURL(newValue));
}
};
const handleSave = () => {
// Validate]
const toSubmit = {
checkTTL: settingsData.settings.checkTTL,
pagespeedApiKey: settingsData.settings.pagespeedApiKey,
language: settingsData.settings.language,
timezone: settingsData.settings.timezone,
systemEmailHost: settingsData.settings.systemEmailHost,
systemEmailPort: settingsData.settings.systemEmailPort,
systemEmailSecure: settingsData.settings.systemEmailSecure,
systemEmailPool: settingsData.settings.systemEmailPool,
systemEmailAddress: settingsData.settings.systemEmailAddress,
systemEmailPassword: settingsData.settings.systemEmailPassword,
systemEmailUser: settingsData.settings.systemEmailUser,
systemEmailConnectionHost: settingsData.settings.systemEmailConnectionHost,
systemEmailTLSServername: settingsData.settings.systemEmailTLSServername,
systemEmailIgnoreTLS: settingsData.settings.systemEmailIgnoreTLS,
systemEmailRequireTLS: settingsData.settings.systemEmailRequireTLS,
systemEmailRejectUnauthorized: settingsData.settings.systemEmailRejectUnauthorized,
showURL: settingsData.settings.showURL,
globalThresholds: settingsData.settings.globalThresholds,
};
const { error } = settingsValidation.validate(toSubmit, {
abortEarly: false,
});
if (!error || error.details.length === 0) {
setErrors({});
saveSettings(toSubmit);
} else {
const newErrors = {};
error.details.forEach((err) => {
newErrors[err.path[0]] = err.message;
});
setErrors(newErrors);
}
};
return ( return (
<Stack gap={theme.spacing(10)}> <Stack gap={theme.spacing(10)}>
<Breadcrumbs list={BREADCRUMBS} /> <Breadcrumbs list={BREADCRUMBS} />
<Typography variant="h1">{t("settingsPage.title")}</Typography> <Typography variant="h1">{t("settingsPage.title")}</Typography>
<SettingsTimeZone <SettingsTimeZone HEADING_SX={HEADING_SX} />
HEADING_SX={HEADING_SX} <SettingsUI HEADING_SX={HEADING_SX} />
handleChange={handleChange}
timezone={timezone}
/>
<SettingsUI
HEADING_SX={HEADING_SX}
handleChange={handleChange}
mode={mode}
language={language}
chartType={chartType}
/>
<SettingsPagespeed <SettingsPagespeed
isAdmin={isAdmin} isAdmin={isAdmin}
HEADING_SX={HEADING_SX} HEADING_SX={HEADING_SX}
settingsData={settingsData}
setSettingsData={setSettingsData}
isApiKeySet={isApiKeySet} isApiKeySet={isApiKeySet}
apiKeyHasBeenReset={apiKeyHasBeenReset} apiKeyHasBeenReset={apiKeyHasBeenReset}
setApiKeyHasBeenReset={setApiKeyHasBeenReset} setApiKeyHasBeenReset={setApiKeyHasBeenReset}
control={control}
defaults={defaults}
setValue={setValue}
/> />
<SettingsURL <SettingsURL
HEADING_SX={HEADING_SX} HEADING_SX={HEADING_SX}
handleChange={handleChange} control={control}
showURL={showURL} defaults={defaults}
/> />
<SettingsStats <SettingsStats
isAdmin={isAdmin} isAdmin={isAdmin}
HEADING_SX={HEADING_SX} HEADING_SX={HEADING_SX}
settingsData={settingsData}
handleChange={handleChange}
errors={errors} errors={errors}
/> />
<SettingsGlobalThresholds <SettingsGlobalThresholds
isAdmin={isAdmin} isAdmin={isAdmin}
HEADING_SX={HEADING_SX} HEADING_SX={HEADING_SX}
settingsData={settingsData} control={control}
setSettingsData={setSettingsData} defaults={defaults}
/> />
<SettingsDemoMonitors <SettingsDemoMonitors
isAdmin={isAdmin} isAdmin={isAdmin}
HEADER_SX={HEADING_SX} HEADER_SX={HEADING_SX}
handleChange={handleChange}
isLoading={ isLoading={
isSettingsLoading || isSaving || isDeletingMonitorStats || isAddingDemoMonitors isSettingsLoading || isSaving || isDeletingMonitorStats || isAddingDemoMonitors
} }
@@ -277,18 +154,18 @@ const Settings = () => {
<SettingsEmail <SettingsEmail
isAdmin={isAdmin} isAdmin={isAdmin}
HEADER_SX={HEADING_SX} HEADER_SX={HEADING_SX}
handleChange={handleChange}
settingsData={settingsData}
setSettingsData={setSettingsData}
isEmailPasswordSet={isEmailPasswordSet} isEmailPasswordSet={isEmailPasswordSet}
emailPasswordHasBeenReset={emailPasswordHasBeenReset} emailPasswordHasBeenReset={emailPasswordHasBeenReset}
setEmailPasswordHasBeenReset={setEmailPasswordHasBeenReset} setEmailPasswordHasBeenReset={setEmailPasswordHasBeenReset}
control={control}
defaults={defaults}
formValues={watch()}
setValue={setValue}
/> />
<SettingsExport <SettingsExport
isAdmin={isAdmin} isAdmin={isAdmin}
HEADER_SX={HEADING_SX} HEADER_SX={HEADING_SX}
handleChange={handleChange}
isLoading={isSettingsLoading || isSaving || isFetchingJson} isLoading={isSettingsLoading || isSaving || isFetchingJson}
/> />
<SettingsAbout /> <SettingsAbout />
@@ -322,7 +199,7 @@ const Settings = () => {
variant="contained" variant="contained"
color="accent" color="accent"
sx={{ px: theme.spacing(12), py: theme.spacing(8) }} sx={{ px: theme.spacing(12), py: theme.spacing(8) }}
onClick={handleSave} onClick={handleSubmit(onSubmit)}
> >
{t("settingsPage.saveButtonLabel")} {t("settingsPage.saveButtonLabel")}
</Button> </Button>
+24 -8
View File
@@ -8,10 +8,6 @@ export const settingsSchema = z.object({
systemEmailSecure: z.boolean().optional(), systemEmailSecure: z.boolean().optional(),
systemEmailPool: z.boolean().optional(), systemEmailPool: z.boolean().optional(),
showURL: z.boolean().optional(), showURL: z.boolean().optional(),
timezone: z.string().min(1, "Timezone is required").optional(),
mode: z.enum(["light", "dark"]).optional(),
language: z.string().min(2, "Language is required"),
chartType: z.enum(["histogram", "heatmap"]).optional(),
checkTTL: z.coerce.number().int().min(1, "Please enter a value"), checkTTL: z.coerce.number().int().min(1, "Please enter a value"),
pagespeedApiKey: z.string().optional().or(z.literal("")), pagespeedApiKey: z.string().optional().or(z.literal("")),
systemEmailHost: z.string().optional().or(z.literal("")), systemEmailHost: z.string().optional().or(z.literal("")),
@@ -26,10 +22,30 @@ export const settingsSchema = z.object({
systemEmailTLSServername: z.string().optional().or(z.literal("")), systemEmailTLSServername: z.string().optional().or(z.literal("")),
globalThresholds: z globalThresholds: z
.object({ .object({
cpu: z.coerce.number().min(1).max(100).optional(), cpu: z.coerce
memory: z.coerce.number().min(1).max(100).optional(), .number()
disk: z.coerce.number().min(1).max(100).optional(), .min(1, "Min 1%")
temperature: z.coerce.number().min(1).max(150).optional(), .max(100, "Max 100%")
.optional()
.or(z.literal("")),
memory: z.coerce
.number()
.min(1, "Min 1%")
.max(100, "Max 100%")
.optional()
.or(z.literal("")),
disk: z.coerce
.number()
.min(1, "Min 1%")
.max(100, "Max 100%")
.optional()
.or(z.literal("")),
temperature: z.coerce
.number()
.min(1, "Min 1°C")
.max(150, "Max 150°C")
.optional()
.or(z.literal("")),
}) })
.optional(), .optional(),
}); });