Merge pull request #3288 from bluewave-labs/settings-zod-schema

Settings zod schema
This commit is contained in:
Alexander Holliday authored and GitHub committed 2026-02-18 09:32:28 -08:00
commit dab465b8c5
14 files changed
+640 -562

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
import { useMemo } from "react";
import { settingsSchema } from "@/Validation/settings";
import type { Settings } from "@/Types/Settings";
import type { SettingsFormData } from "@/Validation/settings";
interface UseSettingsFormOptions {
data?: Settings | null;
}
export const useSettingsForm = ({ data = null }: UseSettingsFormOptions = {}) => {
return useMemo(() => {
const defaults: SettingsFormData = {
systemEmailIgnoreTLS: data?.systemEmailIgnoreTLS || false,
systemEmailRequireTLS: data?.systemEmailRequireTLS || false,
systemEmailRejectUnauthorized: data?.systemEmailRejectUnauthorized || true,
systemEmailSecure: data?.systemEmailSecure || false,
systemEmailPool: data?.systemEmailPool || false,
showURL: data?.showURL || false,
systemEmailHost: data?.systemEmailHost || "",
systemEmailUser: data?.systemEmailUser || "",
systemEmailAddress: data?.systemEmailAddress || "",
systemEmailConnectionHost: data?.systemEmailConnectionHost || "localhost",
systemEmailTLSServername: data?.systemEmailTLSServername || "",
systemEmailPort: data?.systemEmailPort || "",
globalThresholds: {
cpu: data?.globalThresholds?.cpu || "",
memory: data?.globalThresholds?.memory || "",
disk: data?.globalThresholds?.disk || "",
temperature: data?.globalThresholds?.temperature || "",
},
checkTTL: data?.checkTTL || 30,
pagespeedApiKey: "",
systemEmailPassword: "",
};
return { schema: settingsSchema, defaults };
}, [data]);
};
+2 -2
View File
@@ -16,7 +16,7 @@ const SettingsAbout = () => {
component="h1" component="h1"
variant="h2" variant="h2"
> >
{t("settingsPage.aboutSettings.title")} {t("pages.settings.aboutSettings.title")}
</Typography> </Typography>
</Box> </Box>
<Box> <Box>
@@ -24,7 +24,7 @@ const SettingsAbout = () => {
{t("common.appName")} {__APP_VERSION__} {t("common.appName")} {__APP_VERSION__}
</Typography> </Typography>
<Typography sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }}> <Typography sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }}>
{t("settingsPage.aboutSettings.labelDevelopedBy")} {t("pages.settings.aboutSettings.labelDevelopedBy")}
</Typography> </Typography>
<Link <Link
level="secondary" level="secondary"
@@ -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>
@@ -27,10 +29,10 @@ const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, handleChange, isLoading }) =
component="h1" component="h1"
variant="h2" variant="h2"
> >
{t("settingsPage.demoMonitorsSettings.title")} {t("pages.settings.demoMonitorsSettings.title")}
</Typography> </Typography>
<Typography sx={HEADER_SX}> <Typography sx={HEADER_SX}>
{t("settingsPage.demoMonitorsSettings.description")} {t("pages.settings.demoMonitorsSettings.description")}
</Typography> </Typography>
</Box> </Box>
<Box> <Box>
@@ -38,17 +40,12 @@ 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) }}
> >
{t("settingsPage.demoMonitorsSettings.buttonAddMonitors")} {t("pages.settings.demoMonitorsSettings.buttonAddMonitors")}
</Button> </Button>
</Box> </Box>
</ConfigBox> </ConfigBox>
@@ -58,10 +55,10 @@ const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, handleChange, isLoading }) =
component="h1" component="h1"
variant="h2" variant="h2"
> >
{t("settingsPage.systemResetSettings.title")} {t("pages.settings.systemResetSettings.title")}
</Typography> </Typography>
<Typography sx={{ mt: theme.spacing(2) }}> <Typography sx={{ mt: theme.spacing(2) }}>
{t("settingsPage.systemResetSettings.description")} {t("pages.settings.systemResetSettings.description")}
</Typography> </Typography>
</Box> </Box>
<Box> <Box>
@@ -72,22 +69,17 @@ const SettingsDemoMonitors = ({ isAdmin, HEADER_SX, handleChange, isLoading }) =
onClick={() => setIsOpen(true)} onClick={() => setIsOpen(true)}
sx={{ mt: theme.spacing(4) }} sx={{ mt: theme.spacing(4) }}
> >
{t("settingsPage.systemResetSettings.buttonRemoveAllMonitors")} {t("pages.settings.systemResetSettings.buttonRemoveAllMonitors")}
</Button> </Button>
</Box> </Box>
<Dialog <Dialog
open={isOpen} open={isOpen}
theme={theme} theme={theme}
title={t("settingsPage.systemResetSettings.dialogTitle")} title={t("pages.settings.systemResetSettings.dialogTitle")}
onCancel={() => setIsOpen(false)} onCancel={() => setIsOpen(false)}
confirmationButtonLabel={t("settingsPage.systemResetSettings.dialogConfirm")} confirmationButtonLabel={t("pages.settings.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,
}; };
+247 -216
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,10 +63,10 @@ const SettingsEmail = ({
!systemEmailHost || !systemEmailHost ||
!systemEmailPort || !systemEmailPort ||
!systemEmailAddress || !systemEmailAddress ||
!(password || systemEmailPassword) !systemEmailPassword
) { ) {
createToast({ createToast({
body: t("settingsPage.emailSettings.toastEmailRequiredFieldsError"), body: t("pages.settings.emailSettings.toastEmailRequiredFieldsError"),
variant: "error", variant: "error",
}); });
return; return;
@@ -85,7 +78,7 @@ const SettingsEmail = ({
systemEmailHost, systemEmailHost,
systemEmailPort, systemEmailPort,
systemEmailAddress, systemEmailAddress,
systemEmailPassword: password || systemEmailPassword, systemEmailPassword,
systemEmailSecure, systemEmailSecure,
systemEmailPool, systemEmailPool,
systemEmailIgnoreTLS, systemEmailIgnoreTLS,
@@ -108,229 +101,267 @@ const SettingsEmail = ({
component="h1" component="h1"
variant="h2" variant="h2"
> >
{t("settingsPage.emailSettings.title")} {t("pages.settings.emailSettings.title")}
</Typography> </Typography>
<Typography sx={HEADER_SX}> <Typography sx={HEADER_SX}>
{t("settingsPage.emailSettings.description")} {t("pages.settings.emailSettings.description")}
</Typography> </Typography>
</Box> </Box>
<Box>
<Stack gap={theme.spacing(10)}>
<Box>
<TextInput
label={t("settingsPage.emailSettings.labelHost")}
name="systemEmailHost"
placeholder="smtp.gmail.com"
value={systemEmailHost}
onChange={handleChange}
/>
</Box>
<Box>
<TextInput
label={t("settingsPage.emailSettings.labelPort")}
name="systemEmailPort"
placeholder="425"
type="number"
value={systemEmailPort}
onChange={handleChange}
/>
</Box>
<Box>
<TextInput
label={t("settingsPage.emailSettings.labelUser")}
name="systemEmailUser"
placeholder={t("settingsPage.emailSettings.placeholderUser")}
value={systemEmailUser}
onChange={handleChange}
/>
</Box>
<Box>
<TextInput
label={t("settingsPage.emailSettings.labelAddress")}
name="systemEmailAddress"
placeholder="uptime@bluewavelabs.ca"
value={systemEmailAddress}
onChange={handleChange}
/>
</Box>
{(isEmailPasswordSet === false || emailPasswordHasBeenReset === true) && (
<Box>
<TextInput
label={t("settingsPage.emailSettings.labelPassword")}
name="systemEmailPassword"
type="password"
placeholder="123 456 789 101112"
value={password}
onChange={handlePasswordChange}
endAdornment={<PasswordEndAdornment />}
/>
</Box>
)}
{isEmailPasswordSet === true && emailPasswordHasBeenReset === false && ( <Stack gap={theme.spacing(10)}>
<Box> <Box>
<Typography>{t("settingsPage.emailSettings.labelPasswordSet")}</Typography> <Controller
<Button name="systemEmailHost"
onClick={() => { control={control}
setPassword(""); defaultValue={defaults.systemEmailHost}
setSettingsData({ render={({ field, fieldState }) => (
...settingsData, <TextInput
settings: { ...settingsData.settings, systemEmailPassword: "" }, {...field}
}); label={t("pages.settings.emailSettings.labelHost")}
setEmailPasswordHasBeenReset(true); placeholder="smtp.gmail.com"
}} error={!!fieldState.error}
variant="contained" helperText={fieldState.error?.message}
color="error" />
sx={{ mt: theme.spacing(4) }} )}
> />
{t("reset")} </Box>
</Button> <Box>
</Box> <Controller
)} name="systemEmailPort"
control={control}
defaultValue={defaults.systemEmailPort}
render={({ field, fieldState }) => (
<TextInput
{...field}
label={t("pages.settings.emailSettings.labelPort")}
placeholder="425"
type="number"
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/>
</Box>
<Box>
<Controller
name="systemEmailUser"
control={control}
defaultValue={defaults.systemEmailUser}
render={({ field, fieldState }) => (
<TextInput
{...field}
label={t("pages.settings.emailSettings.labelUser")}
placeholder={t("pages.settings.emailSettings.placeholderUser")}
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/>
</Box>
<Box>
<Controller
name="systemEmailAddress"
control={control}
defaultValue={defaults.systemEmailAddress}
render={({ field, fieldState }) => (
<TextInput
{...field}
label={t("pages.settings.emailSettings.labelAddress")}
placeholder="uptime@bluewavelabs.ca"
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/>
</Box>
{(isEmailPasswordSet === false || emailPasswordHasBeenReset === true) && (
<Box> <Box>
<TextInput <Controller
label={t("settingsPage.emailSettings.labelTLSServername")} name="systemEmailPassword"
name="systemEmailTLSServername" control={control}
placeholder="bluewavelabs.ca" defaultValue={defaults.systemEmailPassword}
value={systemEmailTLSServername} render={({ field, fieldState }) => (
onChange={handleChange} <TextInput
{...field}
label={t("pages.settings.emailSettings.labelPassword")}
type="password"
placeholder="123 456 789 101112"
endAdornment={<PasswordEndAdornment />}
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/> />
</Box> </Box>
)}
{isEmailPasswordSet === true && emailPasswordHasBeenReset === false && (
<Box> <Box>
<TextInput <Typography>{t("pages.settings.emailSettings.labelPasswordSet")}</Typography>
label={t("settingsPage.emailSettings.labelConnectionHost")} <Button
name="systemEmailConnectionHost" onClick={() => {
placeholder="bluewavelabs.ca" setEmailPasswordHasBeenReset(true);
value={systemEmailConnectionHost} }}
onChange={handleChange} variant="contained"
/> color="error"
sx={{ mt: theme.spacing(4) }}
>
{t("reset")}
</Button>
</Box> </Box>
)}
<Box>
<Controller
name="systemEmailTLSServername"
control={control}
defaultValue={defaults.systemEmailTLSServername}
render={({ field, fieldState }) => (
<TextInput
{...field}
label={t("pages.settings.emailSettings.labelTLSServername")}
placeholder="bluewavelabs.ca"
/>
)}
/>
</Box>
<Box>
<Controller
name="systemEmailConnectionHost"
control={control}
defaultValue={defaults.systemEmailConnectionHost}
render={({ field, fieldState }) => (
<TextInput
{...field}
label={t("pages.settings.emailSettings.labelConnectionHost")}
placeholder="bluewavelabs.ca"
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/>
</Box>
<Box
sx={{
display: "flex",
flexDirection: "column",
gap: theme.spacing(4),
}}
>
{[
[
"pages.settings.emailSettings.labelSecure",
"systemEmailSecure",
systemEmailSecure,
],
[
"pages.settings.emailSettings.labelPool",
"systemEmailPool",
systemEmailPool,
],
[
"pages.settings.emailSettings.labelIgnoreTLS",
"systemEmailIgnoreTLS",
systemEmailIgnoreTLS,
],
[
"pages.settings.emailSettings.labelRequireTLS",
"systemEmailRequireTLS",
systemEmailRequireTLS,
],
[
"pages.settings.emailSettings.labelRejectUnauthorized",
"systemEmailRejectUnauthorized",
systemEmailRejectUnauthorized,
],
].map(([labelKey, name, value]) => (
<Controller
key={name}
name={name}
control={control}
defaultValue={defaults[name]}
render={({ field }) => (
<Box
key={name}
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
<Typography>{t(labelKey)}</Typography>
<Switch
{...field}
checked={field.value}
/>
</Box>
)}
/>
))}
<TextLink
text={t("pages.settings.emailSettings.descriptionTransport")}
linkText={t("pages.settings.emailSettings.linkTransport")}
href="https://nodemailer.com/smtp"
target="_blank"
/>
<Box <Box
component={"pre"}
sx={{ sx={{
display: "flex", fontFamily: "monospace",
flexDirection: "column", p: 2,
gap: theme.spacing(4), borderRadius: 1,
overflow: "auto",
}} }}
> >
{[ <code>
[ {JSON.stringify(
"settingsPage.emailSettings.labelSecure", {
"systemEmailSecure", host: systemEmailHost,
systemEmailSecure, port: systemEmailPort,
], secure: systemEmailSecure,
[ auth: {
"settingsPage.emailSettings.labelPool", user: systemEmailUser || systemEmailAddress,
"systemEmailPool", pass: "<your_password>",
systemEmailPool,
],
[
"settingsPage.emailSettings.labelIgnoreTLS",
"systemEmailIgnoreTLS",
systemEmailIgnoreTLS,
],
[
"settingsPage.emailSettings.labelRequireTLS",
"systemEmailRequireTLS",
systemEmailRequireTLS,
],
[
"settingsPage.emailSettings.labelRejectUnauthorized",
"systemEmailRejectUnauthorized",
systemEmailRejectUnauthorized,
],
].map(([labelKey, name, value]) => (
<Box
key={name}
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
<Typography>{t(labelKey)}</Typography>
<Switch
name={name}
checked={value}
onChange={handleChange}
/>
</Box>
))}
<TextLink
text={t("settingsPage.emailSettings.descriptionTransport")}
linkText={t("settingsPage.emailSettings.linkTransport")}
href="https://nodemailer.com/smtp"
target="_blank"
/>
<Box
component={"pre"}
sx={{
fontFamily: "monospace",
p: 2,
borderRadius: 1,
overflow: "auto",
}}
>
<code>
{JSON.stringify(
{
host: systemEmailHost,
port: systemEmailPort,
secure: systemEmailSecure,
auth: {
user: systemEmailUser || systemEmailAddress,
pass: "<your_password>",
},
name: systemEmailConnectionHost || "localhost",
pool: systemEmailPool,
tls: {
rejectUnauthorized: systemEmailRejectUnauthorized,
ignoreTLS: systemEmailIgnoreTLS,
requireTLS: systemEmailRequireTLS,
servername: systemEmailTLSServername,
},
}, },
null, name: systemEmailConnectionHost || "localhost",
2 pool: systemEmailPool,
)} tls: {
</code> rejectUnauthorized: systemEmailRejectUnauthorized,
</Box> ignoreTLS: systemEmailIgnoreTLS,
</Box> requireTLS: systemEmailRequireTLS,
servername: systemEmailTLSServername,
<pre> },
{JSON.stringify({ },
systemEmailHost, null,
systemEmailAddress, 2
systemEmailPassword,
})}
</pre>
<Box>
{systemEmailHost &&
systemEmailPort &&
systemEmailAddress &&
systemEmailPassword && (
<Button
variant="contained"
color="accent"
loading={isSending}
onClick={handleSendTestEmail}
>
{t("settingsPage.emailSettings.buttonSendTestEmail")}
</Button>
)} )}
</code>
</Box> </Box>
</Stack> </Box>
</Box>
<Box>
{systemEmailHost &&
systemEmailPort &&
systemEmailAddress &&
systemEmailPassword && (
<Button
variant="contained"
color="accent"
loading={isSending}
onClick={handleSendTestEmail}
>
{t("pages.settings.emailSettings.buttonSendTestEmail")}
</Button>
)}
</Box>
</Stack>
</ConfigBox> </ConfigBox>
); );
}; };
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;
@@ -51,11 +30,11 @@ const SettingsGlobalThresholds = ({
component="h1" component="h1"
variant="h2" variant="h2"
> >
{t("settingsPage.globalThresholds.title", "Global Thresholds")} {t("pages.settings.globalThresholds.title", "Global Thresholds")}
</Typography> </Typography>
<Typography sx={HEADING_SX}> <Typography sx={HEADING_SX}>
{t( {t(
"settingsPage.globalThresholds.description", "pages.settings.globalThresholds.description",
"Configure global CPU, Memory, Disk, and Temperature thresholds." "Configure global CPU, Memory, Disk, and Temperature thresholds."
)} )}
</Typography> </Typography>
@@ -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;
+24 -28
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;
} }
@@ -46,35 +39,40 @@ const SettingsPagespeed = ({
component="h1" component="h1"
variant="h2" variant="h2"
> >
{t("settingsPage.pageSpeedSettings.title")} {t("pages.settings.pageSpeedSettings.title")}
</Typography> </Typography>
<Typography sx={HEADING_SX}> <Typography sx={HEADING_SX}>
{t("settingsPage.pageSpeedSettings.description")} {t("pages.settings.pageSpeedSettings.description")}
</Typography> </Typography>
</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("pages.settings.pageSpeedSettings.labelApiKey")}
type={"password"}
optionalLabel="(Optional)"
endAdornment={<PasswordEndAdornment />}
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
/> />
)} )}
{isApiKeySet === true && apiKeyHasBeenReset === false && ( {isApiKeySet === true && apiKeyHasBeenReset === false && (
<Box> <Box>
<Typography>{t("settingsPage.pageSpeedSettings.labelApiKeySet")}</Typography> <Typography>
{t("pages.settings.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 +91,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,
+13 -17
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>
@@ -29,16 +31,16 @@ const SettingsStats = ({ isAdmin, HEADING_SX, handleChange, settingsData, errors
variant="h2" variant="h2"
sx={HEADING_SX} sx={HEADING_SX}
> >
{t("settingsPage.statsSettings.title")} {t("pages.settings.statsSettings.title")}
</Typography> </Typography>
<Typography sx={{ mt: theme.spacing(2) }}> <Typography sx={{ mt: theme.spacing(2) }}>
{t("settingsPage.statsSettings.description")} {t("pages.settings.statsSettings.description")}
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
<Box> <Box>
<Typography> <Typography>
{t("settingsPage.statsSettings.clearAllStatsDescription")} {t("pages.settings.statsSettings.clearAllStatsDescription")}
</Typography> </Typography>
<Button <Button
variant="contained" variant="contained"
@@ -46,26 +48,22 @@ const SettingsStats = ({ isAdmin, HEADING_SX, handleChange, settingsData, errors
onClick={() => setIsOpen(true)} onClick={() => setIsOpen(true)}
sx={{ mt: theme.spacing(4) }} sx={{ mt: theme.spacing(4) }}
> >
{t("settingsPage.statsSettings.clearAllStatsButton")} {t("pages.settings.statsSettings.clearAllStatsButton")}
</Button> </Button>
</Box> </Box>
</Stack> </Stack>
<Dialog <Dialog
open={isOpen} open={isOpen}
theme={theme} theme={theme}
title={t("settingsPage.statsSettings.clearAllStatsDialogTitle")} title={t("pages.settings.statsSettings.clearAllStatsDialogTitle")}
description={t("settingsPage.statsSettings.clearAllStatsDialogDescription")} description={t("pages.settings.statsSettings.clearAllStatsDialogDescription")}
onCancel={() => setIsOpen(false)} onCancel={() => setIsOpen(false)}
confirmationButtonLabel={t( confirmationButtonLabel={t(
"settingsPage.statsSettings.clearAllStatsDialogConfirm" "pages.settings.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,
}; };
+12 -17
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>
@@ -40,11 +37,11 @@ const SettingsTimeZone = ({ HEADING_SX, handleChange, timezone }) => {
component="h1" component="h1"
variant="h2" variant="h2"
> >
{t("settingsPage.timezoneSettings.title")} {t("pages.settings.timezoneSettings.title")}
</Typography> </Typography>
<Typography sx={HEADING_SX}> <Typography sx={HEADING_SX}>
<Typography component="span"> <Typography component="span">
{t("settingsPage.timezoneSettings.description")} {t("pages.settings.timezoneSettings.description")}
</Typography> </Typography>
</Typography> </Typography>
</Box> </Box>
@@ -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;
+19 -15
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>
@@ -24,18 +32,18 @@ const SettingsUI = ({ HEADING_SX, handleChange, mode, language, chartType }) =>
component="h1" component="h1"
variant="h2" variant="h2"
> >
{t("settingsPage.uiSettings.title")} {t("pages.settings.uiSettings.title")}
</Typography> </Typography>
<Typography sx={HEADING_SX}> <Typography sx={HEADING_SX}>
{t("settingsPage.uiSettings.description")} {t("pages.settings.uiSettings.description")}
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
<Select <Select
name="mode" name="mode"
label={t("settingsPage.uiSettings.labelTheme")} label={t("pages.settings.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" },
@@ -43,19 +51,19 @@ const SettingsUI = ({ HEADING_SX, handleChange, mode, language, chartType }) =>
></Select> ></Select>
<Select <Select
name="language" name="language"
label={t("settingsPage.uiSettings.labelLanguage")} label={t("pages.settings.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("pages.settings.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("pages.settings.uiSettings.chartTypeHistogram") },
{ _id: "heatmap", name: t("settingsPage.uiSettings.chartTypeHeatmap") }, { _id: "heatmap", name: t("pages.settings.uiSettings.chartTypeHeatmap") },
]} ]}
></Select> ></Select>
<ThemeProvider theme={v2Theme}> <ThemeProvider theme={v2Theme}>
@@ -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;
+20 -14
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 (
@@ -19,23 +20,30 @@ const SettingsURL = ({ HEADING_SX, handleChange, showURL = false }) => {
component="h1" component="h1"
variant="h2" variant="h2"
> >
{t("settingsPage.urlSettings.title")} {t("pages.settings.urlSettings.title")}
</Typography> </Typography>
<Typography sx={HEADING_SX}> <Typography sx={HEADING_SX}>
{t("settingsPage.urlSettings.description")} {t("pages.settings.urlSettings.description")}
</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("pages.settings.urlSettings.label")}
items={[
{ _id: true, name: t("pages.settings.urlSettings.selectEnabled") },
{ _id: false, name: t("pages.settings.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;
+59 -182
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("pages.settings.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,9 +199,9 @@ 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("pages.settings.saveButtonLabel")}
</Button> </Button>
</Stack> </Stack>
</Stack> </Stack>
+58
View File
@@ -0,0 +1,58 @@
import { z } from "zod";
export const settingsSchema = z.object({
systemEmailIgnoreTLS: z.boolean(),
systemEmailRequireTLS: z.boolean(),
systemEmailRejectUnauthorized: z.boolean(),
systemEmailConnectionHost: z.string().optional(),
systemEmailSecure: z.boolean().optional(),
systemEmailPool: z.boolean().optional(),
showURL: z.boolean().optional(),
checkTTL: z.coerce.number().int().min(1, "Please enter a value"),
pagespeedApiKey: z.string().optional(),
systemEmailHost: z.string().optional(),
systemEmailPort: z.coerce
.number()
.int()
.min(1, "Port must be at least 1")
.optional()
.or(z.literal("")),
systemEmailAddress: z
.email("Please enter a valid email address")
.transform((val) => val.toLowerCase().trim())
.optional()
.or(z.literal("")),
systemEmailUser: z.string().optional(),
systemEmailPassword: z.string().optional(),
systemEmailTLSServername: z.string().optional(),
globalThresholds: z
.object({
cpu: z.coerce
.number()
.min(1, "Min 1%")
.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(),
});
export type SettingsFormData = z.infer<typeof settingsSchema>;
+87
View File
@@ -907,6 +907,93 @@
"title": "A PageSpeed monitor is used to:" "title": "A PageSpeed monitor is used to:"
} }
}, },
"settings": {
"aboutSettings": {
"labelDevelopedBy": "Developed by Bluewave Labs",
"labelVersion": "Version",
"title": "About"
},
"demoMonitorsSettings": {
"buttonAddMonitors": "Add demo monitors",
"description": "Add sample monitors for demonstration purposes.",
"title": "Demo monitors"
},
"emailSettings": {
"buttonSendTestEmail": "Send test e-mail",
"description": "Configure the email settings for your system. This is used to send notifications and alerts.",
"descriptionTransport": "This builds an SMTP transport for NodeMailer",
"labelAddress": "Email address - Used for authentication",
"labelConnectionHost": "Email connection host - Hostname to use in the HELO/EHLO greeting",
"labelHost": "Email host - Hostname or IP address to connect to",
"labelIgnoreTLS": "Disable STARTTLS: Don't use TLS even if the server supports it",
"labelPassword": "Email password - Password for authentication",
"labelPasswordSet": "Password is set. Click Reset to change it.",
"labelPool": "Enable connection pooling: Reuse existing connections to improve performance",
"labelPort": "Email port - Port to connect to",
"labelRejectUnauthorized": "Reject invalid certificates: Reject connections with self-signed or untrusted certificates",
"labelRequireTLS": "Force STARTTLS: Require TLS upgrade, fail if not supported",
"labelSecure": "Use SSL (recommended): Encrypt the connection using SSL/TLS",
"labelTLSServername": "TLS Servername - Optional Hostname for TLS Validation when host is an IP",
"labelUser": "Email user - Username for authentication, overrides email address if specified",
"linkTransport": "See specifications here",
"placeholderUser": "Leave empty if not required",
"title": "Email",
"toastEmailRequiredFieldsError": "Email address, host, port and password are required"
},
"globalThresholds": {
"title": "Global Thresholds",
"description": "Configure global CPU, Memory, Disk, and Temperature thresholds. If a value is provided, it will automatically be enabled for monitoring."
},
"pageSpeedSettings": {
"description": "Enter your Google PageSpeed API key to enable Google PageSpeed monitoring. Click Reset to update the key.",
"labelApiKeySet": "API key is set. Click Reset to change it.",
"labelApiKey": "PageSpeed API key",
"title": "Google PageSpeed API key"
},
"saveButtonLabel": "Save",
"statsSettings": {
"clearAllStatsButton": "Clear all stats",
"clearAllStatsDescription": "Clear all stats. This is irreversible.",
"clearAllStatsDialogConfirm": "Yes, clear all stats",
"clearAllStatsDialogDescription": "Once removed, the monitoring history and stats cannot be retrieved.",
"clearAllStatsDialogTitle": "Do you want to clear all stats?",
"description": "Define how long you want to retain historical data. You can also clear all existing data.",
"labelTTL": "The days you want to keep monitoring history.",
"labelTTLOptional": "0 for infinite",
"title": "Monitor history"
},
"systemResetSettings": {
"buttonRemoveAllMonitors": "Remove all monitors",
"description": "Remove all monitors from your system.",
"dialogConfirm": "Yes, remove all monitors",
"dialogDescription": "Once removed, the monitors cannot be retrieved.",
"dialogTitle": "Do you want to remove all monitors?",
"title": "System reset"
},
"timezoneSettings": {
"description": "Select the timezone used to display dates and times throughout the application.",
"label": "Display timezone",
"title": "Display timezone"
},
"title": "Settings",
"uiSettings": {
"description": "Switch between light and dark mode, or change user interface language.",
"labelLanguage": "Language",
"labelTheme": "Theme mode",
"labelChartType": "Chart type",
"chartTypeHistogram": "Histogram",
"chartTypeHeatmap": "Heatmap",
"title": "Appearance"
},
"urlSettings": {
"description": "Display the IP address or URL of monitor on the public Status page. If it's disabled, only the monitor name will be shown to protect sensitive information.",
"label": "Display IP/URL on status page",
"selectDisabled": "Disabled",
"selectEnabled": "Enabled",
"title": "Monitor IP/URL on Status Page"
}
},
"statusPages": { "statusPages": {
"deleteSuccess": "Status page deleted successfully", "deleteSuccess": "Status page deleted successfully",
"fallback": { "fallback": {