Files
Checkmate/client/src/Pages/Uptime/Create/index.jsx
T

542 lines
15 KiB
React
Raw Normal View History

2024-12-03 15:29:19 +08:00
// React, Redux, Router
import { useTheme } from "@emotion/react";
import { useNavigate, useParams } from "react-router-dom";
import { useEffect } from "react";
import { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { useTranslation } from "react-i18next";
2024-12-03 15:29:19 +08:00
// Utility and Network
import { checkEndpointResolution } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
2024-07-19 18:04:58 -04:00
import { monitorValidation } from "../../../Validation/validation";
2024-12-03 15:29:19 +08:00
import { getUptimeMonitorById } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
2024-07-30 11:25:14 -07:00
import { createUptimeMonitor } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
2024-12-03 15:29:19 +08:00
// MUI
import { Box, Stack, Typography, Button, ButtonGroup } from "@mui/material";
2025-05-08 15:28:44 +05:30
import Switch from "@mui/material/Switch";
import FormControlLabel from "@mui/material/FormControlLabel";
2024-12-03 15:29:19 +08:00
//Components
import Breadcrumbs from "../../../Components/Breadcrumbs";
2024-11-26 12:21:42 +08:00
import TextInput from "../../../Components/Inputs/TextInput";
import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments";
2024-12-03 15:29:19 +08:00
import { createToast } from "../../../Utils/toastUtils";
import Radio from "../../../Components/Inputs/Radio";
import Checkbox from "../../../Components/Inputs/Checkbox";
2024-12-03 15:29:19 +08:00
import Select from "../../../Components/Inputs/Select";
2024-12-18 12:20:18 -08:00
import ConfigBox from "../../../Components/ConfigBox";
import NotificationIntegrationModal from "../../../Components/NotificationIntegrationModal/Components/NotificationIntegrationModal";
2024-07-17 20:15:45 -04:00
const CreateMonitor = () => {
const MS_PER_MINUTE = 60000;
2024-12-03 15:29:19 +08:00
const SELECT_VALUES = [
{ _id: 1, name: "1 minute" },
{ _id: 2, name: "2 minutes" },
{ _id: 3, name: "3 minutes" },
{ _id: 4, name: "4 minutes" },
{ _id: 5, name: "5 minutes" },
];
const matchMethodOptions = [
{ _id: "equal", name: "Equal" },
{ _id: "include", name: "Include" },
{ _id: "regex", name: "Regex" },
];
const expectedValuePlaceholders = {
2025-03-28 13:06:40 -04:00
regex: "^(success|ok)$",
equal: "success",
include: "ok",
};
const monitorTypeMaps = {
http: {
label: "URL to monitor",
placeholder: "google.com",
namePlaceholder: "Google",
},
ping: {
label: "IP address to monitor",
placeholder: "1.1.1.1",
namePlaceholder: "Google",
},
docker: {
label: "Container ID",
placeholder: "abc123",
namePlaceholder: "My Container",
},
2024-12-27 11:16:58 -08:00
port: {
label: "URL to monitor",
placeholder: "localhost",
namePlaceholder: "Localhost:5173",
},
};
const { user } = useSelector((state) => state.auth);
2025-01-07 10:12:41 -08:00
const { isLoading } = useSelector((state) => state.uptimeMonitors);
const dispatch = useDispatch();
const navigate = useNavigate();
const theme = useTheme();
const { monitorId } = useParams();
2024-12-03 15:29:19 +08:00
const crumbs = [
2024-12-10 14:23:46 +08:00
{ name: "uptime", path: "/uptime" },
{ name: "create", path: `/uptime/create` },
2024-12-03 15:29:19 +08:00
];
// State
2025-03-01 22:36:07 -08:00
const [isNotificationModalOpen, setIsNotificationModalOpen] = useState(false);
const handleOpenNotificationModal = () => {
2025-03-19 09:02:30 -07:00
setIsNotificationModalOpen(true);
};
2024-12-03 15:29:19 +08:00
const [errors, setErrors] = useState({});
const [https, setHttps] = useState(true);
const [monitor, setMonitor] = useState({
url: "",
name: "",
type: "http",
2025-05-08 15:28:44 +05:30
ignoreTlsErrors: false,
notifications: [],
interval: 1,
});
2024-11-27 15:48:06 +08:00
const handleCreateMonitor = async (event) => {
event.preventDefault();
let form = {
url:
2024-12-03 15:29:19 +08:00
//prepending protocol for url
monitor.type === "http"
? `http${https ? "s" : ""}://` + monitor.url
: monitor.url,
2024-12-27 11:16:58 -08:00
port: monitor.type === "port" ? monitor.port : undefined,
2025-02-01 22:14:27 +08:00
name: monitor.name || monitor.url.substring(0, 50),
type: monitor.type,
2025-05-08 15:28:44 +05:30
ignoreTlsErrors: monitor.ignoreTlsErrors,
interval: monitor.interval * MS_PER_MINUTE,
};
2024-06-27 17:26:00 -04:00
2025-02-13 00:54:24 +00:00
if (monitor.type === "http") {
form.expectedValue = monitor.expectedValue;
form.jsonPath = monitor.jsonPath;
form.matchMethod = monitor.matchMethod;
}
const { error } = monitorValidation.validate(form, {
abortEarly: false,
});
2024-07-18 12:11:27 -07:00
if (error) {
const newErrors = {};
error.details.forEach((err) => {
newErrors[err.path[0]] = err.message;
});
setErrors(newErrors);
2024-12-03 15:29:19 +08:00
createToast({ body: "Please check the form for errors." });
return;
}
form = {
...form,
2025-02-01 22:14:27 +08:00
description: monitor.name || monitor.url,
2024-12-03 15:29:19 +08:00
teamId: user.teamId,
userId: user._id,
notifications: monitor.notifications,
};
const action = await dispatch(createUptimeMonitor({ monitor: form }));
2024-12-03 15:29:19 +08:00
if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Monitor created successfully!" });
2024-12-10 14:23:46 +08:00
navigate("/uptime");
2024-12-03 15:29:19 +08:00
} else {
createToast({ body: "Failed to create monitor." });
}
};
const handleChange = (event, formName) => {
2025-05-08 15:28:44 +05:30
const { type, checked, value } = event.target;
const newVal = type === "checkbox" ? checked : value;
2025-02-01 22:14:27 +08:00
const newMonitor = {
2024-12-03 15:29:19 +08:00
...monitor,
2025-05-08 15:28:44 +05:30
[formName]: newVal,
2025-02-01 22:14:27 +08:00
};
2025-02-13 15:20:12 -08:00
if (formName === "type") {
newMonitor.url = "";
2025-02-01 22:14:27 +08:00
}
setMonitor(newMonitor);
2024-12-03 15:29:19 +08:00
const { error } = monitorValidation.validate(
2025-05-08 15:28:44 +05:30
{ type: monitor.type, [formName]: newVal },
2024-12-03 15:29:19 +08:00
{ abortEarly: false }
);
setErrors((prev) => ({
...prev,
2025-02-01 22:14:27 +08:00
url: undefined,
2024-12-03 15:29:19 +08:00
...(error ? { [formName]: error.details[0].message } : { [formName]: undefined }),
}));
};
2024-12-03 15:29:19 +08:00
const handleNotifications = (event, type) => {
const { value } = event.target;
let notifications = [...monitor.notifications];
const notificationExists = notifications.some((notification) => {
if (notification.type === type && notification.address === value) {
return true;
}
2024-12-03 15:29:19 +08:00
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 });
}
2024-12-03 15:29:19 +08:00
setMonitor((prev) => ({
...prev,
notifications,
}));
};
2024-06-27 16:44:56 -04:00
2024-12-03 15:29:19 +08:00
useEffect(() => {
const fetchMonitor = async () => {
if (monitorId) {
const action = await dispatch(getUptimeMonitorById({ monitorId }));
2024-12-03 15:29:19 +08:00
if (action.payload.success) {
const data = action.payload.data;
const { name, ...rest } = data; //data.name is read-only
if (rest.type === "http") {
const url = new URL(rest.url);
rest.url = url.host;
}
rest.name = `${name} (Clone)`;
rest.interval /= MS_PER_MINUTE;
setMonitor({
...rest,
});
} else {
navigate("/not-found", { replace: true });
createToast({
body: "There was an error cloning the monitor.",
});
}
}
};
fetchMonitor();
}, [monitorId, dispatch, navigate]);
2024-06-25 13:22:28 +03:30
2025-03-17 01:16:42 +05:30
const { t } = useTranslation();
return (
<Box className="create-monitor">
2024-12-03 15:29:19 +08:00
<Breadcrumbs list={crumbs} />
<Stack
component="form"
gap={theme.spacing(12)}
mt={theme.spacing(6)}
2024-12-03 15:29:19 +08:00
onSubmit={handleCreateMonitor}
>
<Typography
component="h1"
variant="h1"
>
<Typography
component="span"
fontSize="inherit"
>
2025-03-17 01:16:42 +05:30
{t("createYour")}{" "}
</Typography>
<Typography
component="span"
variant="h2"
fontSize="inherit"
fontWeight="inherit"
>
2025-03-17 01:16:42 +05:30
{t("monitor")}
</Typography>
</Typography>
<ConfigBox>
<Box>
2025-05-18 20:14:37 -04:00
<Typography component="h2" variant="h2">{t("distributedUptimeCreateChecks")}</Typography>
<Typography component="p">
2025-03-17 01:16:42 +05:30
{t("distributedUptimeCreateChecksDescription")}
</Typography>
</Box>
<Stack gap={theme.spacing(12)}>
<Stack gap={theme.spacing(6)}>
<Radio
id="monitor-checks-http"
2025-03-17 01:16:42 +05:30
title={t("websiteMonitoring")}
desc={t("websiteMonitoringDescription")}
size="small"
value="http"
checked={monitor.type === "http"}
2024-12-03 15:29:19 +08:00
onChange={(event) => handleChange(event, "type")}
/>
{monitor.type === "http" ? (
<ButtonGroup sx={{ ml: theme.spacing(16) }}>
<Button
variant="group"
filled={https.toString()}
onClick={() => setHttps(true)}
>
2025-03-17 01:16:42 +05:30
{t("https")}
</Button>
<Button
variant="group"
filled={(!https).toString()}
onClick={() => setHttps(false)}
>
2025-03-17 01:16:42 +05:30
{t("http")}
</Button>
</ButtonGroup>
) : (
""
)}
</Stack>
<Radio
id="monitor-checks-ping"
2025-03-17 01:16:42 +05:30
title={t("pingMonitoring")}
desc={t("pingMonitoringDescription")}
size="small"
value="ping"
checked={monitor.type === "ping"}
2024-12-03 15:29:19 +08:00
onChange={(event) => handleChange(event, "type")}
/>
<Radio
id="monitor-checks-docker"
2025-03-17 01:16:42 +05:30
title={t("dockerContainerMonitoring")}
desc={t("dockerContainerMonitoringDescription")}
size="small"
value="docker"
checked={monitor.type === "docker"}
2024-12-03 15:29:19 +08:00
onChange={(event) => handleChange(event, "type")}
/>
2024-12-27 11:16:58 -08:00
<Radio
id="monitor-checks-port"
2025-03-17 01:16:42 +05:30
title={t("portMonitoring")}
desc={t("portMonitoringDescription")}
2024-12-27 11:16:58 -08:00
size="small"
value="port"
checked={monitor.type === "port"}
onChange={(event) => handleChange(event, "type")}
/>
{errors["type"] ? (
<Box className="error-container">
<Typography
component="p"
className="input-error"
2024-11-10 17:00:13 -05:00
color={theme.palette.error.contrastText}
>
{errors["type"]}
</Typography>
</Box>
) : (
""
)}
</Stack>
</ConfigBox>
<ConfigBox>
<Box>
2025-05-18 20:14:37 -04:00
<Typography component="h2" variant="h2">{t("settingsGeneralSettings")}</Typography>
<Typography component="p">{t("uptimeCreateSelectURL")}</Typography>
</Box>
<Stack gap={theme.spacing(15)}>
<TextInput
type={monitor.type === "http" ? "url" : "text"}
id="monitor-url"
startAdornment={
monitor.type === "http" ? <HttpAdornment https={https} /> : null
}
label={monitorTypeMaps[monitor.type].label || "URL to monitor"}
https={https}
placeholder={monitorTypeMaps[monitor.type].placeholder || ""}
value={monitor.url}
onChange={(event) => handleChange(event, "url")}
error={errors["url"] ? true : false}
helperText={errors["url"]}
/>
<TextInput
type="number"
id="monitor-port"
2025-03-17 01:16:42 +05:30
label={t("portToMonitor")}
placeholder="5173"
value={monitor.port}
onChange={(event) => handleChange(event, "port")}
error={errors["port"] ? true : false}
helperText={errors["port"]}
hidden={monitor.type !== "port"}
/>
<TextInput
type="text"
id="monitor-name"
2025-03-17 01:16:42 +05:30
label={t("displayName")}
isOptional={true}
placeholder={monitorTypeMaps[monitor.type].namePlaceholder || ""}
value={monitor.name}
onChange={(event) => handleChange(event, "name")}
error={errors["name"] ? true : false}
helperText={errors["name"]}
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Box>
2025-05-18 20:14:37 -04:00
<Typography component="h2" variant="h2">
2025-03-19 09:02:30 -07:00
{t("distributedUptimeCreateIncidentNotification")}
</Typography>
<Typography component="p">
2025-03-17 01:16:42 +05:30
{t("distributedUptimeCreateIncidentDescription")}
</Typography>
</Box>
<Stack gap={theme.spacing(6)}>
<Checkbox
id="notify-email-default"
label={`Notify via email (to ${user.email})`}
isChecked={monitor.notifications.some(
(notification) => notification.type === "email"
)}
value={user?.email}
2024-12-03 15:29:19 +08:00
onChange={(event) => handleNotifications(event, "email")}
/>
2025-02-24 22:08:06 -08:00
2025-04-12 19:22:53 -07:00
<Box mt={theme.spacing(2)}>
2025-03-19 09:02:30 -07:00
<Button
variant="contained"
color="accent"
onClick={handleOpenNotificationModal}
>
{t("notifications.integrationButton")}
</Button>
2025-04-12 19:22:53 -07:00
</Box>
</Stack>
</ConfigBox>
2025-05-08 15:28:44 +05:30
<ConfigBox>
<Box>
2025-05-18 20:14:37 -04:00
<Typography component="h2" variant="h2">{t("ignoreTLSError")}</Typography>
2025-05-08 15:47:20 +05:30
<Typography component="p">{t("ignoreTLSErrorDescription")}</Typography>
2025-05-08 15:28:44 +05:30
</Box>
<Stack>
<FormControlLabel
2025-05-12 21:46:52 +05:30
sx={{ marginLeft: 0 }}
2025-05-08 15:28:44 +05:30
control={
<Switch
name="ignore-error"
checked={monitor.ignoreTlsErrors}
onChange={(event) => handleChange(event, "ignoreTlsErrors")}
sx={{ mr: theme.spacing(2) }}
/>
}
2025-05-08 15:47:20 +05:30
label={t("tlsErrorIgnored")}
2025-05-08 15:28:44 +05:30
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Box>
2025-05-18 20:14:37 -04:00
<Typography component="h2" variant="h2">
2025-03-19 09:02:30 -07:00
{t("distributedUptimeCreateAdvancedSettings")}
</Typography>
</Box>
<Stack gap={theme.spacing(12)}>
<Select
id="monitor-interval"
label="Check frequency"
value={monitor.interval || 1}
onChange={(event) => handleChange(event, "interval")}
2024-12-03 15:29:19 +08:00
items={SELECT_VALUES}
/>
2025-02-24 14:33:25 -08:00
{monitor.type === "http" && (
<>
2025-02-13 00:54:24 +00:00
<Select
id="match-method"
label="Match Method"
value={monitor.matchMethod || "equal"}
onChange={(event) => handleChange(event, "matchMethod")}
items={matchMethodOptions}
2025-02-13 00:54:24 +00:00
/>
<Stack>
<TextInput
type="text"
id="expected-value"
label="Expected value"
isOptional={true}
2025-02-24 14:33:25 -08:00
placeholder={
expectedValuePlaceholders[monitor.matchMethod || "equal"]
}
2025-02-13 00:54:24 +00:00
value={monitor.expectedValue}
onChange={(event) => handleChange(event, "expectedValue")}
error={errors["expectedValue"] ? true : false}
helperText={errors["expectedValue"]}
/>
<Typography
component="span"
color={theme.palette.primary.contrastTextTertiary}
opacity={0.8}
>
2025-03-17 01:16:42 +05:30
{t("uptimeCreate")}
2025-02-13 00:54:24 +00:00
</Typography>
</Stack>
<Stack>
<TextInput
type="text"
id="json-path"
label="JSON Path"
isOptional={true}
2025-03-25 20:54:50 -04:00
placeholder="data.status"
2025-02-13 00:54:24 +00:00
value={monitor.jsonPath}
onChange={(event) => handleChange(event, "jsonPath")}
error={errors["jsonPath"] ? true : false}
helperText={errors["jsonPath"]}
/>
<Typography
component="span"
color={theme.palette.primary.contrastTextTertiary}
opacity={0.8}
>
2025-03-17 01:16:42 +05:30
{t("uptimeCreateJsonPath")}&nbsp;
2025-02-24 14:33:25 -08:00
<Typography
component="a"
href="https://jmespath.org/"
target="_blank"
color="info"
>
2025-02-13 00:54:24 +00:00
jmespath.org
</Typography>
2025-03-17 01:16:42 +05:30
&nbsp;{t("uptimeCreateJsonPathQuery")}
2025-02-13 00:54:24 +00:00
</Typography>
</Stack>
</>
2025-02-24 14:33:25 -08:00
)}
</Stack>
</ConfigBox>
<Stack
direction="row"
justifyContent="flex-end"
>
2025-02-13 15:20:12 -08:00
<Button
variant="contained"
2025-01-14 08:09:03 -05:00
color="accent"
onClick={handleCreateMonitor}
2024-12-03 15:29:19 +08:00
disabled={!Object.values(errors).every((value) => value === undefined)}
loading={isLoading}
>
2025-03-17 01:16:42 +05:30
{t("createMonitor")}
2025-02-13 15:20:12 -08:00
</Button>
</Stack>
</Stack>
2025-03-01 22:36:07 -08:00
<NotificationIntegrationModal
2025-03-19 09:02:30 -07:00
open={isNotificationModalOpen}
onClose={() => setIsNotificationModalOpen(false)}
monitor={monitor}
setMonitor={setMonitor}
/>
</Box>
);
2024-06-18 22:39:58 +03:30
};
export default CreateMonitor;