Revert "FE - Advanced Settings Page Validation and Error Handling"

This commit is contained in:
Alexander Holliday authored and GitHub committed 2024-10-22 18:21:10 +08:00
1 parent c9864d9075
commit 238db5bc8f
4 files changed
+279 -339

No files matched your search

+216 -239
View File
@@ -12,47 +12,45 @@ import { useNavigate } from "react-router";
import { getAppSettings, updateAppSettings } from "../../Features/Settings/settingsSlice"; import { getAppSettings, updateAppSettings } from "../../Features/Settings/settingsSlice";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import Select from "../../Components/Inputs/Select"; import Select from "../../Components/Inputs/Select";
import { advancedSettingsValidation } from "../../Validation/validation";
import { buildErrors, hasValidationErrors } from "../../Validation/error";
const AdvancedSettings = ({ isAdmin }) => { const AdvancedSettings = ({ isAdmin }) => {
const navigate = useNavigate(); const navigate = useNavigate();
useEffect(() => {
if (!isAdmin) {
navigate("/");
}
}, [navigate, isAdmin]);
const theme = useTheme(); useEffect(() => {
const { authToken } = useSelector((state) => state.auth); if (!isAdmin) {
const dispatch = useDispatch(); navigate("/");
const settings = useSelector((state) => state.settings); }
const [localSettings, setLocalSettings] = useState({ }, [navigate, isAdmin]);
apiBaseUrl: "",
logLevel: "debug",
systemEmailHost: "",
systemEmailPort: "",
systemEmailAddress: "",
systemEmailPassword: "",
jwtTTL: "",
dbType: "",
redisHost: "",
redisPort: "",
pagespeedApiKey: "",
});
const [errors, setErrors] = useState({});
useEffect(() => { const theme = useTheme();
const getSettings = async () => { const { authToken } = useSelector((state) => state.auth);
const action = await dispatch(getAppSettings({ authToken })); const dispatch = useDispatch();
if (action.payload?.success) { const settings = useSelector((state) => state.settings);
setLocalSettings(action.payload.data); const [localSettings, setLocalSettings] = useState({
} else { apiBaseUrl: "",
createToast({ body: "Failed to get settings" }); logLevel: "debug",
} systemEmailHost: "",
}; systemEmailPort: "",
getSettings(); systemEmailAddress: "",
}, [authToken, dispatch]); systemEmailPassword: "",
jwtTTL: "",
dbType: "",
redisHost: "",
redisPort: "",
pagespeedApiKey: "",
});
useEffect(() => {
const getSettings = async () => {
const action = await dispatch(getAppSettings({ authToken }));
if (action.payload.success) {
setLocalSettings(action.payload.data);
} else {
createToast({ body: "Failed to get settings" });
}
};
getSettings();
}, [authToken, dispatch]);
const logItems = [ const logItems = [
{ _id: 1, name: "none" }, { _id: 1, name: "none" },
@@ -74,210 +72,189 @@ const AdvancedSettings = ({ isAdmin }) => {
setLocalSettings({ ...localSettings, logLevel: newLogLevel }); setLocalSettings({ ...localSettings, logLevel: newLogLevel });
}; };
const handleChange = (event) => { const handleChange = (event) => {
const { value, id } = event.target; const { value, id } = event.target;
setLocalSettings({ ...localSettings, [id]: value }); setLocalSettings({ ...localSettings, [id]: value });
const { error } = advancedSettingsValidation.validate( };
{ [id]: value },
{
abortEarly: false,
}
);
setErrors((prev) => {
return buildErrors(prev, id, error);
});
};
const handleSave = async () => { const handleSave = async () => {
if (hasValidationErrors(localSettings, advancedSettingsValidation, setErrors)) const action = await dispatch(
return; updateAppSettings({ settings: localSettings, authToken })
const action = await dispatch( );
updateAppSettings({ settings: localSettings, authToken }) let body = "";
); if (action.payload.success) {
let body = ""; console.log(action.payload.data);
if (action.payload.success) { setLocalSettings(action.payload.data);
console.log(action.payload.data); body = "Settings saved successfully";
setLocalSettings(action.payload.data); } else {
body = "Settings saved successfully"; body = "Failed to save settings";
} else { }
body = "Failed to save settings"; createToast({ body });
} };
createToast({ body });
};
return ( return (
<Box <Box
className="settings" className="settings"
style={{ style={{
paddingBottom: 0, paddingBottom: 0,
}} }}
> >
<Stack <Stack
component="form" component="form"
gap={theme.spacing(12)} gap={theme.spacing(12)}
noValidate noValidate
spellCheck="false" spellCheck="false"
> >
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography component="h1">Client settings</Typography> <Typography component="h1">Client settings</Typography>
<Typography sx={{ mt: theme.spacing(2) }}> <Typography sx={{ mt: theme.spacing(2) }}>
Modify client settings here. Modify client settings here.
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
<Field <Field
id="apiBaseUrl" id="apiBaseUrl"
label="API URL Host" label="API URL Host"
value={localSettings.apiBaseUrl} value={localSettings.apiBaseUrl}
onChange={handleChange} onChange={handleChange}
error={errors.apiBaseUrl} />
/> <Select
<Select id="logLevel"
id="logLevel" label="Log level"
label="Log level" name="logLevel"
name="logLevel" items={logItems}
items={logItems} value={logItemLookup[localSettings.logLevel]}
value={logItemLookup[localSettings.logLevel]} onChange={handleLogLevel}
onChange={handleLogLevel} />
error={errors.logLevel} </Stack>
/> </ConfigBox>
</Stack> <ConfigBox>
</ConfigBox> <Box>
<ConfigBox> <Typography component="h1">Email settings</Typography>
<Box> <Typography sx={{ mt: theme.spacing(2) }}>
<Typography component="h1">Email settings</Typography> Set your host email settings here. These settings are used for sending
<Typography sx={{ mt: theme.spacing(2) }}> system emails.
Set your host email settings here. These settings are used for </Typography>
sending system emails. </Box>
</Typography> <Stack gap={theme.spacing(20)}>
</Box> <Field
<Stack gap={theme.spacing(20)}> type="text"
<Field id="systemEmailHost"
type="text" label="Email host"
id="systemEmailHost" name="systemEmailHost"
label="Email host" value={localSettings.systemEmailHost}
name="systemEmailHost" onChange={handleChange}
value={localSettings.systemEmailHost} />
onChange={handleChange} <Field
error={errors.systemEmailHost} type="number"
/> id="systemEmailPort"
<Field label="System email address"
type="number" name="systemEmailPort"
id="systemEmailPort" value={localSettings.systemEmailPort.toString()}
label="System email address" onChange={handleChange}
name="systemEmailPort" />
value={localSettings.systemEmailPort.toString()} <Field
onChange={handleChange} type="email"
error={errors.systemEmailPort} id="systemEmailAddress"
/> label="System email address"
<Field name="systemEmailAddress"
type="email" value={localSettings.systemEmailAddress}
id="systemEmailAddress" onChange={handleChange}
label="System email address" />
name="systemEmailAddress" <Field
value={localSettings.systemEmailAddress} type="text"
onChange={handleChange} id="systemEmailPassword"
error={errors.systemEmailAddress} label="System email password"
/> name="systemEmailPassword"
<Field value={localSettings.systemEmailPassword}
type="text" onChange={handleChange}
id="systemEmailPassword" />
label="System email password" </Stack>
name="systemEmailPassword" </ConfigBox>
value={localSettings.systemEmailPassword} <ConfigBox>
onChange={handleChange} <Box>
error={errors.systemEmailPassword} <Typography component="h1">Server settings</Typography>
/> <Typography sx={{ mt: theme.spacing(2) }}>
</Stack> Modify server settings here.
</ConfigBox> </Typography>
<ConfigBox> </Box>
<Box> <Stack gap={theme.spacing(20)}>
<Typography component="h1">Server settings</Typography> <Field
<Typography sx={{ mt: theme.spacing(2) }}> type="text"
Modify server settings here. id="jwtTTL"
</Typography> label="JWT time to live"
</Box> name="jwtTTL"
<Stack gap={theme.spacing(20)}> value={localSettings.jwtTTL}
<Field onChange={handleChange}
type="text" />
id="jwtTTL" <Field
label="JWT time to live" type="text"
name="jwtTTL" id="dbType"
value={localSettings.jwtTTL} label="Database type"
onChange={handleChange} name="dbType"
error={errors.jwtTTL} value={localSettings.dbType}
/> onChange={handleChange}
<Field />
type="text" <Field
id="dbType" type="text"
label="Database type" id="redisHost"
name="dbType" label="Redis host"
value={localSettings.dbType} name="redisHost"
onChange={handleChange} value={localSettings.redisHost}
error={errors.dbType} onChange={handleChange}
/> />
<Field <Field
type="text" type="number"
id="redisHost" id="redisPort"
label="Redis host" label="Redis port"
name="redisHost" name="redisPort"
value={localSettings.redisHost} value={localSettings.redisPort.toString()}
onChange={handleChange} onChange={handleChange}
error={errors.redisHost} />
/> <Field
<Field type="text"
type="number" id="pagespeedApiKey"
id="redisPort" label="PageSpeed API key"
label="Redis port" name="pagespeedApiKey"
name="redisPort" value={localSettings.pagespeedApiKey}
value={localSettings.redisPort.toString()} onChange={handleChange}
onChange={handleChange} />
error={errors.redisPort} </Stack>
/> </ConfigBox>
<Field <ConfigBox>
type="text" <Box>
id="pagespeedApiKey" <Typography component="h1">About</Typography>
label="PageSpeed API key" </Box>
name="pagespeedApiKey" <Box>
value={localSettings.pagespeedApiKey} <Typography component="h2">BlueWave Uptime v1.0.0</Typography>
onChange={handleChange} <Typography sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }}>
error={errors.pagespeedApiKey} Developed by Bluewave Labs.
/> </Typography>
</Stack> <Link
</ConfigBox> level="secondary"
<ConfigBox> url="https://github.com/bluewave-labs"
<Box> label="https://github.com/bluewave-labs"
<Typography component="h1">About</Typography> />
</Box> </Box>
<Box> </ConfigBox>
<Typography component="h2">BlueWave Uptime v1.0.0</Typography> <Stack
<Typography direction="row"
sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }} justifyContent="flex-end"
> >
Developed by Bluewave Labs. <LoadingButton
</Typography> loading={settings.isLoading || settings.authIsLoading}
<Link variant="contained"
level="secondary" color="primary"
url="https://github.com/bluewave-labs" sx={{ px: theme.spacing(12), mt: theme.spacing(20) }}
label="https://github.com/bluewave-labs" onClick={handleSave}
/> >
</Box> Save
</ConfigBox> </LoadingButton>
<Stack direction="row" justifyContent="flex-end"> </Stack>
<LoadingButton </Stack>
loading={settings.isLoading || settings.authIsLoading} </Box>
variant="contained" );
color="primary"
sx={{ px: theme.spacing(12), mt: theme.spacing(20) }}
onClick={handleSave}
>
Save
</LoadingButton>
</Stack>
</Stack>
</Box>
);
}; };
AdvancedSettings.propTypes = { AdvancedSettings.propTypes = {
@@ -28,7 +28,6 @@ import {
MS_PER_WEEK, MS_PER_WEEK,
} from "../../../Utils/timeUtils"; } from "../../../Utils/timeUtils";
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
import { buildErrors, hasValidationErrors } from "../../../Validation/error";
const getDurationAndUnit = (durationInMs) => { const getDurationAndUnit = (durationInMs) => {
if (durationInMs % MS_PER_DAY === 0) { if (durationInMs % MS_PER_DAY === 0) {
@@ -146,36 +145,46 @@ const CreateMaintenance = () => {
return; return;
} }
const res = await networkService.getMaintenanceWindowById({ const res = await networkService.getMaintenanceWindowById({
authToken: authToken, authToken: authToken,
maintenanceWindowId: maintenanceWindowId, maintenanceWindowId: maintenanceWindowId,
}); });
const maintenanceWindow = res.data.data; const maintenanceWindow = res.data.data;
const { name, start, end, repeat, monitorId } = maintenanceWindow; const { name, start, end, repeat, monitorId } = maintenanceWindow;
const startTime = dayjs(start); const startTime = dayjs(start);
const endTime = dayjs(end); const endTime = dayjs(end);
const durationInMs = endTime.diff(startTime, "milliseconds").toString(); const durationInMs = endTime.diff(startTime, "milliseconds").toString();
const { duration, durationUnit } = getDurationAndUnit(durationInMs); const { duration, durationUnit } = getDurationAndUnit(durationInMs);
const monitor = monitors.find((monitor) => monitor._id === monitorId); const monitor = monitors.find((monitor) => monitor._id === monitorId);
setForm({ setForm({
...form, ...form,
name, name,
repeat: REVERSE_REPEAT_LOOKUP[repeat], repeat: REVERSE_REPEAT_LOOKUP[repeat],
startDate: startTime, startDate: startTime,
startTime, startTime,
duration, duration,
durationUnit, durationUnit,
monitors: monitor ? [monitor] : [], monitors: monitor ? [monitor] : [],
}); });
} catch (error) { } catch (error) {
createToast({ body: "Failed to fetch data" }); createToast({ body: "Failed to fetch data" });
logger.error("Failed to fetch monitors", error); logger.error("Failed to fetch monitors", error);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}; };
fetchMonitors(); fetchMonitors();
}, [authToken, user]); }, [authToken, user]);
const buildErrors = (prev, id, error) => {
const updatedErrors = { ...prev };
if (error) {
updatedErrors[id] = error.details[0].message;
} else {
delete updatedErrors[id];
}
return updatedErrors;
};
const handleSearch = (value) => { const handleSearch = (value) => {
setSearch(value); setSearch(value);
@@ -214,17 +223,29 @@ const CreateMaintenance = () => {
}); });
}; };
const handleSubmit = async () => { const handleSubmit = async () => {
if(hasValidationErrors(form, maintenanceWindowValidation, setErrors)) const { error } = maintenanceWindowValidation.validate(form, {
return; abortEarly: false,
// Build timestamp for maintenance window from startDate and startTime });
const start = dayjs(form.startDate)
.set("hour", form.startTime.hour()) // If errors, return early
.set("minute", form.startTime.minute()); if (error) {
// Build end timestamp for maintenance window const newErrors = {};
const MS_MULTIPLIER = MS_LOOKUP[form.durationUnit]; error.details.forEach((err) => {
const durationInMs = form.duration * MS_MULTIPLIER; newErrors[err.path[0]] = err.message;
const end = start.add(durationInMs); });
setErrors(newErrors);
logger.error(error);
return;
}
// Build timestamp for maintenance window from startDate and startTime
const start = dayjs(form.startDate)
.set("hour", form.startTime.hour())
.set("minute", form.startTime.minute());
// Build end timestamp for maintenance window
const MS_MULTIPLIER = MS_LOOKUP[form.durationUnit];
const durationInMs = form.duration * MS_MULTIPLIER;
const end = start.add(durationInMs);
// Get repeat value in milliseconds // Get repeat value in milliseconds
const repeat = REPEAT_LOOKUP[form.repeat]; const repeat = REPEAT_LOOKUP[form.repeat];
-25
View File
@@ -1,25 +0,0 @@
const buildErrors = (prev, id, error) => {
const updatedErrors = { ...prev };
if (error) {
updatedErrors[id] = error.details[0].message?? "Validation error";
} else {
delete updatedErrors[id];
}
return updatedErrors;
};
const hasValidationErrors = (form, validation, setErrors) => {
const { error } = validation.validate(form, {
abortEarly: false,
});
if (error) {
const newErrors = {};
error.details.forEach((err) => {
newErrors[err.path[0]] = err.message?? "Validation error";
});
setErrors(newErrors);
return true;
}
return false;
};
export { buildErrors, hasValidationErrors };
-33
View File
@@ -128,43 +128,10 @@ const maintenanceWindowValidation = joi.object({
monitors: joi.array().min(1), monitors: joi.array().min(1),
}); });
const advancedSettingsValidation = joi.object({
apiBaseUrl: joi.string().uri({ allowRelative: true }).trim().messages({
"string.empty": "API base url is required.",
"string.uri": "The URL you provided is not valid.",
}),
logLevel: joi.string().valid("debug", "none", "error", "warn").allow(""),
systemEmailHost: joi.string().allow(''),
systemEmailPort: joi.string().allow(''),
systemEmailAddress: joi
.string().allow(''),
systemEmailPassword: joi.string().allow(''),
jwtTTL: joi
.string()
.trim()
.messages({
"string.empty": "JWT TTL is required."
}),
dbType: joi.string().trim().messages({
"string.empty": "DB type is required",
}),
redisHost: joi.string().trim().messages({
"string.empty": "Redis host is required",
}),
redisPort: joi.string().allow('').custom((value, helpers) => {
if(value && isNaN(parseInt(value))){
return helpers.message("Redit port must be a number")
}
return value
}),
pagespeedApiKey: joi.string().allow('')
});
export { export {
credentials, credentials,
imageValidation, imageValidation,
monitorValidation, monitorValidation,
settingsValidation, settingsValidation,
maintenanceWindowValidation, maintenanceWindowValidation,
advancedSettingsValidation,
}; };