Merge pull request #1310 from bluewave-labs/fix/fe/create-infra-refactor
fix: fe/create infra refactor
This commit is contained in:
4 files changed
+365
-264
No files matched your search
@@ -3,33 +3,50 @@ import { FormControlLabel, Checkbox as MuiCheckbox } from "@mui/material";
|
|||||||
import { useTheme } from "@emotion/react";
|
import { useTheme } from "@emotion/react";
|
||||||
import CheckboxOutline from "../../../assets/icons/checkbox-outline.svg?react";
|
import CheckboxOutline from "../../../assets/icons/checkbox-outline.svg?react";
|
||||||
import CheckboxFilled from "../../../assets/icons/checkbox-filled.svg?react";
|
import CheckboxFilled from "../../../assets/icons/checkbox-filled.svg?react";
|
||||||
|
|
||||||
import "./index.css";
|
import "./index.css";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {Object} props
|
* Checkbox Component
|
||||||
* @param {string} props.id - The id attribute for the checkbox input.
|
|
||||||
* @param {string} props.label - The label to display next to the checkbox.
|
|
||||||
* @param {('small' | 'medium' | 'large')} - The size of the checkbox.
|
|
||||||
* @param {boolean} props.isChecked - Whether the checkbox is checked or not.
|
|
||||||
* @param {string} [props.value] - The value of the checkbox input.
|
|
||||||
* @param {function} [props.onChange] - The function to call when the checkbox value changes.
|
|
||||||
* @param {boolean} [props.isDisabled] - Whether the checkbox is disabled or not.
|
|
||||||
*
|
*
|
||||||
* @returns {JSX.Element}
|
* A customized checkbox component using Material-UI that supports custom sizing,
|
||||||
|
* disabled states, and custom icons.
|
||||||
|
*
|
||||||
|
* @component
|
||||||
|
* @param {Object} props - Component properties
|
||||||
|
* @param {string} props.id - Unique identifier for the checkbox input
|
||||||
|
* @param {string} [props.name] - Optional name attribute for the checkbox
|
||||||
|
* @param {(string|React.ReactNode)} props.label - Label text or node for the checkbox
|
||||||
|
* @param {('small'|'medium'|'large')} [props.size='medium'] - Size of the checkbox icon
|
||||||
|
* @param {boolean} props.isChecked - Current checked state of the checkbox
|
||||||
|
* @param {string} [props.value] - Optional value associated with the checkbox
|
||||||
|
* @param {Function} [props.onChange] - Callback function triggered when checkbox state changes
|
||||||
|
* @param {boolean} [props.isDisabled] - Determines if the checkbox is disabled
|
||||||
|
*
|
||||||
|
* @returns {React.ReactElement} Rendered Checkbox component
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
|
* // Basic usage
|
||||||
* <Checkbox
|
* <Checkbox
|
||||||
* id="checkbox-id"
|
* id="terms-checkbox"
|
||||||
* label="Ping monitoring"
|
* label="I agree to terms"
|
||||||
* isChecked={checks.type === "ping"}
|
* isChecked={agreed}
|
||||||
* value="ping"
|
* onChange={handleAgree}
|
||||||
* onChange={handleChange}
|
* />
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* // With custom size and disabled state
|
||||||
|
* <Checkbox
|
||||||
|
* id="advanced-checkbox"
|
||||||
|
* label="Advanced Option"
|
||||||
|
* size="large"
|
||||||
|
* isChecked={isAdvanced}
|
||||||
|
* isDisabled={!canModify}
|
||||||
|
* onChange={handleAdvancedToggle}
|
||||||
* />
|
* />
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const Checkbox = ({
|
const Checkbox = ({
|
||||||
id,
|
id,
|
||||||
|
name,
|
||||||
label,
|
label,
|
||||||
size = "medium",
|
size = "medium",
|
||||||
isChecked,
|
isChecked,
|
||||||
@@ -46,6 +63,7 @@ const Checkbox = ({
|
|||||||
control={
|
control={
|
||||||
<MuiCheckbox
|
<MuiCheckbox
|
||||||
checked={isDisabled ? false : isChecked}
|
checked={isDisabled ? false : isChecked}
|
||||||
|
name={name}
|
||||||
value={value}
|
value={value}
|
||||||
onChange={onChange}
|
onChange={onChange}
|
||||||
icon={<CheckboxOutline />}
|
icon={<CheckboxOutline />}
|
||||||
@@ -89,6 +107,7 @@ const Checkbox = ({
|
|||||||
|
|
||||||
Checkbox.propTypes = {
|
Checkbox.propTypes = {
|
||||||
id: PropTypes.string.isRequired,
|
id: PropTypes.string.isRequired,
|
||||||
|
name: PropTypes.string,
|
||||||
label: PropTypes.oneOfType([PropTypes.string, PropTypes.node]).isRequired,
|
label: PropTypes.oneOfType([PropTypes.string, PropTypes.node]).isRequired,
|
||||||
size: PropTypes.oneOf(["small", "medium", "large"]),
|
size: PropTypes.oneOf(["small", "medium", "large"]),
|
||||||
isChecked: PropTypes.bool.isRequired,
|
isChecked: PropTypes.bool.isRequired,
|
||||||
|
|||||||
@@ -5,32 +5,58 @@ import { useTheme } from "@emotion/react";
|
|||||||
import PropTypes from "prop-types";
|
import PropTypes from "prop-types";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* `CustomThreshold` is a functional React component that displays a
|
* CustomThreshold Component
|
||||||
* group of CheckBox with a label and its correspondant threshold input field.
|
|
||||||
*
|
*
|
||||||
* @param {{ checkboxId: any; checkboxLabel: any; onCheckboxChange: any; fieldId: any; onFieldChange: any; onFieldBlur: any; alertUnit: any; infrastructureMonitor: any; errors: any; }} param0
|
* A reusable component that renders a checkbox with an associated numeric input field
|
||||||
* @param {string} param0.checkboxId - The text is the id of the checkbox.
|
* and an optional unit label. The input field can be enabled/disabled based on checkbox state.
|
||||||
* @param {string} param0.checkboxLabel - The text to be displayed as the label next to the check icon.
|
|
||||||
* @param {func} param0.onCheckboxChange - The function to invoke when checkbox is checked or unchecked.
|
|
||||||
* @param {string} param0.fieldId - The text is the id of the input field.
|
|
||||||
* @param {func} param0.onFieldChange - The function to invoke when input field is changed.
|
|
||||||
* @param {func} param0.onFieldBlur - The function to invoke when input field is losing focus.
|
|
||||||
* @param {string} param0.alertUnit the threshold unit such as usage percentage '%' etc
|
|
||||||
* @param {object} param0.infrastructureMonitor the form object of the create infrastrcuture monitor page
|
|
||||||
* @param {object} param0.errors the object that holds all the errors of the form page
|
|
||||||
* @returns A compound React component that renders the custom threshold alert section
|
|
||||||
*
|
*
|
||||||
|
* @component
|
||||||
|
* @param {Object} props - Component properties
|
||||||
|
* @param {string} [props.checkboxId] - Optional unique identifier for the checkbox
|
||||||
|
* @param {string} [props.checkboxName] - Optional name attribute for the checkbox
|
||||||
|
* @param {string} props.checkboxLabel - Label text for the checkbox
|
||||||
|
* @param {boolean} props.isChecked - Current checked state of the checkbox
|
||||||
|
* @param {Function} props.onCheckboxChange - Callback function when checkbox is toggled
|
||||||
|
* @param {string} props.fieldId - Unique identifier for the input field
|
||||||
|
* @param {string} [props.fieldName] - Optional name attribute for the input field
|
||||||
|
* @param {string} props.fieldValue - Current value of the input field
|
||||||
|
* @param {Function} props.onFieldChange - Callback function when input field value changes
|
||||||
|
* @param {Function} props.onFieldBlur - Callback function when input field loses focus
|
||||||
|
* @param {string} props.alertUnit - Unit label displayed next to the input field
|
||||||
|
* @param {Object} props.errors - Object containing validation errors for the field
|
||||||
|
* @param {Object} props.infrastructureMonitor - Infrastructure monitor configuration object
|
||||||
|
*
|
||||||
|
* @returns {React.ReactElement} Rendered CustomThreshold component
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* <CustomThreshold
|
||||||
|
* checkboxId="cpu-threshold"
|
||||||
|
* checkboxName="cpu_threshold"
|
||||||
|
* checkboxLabel="Enable CPU Threshold"
|
||||||
|
* isChecked={true}
|
||||||
|
* onCheckboxChange={handleCheckboxToggle}
|
||||||
|
* fieldId="cpu-threshold-value"
|
||||||
|
* fieldName="cpu_threshold_value"
|
||||||
|
* fieldValue="80"
|
||||||
|
* onFieldChange={handleFieldChange}
|
||||||
|
* onFieldBlur={handleFieldBlur}
|
||||||
|
* alertUnit="%"
|
||||||
|
* errors={{}}
|
||||||
|
* infrastructureMonitor={monitorConfig}
|
||||||
|
* />
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export const CustomThreshold = ({
|
export const CustomThreshold = ({
|
||||||
checkboxId,
|
checkboxId,
|
||||||
|
checkboxName,
|
||||||
checkboxLabel,
|
checkboxLabel,
|
||||||
onCheckboxChange,
|
onCheckboxChange,
|
||||||
|
isChecked,
|
||||||
fieldId,
|
fieldId,
|
||||||
|
fieldName,
|
||||||
|
fieldValue,
|
||||||
onFieldChange,
|
onFieldChange,
|
||||||
onFieldBlur,
|
onFieldBlur,
|
||||||
alertUnit,
|
alertUnit,
|
||||||
infrastructureMonitor,
|
|
||||||
errors,
|
errors,
|
||||||
}) => {
|
}) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
@@ -46,8 +72,9 @@ export const CustomThreshold = ({
|
|||||||
<Box>
|
<Box>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
id={checkboxId}
|
id={checkboxId}
|
||||||
|
name={checkboxName}
|
||||||
label={checkboxLabel}
|
label={checkboxLabel}
|
||||||
isChecked={infrastructureMonitor[checkboxId]}
|
isChecked={isChecked}
|
||||||
onChange={onCheckboxChange}
|
onChange={onCheckboxChange}
|
||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
@@ -61,11 +88,12 @@ export const CustomThreshold = ({
|
|||||||
maxWidth="var(--env-var-width-4)"
|
maxWidth="var(--env-var-width-4)"
|
||||||
type="number"
|
type="number"
|
||||||
id={fieldId}
|
id={fieldId}
|
||||||
value={infrastructureMonitor[fieldId]}
|
name={fieldName}
|
||||||
|
value={fieldValue}
|
||||||
onBlur={onFieldBlur}
|
onBlur={onFieldBlur}
|
||||||
onChange={onFieldChange}
|
onChange={onFieldChange}
|
||||||
error={errors[fieldId] ? true : false}
|
error={errors[fieldId] ? true : false}
|
||||||
disabled={!infrastructureMonitor[checkboxId]}
|
disabled={!isChecked}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Typography
|
<Typography
|
||||||
@@ -80,10 +108,14 @@ export const CustomThreshold = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
CustomThreshold.propTypes = {
|
CustomThreshold.propTypes = {
|
||||||
checkboxId: PropTypes.string.isRequired,
|
checkboxId: PropTypes.string,
|
||||||
|
checkboxName: PropTypes.string,
|
||||||
checkboxLabel: PropTypes.string.isRequired,
|
checkboxLabel: PropTypes.string.isRequired,
|
||||||
|
isChecked: PropTypes.bool.isRequired,
|
||||||
onCheckboxChange: PropTypes.func.isRequired,
|
onCheckboxChange: PropTypes.func.isRequired,
|
||||||
fieldId: PropTypes.string.isRequired,
|
fieldId: PropTypes.string.isRequired,
|
||||||
|
fieldName: PropTypes.string,
|
||||||
|
fieldValue: PropTypes.string.isRequired,
|
||||||
onFieldChange: PropTypes.func.isRequired,
|
onFieldChange: PropTypes.func.isRequired,
|
||||||
onFieldBlur: PropTypes.func.isRequired,
|
onFieldBlur: PropTypes.func.isRequired,
|
||||||
alertUnit: PropTypes.string.isRequired,
|
alertUnit: PropTypes.string.isRequired,
|
||||||
|
|||||||
@@ -1,27 +1,62 @@
|
|||||||
import { useState } from "react";
|
// React, Redux, Router
|
||||||
import { Box, Stack, Typography } from "@mui/material";
|
|
||||||
import LoadingButton from "@mui/lab/LoadingButton";
|
|
||||||
import { useSelector, useDispatch } from "react-redux";
|
|
||||||
import { infrastructureMonitorValidation } from "../../../Validation/validation";
|
|
||||||
import { parseDomainName } from "../../../Utils/monitorUtils";
|
|
||||||
import {
|
|
||||||
createInfrastructureMonitor,
|
|
||||||
checkInfrastructureEndpointResolution,
|
|
||||||
} from "../../../Features/InfrastructureMonitors/infrastructureMonitorsSlice";
|
|
||||||
import { useNavigate } from "react-router-dom";
|
|
||||||
import { useTheme } from "@emotion/react";
|
import { useTheme } from "@emotion/react";
|
||||||
import { createToast } from "../../../Utils/toastUtils";
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useSelector, useDispatch } from "react-redux";
|
||||||
|
|
||||||
|
// Utility and Network
|
||||||
|
import { infrastructureMonitorValidation } from "../../../Validation/validation";
|
||||||
|
import { createInfrastructureMonitor } from "../../../Features/InfrastructureMonitors/infrastructureMonitorsSlice";
|
||||||
|
import { capitalizeFirstLetter } from "../../../Utils/stringUtils";
|
||||||
|
|
||||||
|
// MUI
|
||||||
|
import { Box, Stack, Typography, Button, ButtonGroup } from "@mui/material";
|
||||||
|
import LoadingButton from "@mui/lab/LoadingButton";
|
||||||
|
|
||||||
|
//Components
|
||||||
|
import Breadcrumbs from "../../../Components/Breadcrumbs";
|
||||||
import Link from "../../../Components/Link";
|
import Link from "../../../Components/Link";
|
||||||
import { ConfigBox } from "../../Uptime/styled";
|
import { ConfigBox } from "../../Uptime/styled";
|
||||||
import TextInput from "../../../Components/Inputs/TextInput";
|
import TextInput from "../../../Components/Inputs/TextInput";
|
||||||
import Select from "../../../Components/Inputs/Select";
|
import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments";
|
||||||
|
import { createToast } from "../../../Utils/toastUtils";
|
||||||
import Checkbox from "../../../Components/Inputs/Checkbox";
|
import Checkbox from "../../../Components/Inputs/Checkbox";
|
||||||
import Breadcrumbs from "../../../Components/Breadcrumbs";
|
import Select from "../../../Components/Inputs/Select";
|
||||||
import { buildErrors, hasValidationErrors } from "../../../Validation/error";
|
import { CustomThreshold } from "./CustomThreshold";
|
||||||
import { capitalizeFirstLetter } from "../../../Utils/stringUtils";
|
|
||||||
import { CustomThreshold } from "../CreateMonitor/CustomThreshold";
|
const SELECT_VALUES = [
|
||||||
|
{ _id: 0.25, name: "15 seconds" },
|
||||||
|
{ _id: 0.5, name: "30 seconds" },
|
||||||
|
{ _id: 1, name: "1 minute" },
|
||||||
|
{ _id: 2, name: "2 minutes" },
|
||||||
|
{ _id: 5, name: "5 minutes" },
|
||||||
|
{ _id: 10, name: "10 minutes" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const METRICS = ["cpu", "memory", "disk", "temperature"];
|
||||||
|
const METRIC_PREFIX = "usage_";
|
||||||
|
const MS_PER_MINUTE = 60000;
|
||||||
|
|
||||||
|
const hasAlertError = (errors) => {
|
||||||
|
return Object.keys(errors).filter((k) => k.startsWith(METRIC_PREFIX)).length > 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getAlertError = (errors) => {
|
||||||
|
return Object.keys(errors).find((key) => key.startsWith(METRIC_PREFIX))
|
||||||
|
? errors[Object.keys(errors).find((key) => key.startsWith(METRIC_PREFIX))]
|
||||||
|
: null;
|
||||||
|
};
|
||||||
|
|
||||||
const CreateInfrastructureMonitor = () => {
|
const CreateInfrastructureMonitor = () => {
|
||||||
|
const theme = useTheme();
|
||||||
|
const { user, authToken } = useSelector((state) => state.auth);
|
||||||
|
const monitorState = useSelector((state) => state.infrastructureMonitor);
|
||||||
|
const dispatch = useDispatch();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
// State
|
||||||
|
const [errors, setErrors] = useState({});
|
||||||
|
const [https, setHttps] = useState(false);
|
||||||
const [infrastructureMonitor, setInfrastructureMonitor] = useState({
|
const [infrastructureMonitor, setInfrastructureMonitor] = useState({
|
||||||
url: "",
|
url: "",
|
||||||
name: "",
|
name: "",
|
||||||
@@ -38,118 +73,73 @@ const CreateInfrastructureMonitor = () => {
|
|||||||
secret: "",
|
secret: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
const MS_PER_MINUTE = 60000;
|
// Handlers
|
||||||
const THRESHOLD_FIELD_PREFIX = "usage_";
|
const handleCreateInfrastructureMonitor = async (event) => {
|
||||||
const HARDWARE_MONITOR_TYPES = ["cpu", "memory", "disk", "temperature"];
|
|
||||||
const { user, authToken } = useSelector((state) => state.auth);
|
|
||||||
const monitorState = useSelector((state) => state.infrastructureMonitor);
|
|
||||||
const dispatch = useDispatch();
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const theme = useTheme();
|
|
||||||
|
|
||||||
const idMap = {
|
|
||||||
"notify-email-default": "notification-email",
|
|
||||||
};
|
|
||||||
|
|
||||||
const [errors, setErrors] = useState({});
|
|
||||||
|
|
||||||
const alertErrKeyLen = Object.keys(errors).filter((k) =>
|
|
||||||
k.startsWith(THRESHOLD_FIELD_PREFIX)
|
|
||||||
).length;
|
|
||||||
|
|
||||||
const handleCustomAlertCheckChange = (event) => {
|
|
||||||
const { value, id } = event.target;
|
|
||||||
setInfrastructureMonitor((prev) => {
|
|
||||||
const newState = {
|
|
||||||
[id]: prev[id] == undefined && value == "on" ? true : !prev[id],
|
|
||||||
};
|
|
||||||
return {
|
|
||||||
...prev,
|
|
||||||
...newState,
|
|
||||||
[THRESHOLD_FIELD_PREFIX + id]: newState[id]
|
|
||||||
? prev[THRESHOLD_FIELD_PREFIX + id]
|
|
||||||
: "",
|
|
||||||
};
|
|
||||||
});
|
|
||||||
// Remove the error if unchecked
|
|
||||||
setErrors((prev) => {
|
|
||||||
return buildErrors(prev, [THRESHOLD_FIELD_PREFIX + id]);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleBlur = (event, appendID) => {
|
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const { value, id } = event.target;
|
|
||||||
|
|
||||||
let name = idMap[id] ?? id;
|
// Build the form
|
||||||
if (name === "url" && infrastructureMonitor.name === "") {
|
let form = {
|
||||||
setInfrastructureMonitor((prev) => ({
|
url: `http${https ? "s" : ""}://` + infrastructureMonitor.url,
|
||||||
...prev,
|
name:
|
||||||
name: parseDomainName(value),
|
infrastructureMonitor.name === ""
|
||||||
}));
|
? infrastructureMonitor.url
|
||||||
|
: infrastructureMonitor.name,
|
||||||
|
interval: infrastructureMonitor.interval * MS_PER_MINUTE,
|
||||||
|
cpu: infrastructureMonitor.cpu,
|
||||||
|
...(infrastructureMonitor.cpu
|
||||||
|
? { usage_cpu: infrastructureMonitor.usage_cpu }
|
||||||
|
: {}),
|
||||||
|
memory: infrastructureMonitor.memory,
|
||||||
|
...(infrastructureMonitor.memory
|
||||||
|
? { usage_memory: infrastructureMonitor.usage_memory }
|
||||||
|
: {}),
|
||||||
|
disk: infrastructureMonitor.disk,
|
||||||
|
...(infrastructureMonitor.disk
|
||||||
|
? { usage_disk: infrastructureMonitor.usage_disk }
|
||||||
|
: {}),
|
||||||
|
temperature: infrastructureMonitor.temperature,
|
||||||
|
...(infrastructureMonitor.temperature
|
||||||
|
? { usage_temperature: infrastructureMonitor.usage_temperature }
|
||||||
|
: {}),
|
||||||
|
secret: infrastructureMonitor.secret,
|
||||||
|
};
|
||||||
|
|
||||||
|
const { error } = infrastructureMonitorValidation.validate(form, {
|
||||||
|
abortEarly: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
const newErrors = {};
|
||||||
|
error.details.forEach((err) => {
|
||||||
|
newErrors[err.path[0]] = err.message;
|
||||||
|
});
|
||||||
|
setErrors(newErrors);
|
||||||
|
createToast({ body: "Please check the form for errors." });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (id?.startsWith("notify-email-")) return;
|
// Build the thresholds for the form
|
||||||
const { error } = infrastructureMonitorValidation.validate(
|
const {
|
||||||
{ [id ?? appendID]: value },
|
cpu,
|
||||||
{
|
usage_cpu,
|
||||||
abortEarly: false,
|
memory,
|
||||||
}
|
usage_memory,
|
||||||
);
|
disk,
|
||||||
setErrors((prev) => {
|
usage_disk,
|
||||||
return buildErrors(prev, id ?? appendID, error);
|
temperature,
|
||||||
});
|
usage_temperature,
|
||||||
};
|
...rest
|
||||||
|
} = form;
|
||||||
|
|
||||||
const handleChange = (event, appendedId) => {
|
const thresholds = {
|
||||||
event.preventDefault();
|
...(cpu ? { usage_cpu: usage_cpu / 100 } : {}),
|
||||||
const { value, id } = event.target;
|
...(memory ? { usage_memory: usage_memory / 100 } : {}),
|
||||||
let name = appendedId ?? idMap[id] ?? id;
|
...(disk ? { usage_disk: usage_disk / 100 } : {}),
|
||||||
if (name.includes("notification-")) {
|
...(temperature ? { usage_temperature: usage_temperature / 100 } : {}),
|
||||||
name = name.replace("notification-", "");
|
};
|
||||||
let hasNotif = infrastructureMonitor.notifications.some(
|
|
||||||
(notification) => notification.type === name
|
|
||||||
);
|
|
||||||
setInfrastructureMonitor((prev) => {
|
|
||||||
const notifs = [...prev.notifications];
|
|
||||||
if (hasNotif) {
|
|
||||||
return {
|
|
||||||
...prev,
|
|
||||||
notifications: notifs.filter((notif) => notif.type !== name),
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
return {
|
|
||||||
...prev,
|
|
||||||
notifications: [
|
|
||||||
...notifs,
|
|
||||||
name === "email"
|
|
||||||
? { type: name, address: value }
|
|
||||||
: // TODO - phone number
|
|
||||||
{ type: name, phone: value },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
setInfrastructureMonitor((prev) => ({
|
|
||||||
...prev,
|
|
||||||
[name]: value,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const generatePayload = (form) => {
|
|
||||||
let thresholds = {};
|
|
||||||
Object.keys(form)
|
|
||||||
.filter((k) => k.startsWith(THRESHOLD_FIELD_PREFIX))
|
|
||||||
.map((k) => {
|
|
||||||
if (form[k]) thresholds[k] = form[k] / 100;
|
|
||||||
delete form[k];
|
|
||||||
delete form[k.substring(THRESHOLD_FIELD_PREFIX.length)];
|
|
||||||
});
|
|
||||||
|
|
||||||
form = {
|
form = {
|
||||||
...form,
|
...rest,
|
||||||
description: form.name,
|
description: form.name,
|
||||||
teamId: user.teamId,
|
teamId: user.teamId,
|
||||||
userId: user._id,
|
userId: user._id,
|
||||||
@@ -157,54 +147,69 @@ const CreateInfrastructureMonitor = () => {
|
|||||||
notifications: infrastructureMonitor.notifications,
|
notifications: infrastructureMonitor.notifications,
|
||||||
thresholds,
|
thresholds,
|
||||||
};
|
};
|
||||||
return form;
|
|
||||||
};
|
|
||||||
const handleCreateInfrastructureMonitor = async (event) => {
|
|
||||||
event.preventDefault();
|
|
||||||
let form = {
|
|
||||||
...infrastructureMonitor,
|
|
||||||
name:
|
|
||||||
infrastructureMonitor.name === ""
|
|
||||||
? infrastructureMonitor.url
|
|
||||||
: infrastructureMonitor.name,
|
|
||||||
interval: infrastructureMonitor.interval * MS_PER_MINUTE,
|
|
||||||
};
|
|
||||||
|
|
||||||
delete form.notifications;
|
const action = await dispatch(
|
||||||
if (hasValidationErrors(form, infrastructureMonitorValidation, setErrors)) {
|
createInfrastructureMonitor({ authToken, monitor: form })
|
||||||
return;
|
);
|
||||||
|
if (action.meta.requestStatus === "fulfilled") {
|
||||||
|
createToast({ body: "Infrastructure monitor created successfully!" });
|
||||||
|
navigate("/infrastructure");
|
||||||
} else {
|
} else {
|
||||||
const checkEndpointAction = await dispatch(
|
createToast({ body: "Failed to create monitor." });
|
||||||
checkInfrastructureEndpointResolution({ authToken, monitorURL: form.url })
|
|
||||||
);
|
|
||||||
if (checkEndpointAction.meta.requestStatus === "rejected") {
|
|
||||||
createToast({
|
|
||||||
body: "The endpoint you entered doesn't resolve. Check the URL again.",
|
|
||||||
});
|
|
||||||
setErrors({ url: "The entered URL is not reachable." });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const action = await dispatch(
|
|
||||||
createInfrastructureMonitor({ authToken, monitor: generatePayload(form) })
|
|
||||||
);
|
|
||||||
if (action.meta.requestStatus === "fulfilled") {
|
|
||||||
createToast({ body: "Infrastructure monitor created successfully!" });
|
|
||||||
navigate("/infrastructure");
|
|
||||||
} else {
|
|
||||||
createToast({ body: "Failed to create monitor." });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
//select values
|
const handleChange = (event) => {
|
||||||
const frequencies = [
|
const { value, name } = event.target;
|
||||||
{ _id: 0.25, name: "15 seconds" },
|
setInfrastructureMonitor({
|
||||||
{ _id: 0.5, name: "30 seconds" },
|
...infrastructureMonitor,
|
||||||
{ _id: 1, name: "1 minute" },
|
[name]: value,
|
||||||
{ _id: 2, name: "2 minutes" },
|
});
|
||||||
{ _id: 5, name: "5 minutes" },
|
|
||||||
{ _id: 10, name: "10 minutes" },
|
const { error } = infrastructureMonitorValidation.validate(
|
||||||
];
|
{ [name]: value },
|
||||||
|
{ abortEarly: false }
|
||||||
|
);
|
||||||
|
setErrors((prev) => ({
|
||||||
|
...prev,
|
||||||
|
...(error ? { [name]: error.details[0].message } : { [name]: undefined }),
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCheckboxChange = (event) => {
|
||||||
|
const { name } = event.target;
|
||||||
|
const { checked } = event.target;
|
||||||
|
setInfrastructureMonitor({
|
||||||
|
...infrastructureMonitor,
|
||||||
|
[name]: checked,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleNotifications = (event, type) => {
|
||||||
|
const { value } = event.target;
|
||||||
|
let notifications = [...infrastructureMonitor.notifications];
|
||||||
|
const notificationExists = notifications.some((notification) => {
|
||||||
|
if (notification.type === type && notification.address === value) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
if (notificationExists) {
|
||||||
|
notifications = notifications.filter((notification) => {
|
||||||
|
if (notification.type === type && notification.address === value) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
notifications.push({ type, address: value });
|
||||||
|
}
|
||||||
|
|
||||||
|
setInfrastructureMonitor((prev) => ({
|
||||||
|
...prev,
|
||||||
|
notifications,
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box className="create-infrastructure-monitor">
|
<Box className="create-infrastructure-monitor">
|
||||||
@@ -239,56 +244,75 @@ const CreateInfrastructureMonitor = () => {
|
|||||||
fontSize="inherit"
|
fontSize="inherit"
|
||||||
fontWeight="inherit"
|
fontWeight="inherit"
|
||||||
>
|
>
|
||||||
infrastructure monitor
|
monitor
|
||||||
</Typography>
|
</Typography>
|
||||||
</Typography>
|
</Typography>
|
||||||
<ConfigBox>
|
<ConfigBox>
|
||||||
<Box>
|
<Stack gap={theme.spacing(6)}>
|
||||||
<Stack gap={theme.spacing(6)}>
|
<Typography component="h2">General settings</Typography>
|
||||||
<Typography component="h2">General settings</Typography>
|
<Typography component="p">
|
||||||
<Typography component="p">
|
Here you can select the URL of the host, together with the friendly name and
|
||||||
Here you can select the URL of the host, together with the friendly name
|
authorization secret to connect to the server agent.
|
||||||
and authorization secret to connect to the server agent.
|
</Typography>
|
||||||
</Typography>
|
<Typography component="p">
|
||||||
<Typography component="p">
|
The server you are monitoring must be running the{" "}
|
||||||
The server you are monitoring must be running the{" "}
|
<Link
|
||||||
<Link
|
level="primary"
|
||||||
level="primary"
|
url="https://github.com/bluewave-labs/checkmate-agent"
|
||||||
url="https://github.com/bluewave-labs/checkmate-agent"
|
label="Checkmate Monitoring Agent"
|
||||||
label="Checkmate Monitoring Agent"
|
/>
|
||||||
/>
|
</Typography>
|
||||||
</Typography>
|
</Stack>
|
||||||
</Stack>
|
|
||||||
</Box>
|
|
||||||
<Stack gap={theme.spacing(15)}>
|
<Stack gap={theme.spacing(15)}>
|
||||||
<TextInput
|
<TextInput
|
||||||
type="text"
|
type="url"
|
||||||
id="url"
|
id="url"
|
||||||
|
name="url"
|
||||||
|
startAdornment={<HttpAdornment https={https} />}
|
||||||
|
placeholder={"localhost:59232/api/v1/metrics"}
|
||||||
label="Server URL"
|
label="Server URL"
|
||||||
placeholder="https://"
|
https={https}
|
||||||
value={infrastructureMonitor.url}
|
value={infrastructureMonitor.url}
|
||||||
onBlur={handleBlur}
|
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
error={errors["url"] ? true : false}
|
error={errors["url"] ? true : false}
|
||||||
helperText={errors["url"]}
|
helperText={errors["url"]}
|
||||||
/>
|
/>
|
||||||
|
<Box>
|
||||||
|
<Typography component="p">Protocol</Typography>
|
||||||
|
<ButtonGroup>
|
||||||
|
<Button
|
||||||
|
variant="group"
|
||||||
|
filled={https.toString()}
|
||||||
|
onClick={() => setHttps(true)}
|
||||||
|
>
|
||||||
|
HTTPS
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="group"
|
||||||
|
filled={(!https).toString()}
|
||||||
|
onClick={() => setHttps(false)}
|
||||||
|
>
|
||||||
|
HTTP
|
||||||
|
</Button>
|
||||||
|
</ButtonGroup>
|
||||||
|
</Box>
|
||||||
<TextInput
|
<TextInput
|
||||||
type="text"
|
type="text"
|
||||||
id="name"
|
id="name"
|
||||||
|
name="name"
|
||||||
label="Display name"
|
label="Display name"
|
||||||
placeholder="Google"
|
placeholder="Google"
|
||||||
isOptional={true}
|
isOptional={true}
|
||||||
value={infrastructureMonitor.name}
|
value={infrastructureMonitor.name}
|
||||||
onBlur={handleBlur}
|
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
error={errors["name"]}
|
error={errors["name"]}
|
||||||
/>
|
/>
|
||||||
<TextInput
|
<TextInput
|
||||||
type="text"
|
type="text"
|
||||||
id="secret"
|
id="secret"
|
||||||
|
name="secret"
|
||||||
label="Authorization secret"
|
label="Authorization secret"
|
||||||
value={infrastructureMonitor.secret}
|
value={infrastructureMonitor.secret}
|
||||||
onBlur={handleBlur}
|
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
error={errors["secret"] ? true : false}
|
error={errors["secret"] ? true : false}
|
||||||
helperText={errors["secret"]}
|
helperText={errors["secret"]}
|
||||||
@@ -310,12 +334,10 @@ const CreateInfrastructureMonitor = () => {
|
|||||||
(notification) => notification.type === "email"
|
(notification) => notification.type === "email"
|
||||||
)}
|
)}
|
||||||
value={user?.email}
|
value={user?.email}
|
||||||
onChange={(e) => handleChange(e)}
|
onChange={(event) => handleNotifications(event, "email")}
|
||||||
onBlur={handleBlur}
|
|
||||||
/>
|
/>
|
||||||
</Stack>
|
</Stack>
|
||||||
</ConfigBox>
|
</ConfigBox>
|
||||||
|
|
||||||
<ConfigBox>
|
<ConfigBox>
|
||||||
<Box>
|
<Box>
|
||||||
<Typography component="h2">Customize alerts</Typography>
|
<Typography component="h2">Customize alerts</Typography>
|
||||||
@@ -325,25 +347,31 @@ const CreateInfrastructureMonitor = () => {
|
|||||||
</Typography>
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
<Stack gap={theme.spacing(6)}>
|
<Stack gap={theme.spacing(6)}>
|
||||||
{HARDWARE_MONITOR_TYPES.map((type, idx) => (
|
{METRICS.map((metric) => {
|
||||||
<CustomThreshold
|
return (
|
||||||
key={idx}
|
<CustomThreshold
|
||||||
checkboxId={type}
|
key={metric}
|
||||||
checkboxLabel={
|
infrastructureMonitor={infrastructureMonitor}
|
||||||
type !== "cpu" ? capitalizeFirstLetter(type) : type.toUpperCase()
|
errors={errors}
|
||||||
}
|
checkboxId={metric}
|
||||||
onCheckboxChange={handleCustomAlertCheckChange}
|
checkboxName={metric}
|
||||||
fieldId={THRESHOLD_FIELD_PREFIX + type}
|
checkboxLabel={
|
||||||
fieldValue={infrastructureMonitor[THRESHOLD_FIELD_PREFIX + type] ?? ""}
|
metric !== "cpu"
|
||||||
onFieldChange={handleChange}
|
? capitalizeFirstLetter(metric)
|
||||||
onFieldBlur={handleBlur}
|
: metric.toUpperCase()
|
||||||
// TODO: need BE, maybe in another PR
|
}
|
||||||
alertUnit={type == "temperature" ? "°C" : "%"}
|
onCheckboxChange={handleCheckboxChange}
|
||||||
infrastructureMonitor={infrastructureMonitor}
|
isChecked={infrastructureMonitor[metric]}
|
||||||
errors={errors}
|
fieldId={METRIC_PREFIX + metric}
|
||||||
/>
|
fieldName={METRIC_PREFIX + metric}
|
||||||
))}
|
fieldValue={infrastructureMonitor[METRIC_PREFIX + metric]}
|
||||||
{alertErrKeyLen > 0 && (
|
onFieldChange={handleChange}
|
||||||
|
alertUnit={metric == "temperature" ? "°C" : "%"}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{/* Error text */}
|
||||||
|
{hasAlertError(errors) && (
|
||||||
<Typography
|
<Typography
|
||||||
component="span"
|
component="span"
|
||||||
className="input-error"
|
className="input-error"
|
||||||
@@ -353,14 +381,7 @@ const CreateInfrastructureMonitor = () => {
|
|||||||
opacity: 0.8,
|
opacity: 0.8,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{
|
{getAlertError(errors)}
|
||||||
errors[
|
|
||||||
THRESHOLD_FIELD_PREFIX +
|
|
||||||
HARDWARE_MONITOR_TYPES.filter(
|
|
||||||
(type) => errors[THRESHOLD_FIELD_PREFIX + type]
|
|
||||||
)[0]
|
|
||||||
]
|
|
||||||
}
|
|
||||||
</Typography>
|
</Typography>
|
||||||
)}
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
@@ -372,11 +393,12 @@ const CreateInfrastructureMonitor = () => {
|
|||||||
<Stack gap={theme.spacing(12)}>
|
<Stack gap={theme.spacing(12)}>
|
||||||
<Select
|
<Select
|
||||||
id="interval"
|
id="interval"
|
||||||
|
name="interval"
|
||||||
label="Check frequency"
|
label="Check frequency"
|
||||||
value={infrastructureMonitor.interval || 15}
|
value={infrastructureMonitor.interval || 15}
|
||||||
onChange={(e) => handleChange(e, "interval")}
|
onChange={handleChange}
|
||||||
onBlur={(e) => handleBlur(e, "interval")}
|
onBlur={}
|
||||||
items={frequencies}
|
items={SELECT_VALUES}
|
||||||
/>
|
/>
|
||||||
</Stack>
|
</Stack>
|
||||||
</ConfigBox>
|
</ConfigBox>
|
||||||
|
|||||||
@@ -91,10 +91,24 @@ const credentials = joi.object({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const monitorValidation = joi.object({
|
const monitorValidation = joi.object({
|
||||||
url: joi.string().uri({ allowRelative: true }).trim().messages({
|
url: joi
|
||||||
"string.empty": "This field is required.",
|
.string()
|
||||||
"string.uri": "The URL you provided is not valid.",
|
.trim()
|
||||||
}),
|
.custom((value, helpers) => {
|
||||||
|
const urlRegex =
|
||||||
|
/^(https?:\/\/)?(([0-9]{1,3}\.){3}[0-9]{1,3}|[\da-z\.-]+)(\.[a-z\.]{2,6})?(:(\d+))?([\/\w \.-]*)*\/?$/i;
|
||||||
|
|
||||||
|
if (!urlRegex.test(value)) {
|
||||||
|
return helpers.error("string.invalidUrl");
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
})
|
||||||
|
.messages({
|
||||||
|
"string.empty": "This field is required.",
|
||||||
|
"string.uri": "The URL you provided is not valid.",
|
||||||
|
"string.invalidUrl": "Please enter a valid URL with optional port",
|
||||||
|
}),
|
||||||
name: joi.string().trim().max(50).allow("").messages({
|
name: joi.string().trim().max(50).allow("").messages({
|
||||||
"string.max": "This field should not exceed the 50 characters limit.",
|
"string.max": "This field should not exceed the 50 characters limit.",
|
||||||
}),
|
}),
|
||||||
@@ -176,10 +190,24 @@ const advancedSettingsValidation = joi.object({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const infrastructureMonitorValidation = joi.object({
|
const infrastructureMonitorValidation = joi.object({
|
||||||
url: joi.string().uri({ allowRelative: true }).trim().messages({
|
url: joi
|
||||||
"string.empty": "This field is required.",
|
.string()
|
||||||
"string.uri": "The URL you provided is not valid.",
|
.trim()
|
||||||
}),
|
.custom((value, helpers) => {
|
||||||
|
const urlRegex =
|
||||||
|
/^(https?:\/\/)?(([0-9]{1,3}\.){3}[0-9]{1,3}|[\da-z\.-]+)(\.[a-z\.]{2,6})?(:(\d+))?([\/\w \.-]*)*\/?$/i;
|
||||||
|
|
||||||
|
if (!urlRegex.test(value)) {
|
||||||
|
return helpers.error("string.invalidUrl");
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
})
|
||||||
|
.messages({
|
||||||
|
"string.empty": "This field is required.",
|
||||||
|
"string.uri": "The URL you provided is not valid.",
|
||||||
|
"string.invalidUrl": "Please enter a valid URL with optional port",
|
||||||
|
}),
|
||||||
name: joi.string().trim().max(50).allow("").messages({
|
name: joi.string().trim().max(50).allow("").messages({
|
||||||
"string.max": "This field should not exceed the 50 characters limit.",
|
"string.max": "This field should not exceed the 50 characters limit.",
|
||||||
}),
|
}),
|
||||||
|
|||||||
Reference in new issue
Block a user