add notificaions channel to Uptime Configure

This commit is contained in:
Alex Holliday committed 2025-06-09 12:56:05 +08:00
1 parent e36abfa9a6
commit 04ab4e23db
1 file changed
+157 -238
+157 -238
View File
@@ -1,7 +1,7 @@
import { useNavigate, useParams } from "react-router"; import { useNavigate, useParams } from "react-router";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react"; import { useState, useEffect } from "react";
import { import {
Box, Box,
Stack, Stack,
@@ -13,31 +13,26 @@ import {
} from "@mui/material"; } from "@mui/material";
import { monitorValidation } from "../../../Validation/validation"; import { monitorValidation } from "../../../Validation/validation";
import { createToast } from "../../../Utils/toastUtils"; import { createToast } from "../../../Utils/toastUtils";
import { logger } from "../../../Utils/Logger";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import ConfigBox from "../../../Components/ConfigBox"; import ConfigBox from "../../../Components/ConfigBox";
import { import {
updateUptimeMonitor, updateUptimeMonitor,
pauseUptimeMonitor,
getUptimeMonitorById,
deleteUptimeMonitor, deleteUptimeMonitor,
} from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
import TextInput from "../../../Components/Inputs/TextInput"; import TextInput from "../../../Components/Inputs/TextInput";
import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments"; import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments";
import PauseIcon from "../../../assets/icons/pause-icon.svg?react";
import ResumeIcon from "../../../assets/icons/resume-icon.svg?react";
import Select from "../../../Components/Inputs/Select"; import Select from "../../../Components/Inputs/Select";
import Checkbox from "../../../Components/Inputs/Checkbox";
import Breadcrumbs from "../../../Components/Breadcrumbs"; import Breadcrumbs from "../../../Components/Breadcrumbs";
import PulseDot from "../../../Components/Animated/PulseDot"; import PulseDot from "../../../Components/Animated/PulseDot";
import SkeletonLayout from "./skeleton";
import "./index.css"; import "./index.css";
import Dialog from "../../../Components/Dialog"; import Dialog from "../../../Components/Dialog";
import NotificationIntegrationModal from "../../../Components/NotificationIntegrationModal/Components/NotificationIntegrationModal";
import { usePauseMonitor } from "../../../Hooks/useMonitorControls"; import { usePauseMonitor } from "../../../Hooks/useMonitorControls";
import PauseOutlinedIcon from "@mui/icons-material/PauseOutlined"; import PauseOutlinedIcon from "@mui/icons-material/PauseOutlined";
import PlayArrowOutlinedIcon from "@mui/icons-material/PlayArrowOutlined"; import PlayArrowOutlinedIcon from "@mui/icons-material/PlayArrowOutlined";
import { useMonitorUtils } from "../../../Hooks/useMonitorUtils"; import { useMonitorUtils } from "../../../Hooks/useMonitorUtils";
import { useFetchUptimeMonitorById } from "../../../Hooks/useFetchUptimeMonitorById";
import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications";
import NotificationsConfig from "../../../Components/NotificationConfig";
/** /**
* Parses a URL string and returns a URL object. * Parses a URL string and returns a URL object.
@@ -58,22 +53,41 @@ const parseUrl = (url) => {
* @component * @component
*/ */
const Configure = () => { const Configure = () => {
const { monitorId } = useParams();
// Local state
const [form, setForm] = useState({
ignoreTlsErrors: false,
interval: 60000,
matchMethod: "equal",
expectedValue: "",
jsonPath: "",
notifications: [],
port: "",
type: "http",
});
const [useAdvancedMatching, setUseAdvancedMatching] = useState(false);
const [updateTrigger, setUpdateTrigger] = useState(false);
const [isOpen, setIsOpen] = useState(false);
const [errors, setErrors] = useState({});
const triggerUpdate = () => {
setUpdateTrigger(!updateTrigger);
};
// Network
const [monitor, isLoading, error] = useFetchUptimeMonitorById(monitorId, updateTrigger);
const [notifications, notificationsAreLoading, notificationsError] =
useGetNotificationsByTeamId();
const [pauseMonitor, isPausing, pauseError] = usePauseMonitor({
monitorId: monitor?._id,
triggerUpdate,
});
const MS_PER_MINUTE = 60000; const MS_PER_MINUTE = 60000;
const navigate = useNavigate(); const navigate = useNavigate();
const theme = useTheme(); const theme = useTheme();
const dispatch = useDispatch(); const dispatch = useDispatch();
const { user } = useSelector((state) => state.auth);
const { isLoading } = useSelector((state) => state.uptimeMonitors);
const [monitor, setMonitor] = useState({});
const [errors, setErrors] = useState({});
const { monitorId } = useParams();
const idMap = {
"monitor-url": "url",
"monitor-name": "name",
"monitor-checks-http": "type",
"monitor-checks-ping": "type",
"notify-email-default": "notification-email",
};
const matchMethodOptions = [ const matchMethodOptions = [
{ _id: "equal", name: "Equal" }, { _id: "equal", name: "Equal" },
@@ -81,79 +95,49 @@ const Configure = () => {
{ _id: "regex", name: "Regex" }, { _id: "regex", name: "Regex" },
]; ];
const frequencies = [
{ _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 expectedValuePlaceholders = { const expectedValuePlaceholders = {
regex: "^(success|ok)$", regex: "^(success|ok)$",
equal: "success", equal: "success",
include: "ok", include: "ok",
}; };
const [trigger, setTrigger] = useState(false); // Handlers
const triggerUpdate = () => { const handlePause = async () => {
setTrigger(!trigger); const res = await pauseMonitor();
}; if (typeof res !== "undefined") {
const [pauseMonitor, isPausing, error] = usePauseMonitor({ triggerUpdate();
monitorId: monitor?._id,
triggerUpdate,
});
useEffect(() => {
const fetchMonitor = async () => {
try {
const action = await dispatch(getUptimeMonitorById({ monitorId }));
if (getUptimeMonitorById.fulfilled.match(action)) {
const monitor = action.payload.data;
setMonitor(monitor);
} else if (getUptimeMonitorById.rejected.match(action)) {
throw new Error(action.error.message);
}
} catch (error) {
logger.error("Error fetching monitor of id: " + monitorId);
navigate("/not-found", { replace: true });
} }
}; };
fetchMonitor();
}, [monitorId, navigate, trigger]);
const handleChange = (event, name) => { const handleRemove = async (event) => {
let { checked, value, id } = event.target; event.preventDefault();
if (!name) name = idMap[id]; const action = await dispatch(deleteUptimeMonitor({ monitor }));
if (action.meta.requestStatus === "fulfilled") {
if (name.includes("notification-")) { navigate("/uptime");
name = name.replace("notification-", "");
let hasNotif = monitor.notifications.some(
(notification) => notification.type === name
);
setMonitor((prev) => {
const notifs = [...prev.notifications];
if (hasNotif) {
return {
...prev,
notifications: notifs.filter((notif) => notif.type !== name),
};
} else { } else {
return { createToast({ body: "Failed to delete monitor." });
...prev, }
notifications: [
...notifs,
name === "email"
? { type: name, address: value }
: // TODO - phone number
{ type: name, phone: value },
],
}; };
}
}); const onChange = (event) => {
} else { let { name, value, checked } = event.target;
if (name === "interval") {
value = value * MS_PER_MINUTE;
}
if (name === "ignoreTlsErrors") { if (name === "ignoreTlsErrors") {
value = checked; value = checked;
} }
setMonitor((prev) => ({
...prev, if (name === "interval") {
[name]: value, value = value * MS_PER_MINUTE;
})); }
setForm({ ...form, [name]: value });
const validation = monitorValidation.validate( const validation = monitorValidation.validate(
{ [name]: value }, { [name]: value },
@@ -167,12 +151,48 @@ const Configure = () => {
else delete updatedErrors[name]; else delete updatedErrors[name];
return updatedErrors; return updatedErrors;
}); });
}
}; };
const handleSubmit = async (event) => { const onSubmit = async (e) => {
event.preventDefault(); e.preventDefault();
const action = await dispatch(updateUptimeMonitor({ monitor: monitor }));
const toSubmit = {
_id: form._id,
url: form.url,
name: form.name,
type: form.type,
matchMethod: form.matchMethod,
expectedValue: form.expectedValue,
jsonPath: form.jsonPath,
interval: form.interval,
teamId: form.teamId,
userId: form.userId,
port: form.port,
ignoreTlsErrors: form.ignoreTlsErrors,
};
if (!useAdvancedMatching) {
toSubmit.matchMethod = "";
toSubmit.expectedValue = "";
toSubmit.jsonPath = "";
}
const validation = monitorValidation.validate(toSubmit, {
abortEarly: false,
});
if (validation.error) {
const newErrors = {};
error.details.forEach((err) => {
newErrors[err.path[0]] = err.message;
});
setErrors(newErrors);
createToast({ body: "Please check the form for errors." });
return;
}
toSubmit.notifications = form.notifications;
const action = await dispatch(updateUptimeMonitor({ monitor: toSubmit }));
if (action.meta.requestStatus === "fulfilled") { if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Monitor updated successfully!" }); createToast({ body: "Monitor updated successfully!" });
} else { } else {
@@ -180,53 +200,27 @@ const Configure = () => {
} }
}; };
const [isOpen, setIsOpen] = useState(false); // Effects
const handleRemove = async (event) => { useEffect(() => {
event.preventDefault(); if (monitor?.matchMethod) {
const action = await dispatch(deleteUptimeMonitor({ monitor })); setUseAdvancedMatching(true);
if (action.meta.requestStatus === "fulfilled") {
navigate("/uptime");
} else {
createToast({ body: "Failed to delete monitor." });
} }
};
const frequencies = [ setForm({
{ _id: 1, name: "1 minute" }, ...monitor,
{ _id: 2, name: "2 minutes" }, });
{ _id: 3, name: "3 minutes" }, }, [monitor, notifications]);
{ _id: 4, name: "4 minutes" },
{ _id: 5, name: "5 minutes" },
];
// Parse the URL // Parse the URL
const parsedUrl = parseUrl(monitor?.url); const parsedUrl = parseUrl(monitor?.url);
const protocol = parsedUrl?.protocol?.replace(":", "") || ""; const protocol = parsedUrl?.protocol?.replace(":", "") || "";
// Notification modal state
const [isNotificationModalOpen, setIsNotificationModalOpen] = useState(false);
const handleOpenNotificationModal = () => {
setIsNotificationModalOpen(true);
};
const handleClosenNotificationModal = () => {
setIsNotificationModalOpen(false);
};
const { determineState, statusColor } = useMonitorUtils(); const { determineState, statusColor } = useMonitorUtils();
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<Stack <Stack gap={theme.spacing(10)}>
className="configure-monitor"
gap={theme.spacing(10)}
>
{Object.keys(monitor).length === 0 ? (
<SkeletonLayout />
) : (
<>
<Breadcrumbs <Breadcrumbs
list={[ list={[
{ name: "uptime", path: "/uptime" }, { name: "uptime", path: "/uptime" },
@@ -236,6 +230,7 @@ const Configure = () => {
/> />
<Stack <Stack
component="form" component="form"
onSubmit={onSubmit}
noValidate noValidate
spellCheck="false" spellCheck="false"
gap={theme.spacing(12)} gap={theme.spacing(12)}
@@ -243,14 +238,14 @@ const Configure = () => {
> >
<Stack <Stack
direction="row" direction="row"
gap={theme.spacing(2)} gap={theme.spacing(12)}
> >
<Box> <Box>
<Typography <Typography
component="h1" component="h1"
variant="monitorName" variant="monitorName"
> >
{monitor.name} {form.name}
</Typography> </Typography>
<Stack <Stack
direction="row" direction="row"
@@ -259,7 +254,7 @@ const Configure = () => {
gap={theme.spacing(2)} gap={theme.spacing(2)}
> >
<Tooltip <Tooltip
title={t(`statusMsg.${[determineState(monitor)]}`)} title={t(`statusMsg.${[determineState(form)]}`)}
disableInteractive disableInteractive
slotProps={{ slotProps={{
popper: { popper: {
@@ -275,14 +270,14 @@ const Configure = () => {
}} }}
> >
<Box> <Box>
<PulseDot color={statusColor[determineState(monitor)]} /> <PulseDot color={statusColor[determineState(form)]} />
</Box> </Box>
</Tooltip> </Tooltip>
<Typography <Typography
component="h2" component="h2"
variant="monitorUrl" variant="monitorUrl"
> >
{monitor.url?.replace(/^https?:\/\//, "") || "..."} {form.url?.replace(/^https?:\/\//, "") || "..."}
</Typography> </Typography>
<Typography <Typography
position="relative" position="relative"
@@ -322,13 +317,11 @@ const Configure = () => {
color="secondary" color="secondary"
loading={isPausing} loading={isPausing}
startIcon={ startIcon={
monitor?.isActive ? <PauseOutlinedIcon /> : <PlayArrowOutlinedIcon /> form?.isActive ? <PauseOutlinedIcon /> : <PlayArrowOutlinedIcon />
} }
onClick={() => { onClick={handlePause}
pauseMonitor();
}}
> >
{monitor?.isActive ? t("pause") : t("resume")} {form?.isActive ? t("pause") : t("resume")}
</Button> </Button>
<Button <Button
loading={isLoading} loading={isLoading}
@@ -349,44 +342,40 @@ const Configure = () => {
> >
{t("settingsGeneralSettings")} {t("settingsGeneralSettings")}
</Typography> </Typography>
<Typography component="p"> <Typography component="p">{t("distributedUptimeCreateSelectURL")}</Typography>
{t("distributedUptimeCreateSelectURL")}
</Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
<TextInput <TextInput
type={monitor?.type === "http" ? "url" : "text"} type={form?.type === "http" ? "url" : "text"}
https={protocol === "https"} https={protocol === "https"}
startAdornment={ startAdornment={
monitor?.type === "http" && ( form?.type === "http" && <HttpAdornment https={protocol === "https"} />
<HttpAdornment https={protocol === "https"} />
)
} }
id="monitor-url" id="monitor-url"
label={t("urlMonitor")} label={t("urlMonitor")}
placeholder="google.com" placeholder="google.com"
value={parsedUrl?.host || monitor?.url || ""} value={parsedUrl?.host || form?.url || ""}
disabled={true} disabled={true}
/> />
<TextInput <TextInput
name="port"
type="number" type="number"
id="monitor-port"
label={t("portToMonitor")} label={t("portToMonitor")}
placeholder="5173" placeholder="5173"
value={monitor.port || ""} value={form.port || ""}
onChange={(event) => handleChange(event, "port")} onChange={onChange}
error={errors["port"] ? true : false} error={errors["port"] ? true : false}
helperText={errors["port"]} helperText={errors["port"]}
hidden={monitor.type !== "port"} hidden={form.type !== "port"}
/> />
<TextInput <TextInput
name="name"
type="text" type="text"
id="monitor-name"
label={t("displayName")} label={t("displayName")}
isOptional={true} isOptional={true}
placeholder="Google" placeholder="Google"
value={monitor?.name || ""} value={form?.name || ""}
onChange={handleChange} onChange={onChange}
error={errors["name"] ? true : false} error={errors["name"] ? true : false}
helperText={errors["name"]} helperText={errors["name"]}
/> />
@@ -394,74 +383,16 @@ const Configure = () => {
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography <Typography component="h2">Notifications</Typography>
component="h2"
variant="h2"
>
{t("distributedUptimeCreateIncidentNotification")}
</Typography>
<Typography component="p"> <Typography component="p">
{t("distributedUptimeCreateIncidentDescription")} Select the notifications you want to send out
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(6)}> <NotificationsConfig
<Typography component="p">{t("whenNewIncident")}</Typography> notifications={notifications}
{/* {Leaving components commented for future funtionality implimentation} */} setMonitor={setForm}
{/* <Checkbox setNotifications={form.notifications}
id="notify-sms"
label="Notify via SMS (coming soon)"
isChecked={false}
value=""
onChange={() => logger.warn("disabled")}
isDisabled={true}
/> */}
<Checkbox
id="notify-email-default"
label={`Notify via email (to ${user.email})`}
isChecked={
monitor?.notifications?.some(
(notification) => notification.type === "email"
) || false
}
value={user?.email}
onChange={(event) => handleChange(event)}
/> />
<Box mt={theme.spacing(2)}>
<Button
variant="contained"
color="accent"
onClick={handleOpenNotificationModal}
>
{t("notifications.integrationButton")}
</Button>
</Box>
{/* <Checkbox
id="notify-email"
label="Also notify via email to multiple addresses (coming soon)"
isChecked={false}
value=""
onChange={() => logger.warn("disabled")}
isDisabled={true}
/> */}
{/* {monitor?.notifications?.some(
(notification) => notification.type === "emails"
) ? (
<Box mx={theme.spacing(16)}>
<TextInput
id="notify-email-list"
type="text"
placeholder="name@gmail.com"
value=""
onChange={() => logger.warn("disabled")}
/>
<Typography mt={theme.spacing(4)}>
You can separate multiple emails with a comma
</Typography>
</Box>
) : (
""
)} */}
</Stack>
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
<Box> <Box>
@@ -478,9 +409,9 @@ const Configure = () => {
sx={{ marginLeft: 0 }} sx={{ marginLeft: 0 }}
control={ control={
<Switch <Switch
name="ignore-error" name="ignoreTlsErrors"
checked={monitor.ignoreTlsErrors} checked={form.ignoreTlsErrors ?? false}
onChange={(event) => handleChange(event, "ignoreTlsErrors")} onChange={onChange}
sx={{ mr: theme.spacing(2) }} sx={{ mr: theme.spacing(2) }}
/> />
} }
@@ -499,32 +430,30 @@ const Configure = () => {
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
<Select <Select
id="monitor-interval-configure" name="interval"
label={t("checkFrequency")} label={t("checkFrequency")}
value={monitor?.interval / MS_PER_MINUTE || 1} value={form?.interval / MS_PER_MINUTE || 1}
onChange={(event) => handleChange(event, "interval")} onChange={onChange}
items={frequencies} items={frequencies}
/> />
{monitor.type === "http" && ( {form.type === "http" && (
<> <>
<Select <Select
id="match-method" name="matchMethod"
label={t("matchMethod")} label={t("matchMethod")}
value={monitor.matchMethod || "equal"} value={form.matchMethod || "equal"}
onChange={(event) => handleChange(event, "matchMethod")} onChange={onChange}
items={matchMethodOptions} items={matchMethodOptions}
/> />
<Stack> <Stack>
<TextInput <TextInput
type="text" type="text"
id="expected-value" name="expectedValue"
label={t("expectedValue")} label={t("expectedValue")}
isOptional={true} isOptional={true}
placeholder={ placeholder={expectedValuePlaceholders[form.matchMethod || "equal"]}
expectedValuePlaceholders[monitor.matchMethod || "equal"] value={form.expectedValue}
} onChange={onChange}
value={monitor.expectedValue}
onChange={(event) => handleChange(event, "expectedValue")}
error={errors["expectedValue"] ? true : false} error={errors["expectedValue"] ? true : false}
helperText={errors["expectedValue"]} helperText={errors["expectedValue"]}
/> />
@@ -538,13 +467,13 @@ const Configure = () => {
</Stack> </Stack>
<Stack> <Stack>
<TextInput <TextInput
name="jsonPath"
type="text" type="text"
id="json-path"
label="JSON Path" label="JSON Path"
isOptional={true} isOptional={true}
placeholder="data.status" placeholder="data.status"
value={monitor.jsonPath} value={form.jsonPath}
onChange={(event) => handleChange(event, "jsonPath")} onChange={onChange}
error={errors["jsonPath"] ? true : false} error={errors["jsonPath"] ? true : false}
helperText={errors["jsonPath"]} helperText={errors["jsonPath"]}
/> />
@@ -575,19 +504,16 @@ const Configure = () => {
mt="auto" mt="auto"
> >
<Button <Button
type="submit"
variant="contained" variant="contained"
color="accent" color="accent"
loading={isLoading} loading={isLoading}
sx={{ px: theme.spacing(12) }} sx={{ px: theme.spacing(12) }}
onClick={handleSubmit}
> >
{t("settingsSave")} {t("settingsSave")}
</Button> </Button>
</Stack> </Stack>
</Stack> </Stack>
</>
)}
<Dialog <Dialog
open={isOpen} open={isOpen}
theme={theme} theme={theme}
@@ -598,13 +524,6 @@ const Configure = () => {
onConfirm={handleRemove} onConfirm={handleRemove}
isLoading={isLoading} isLoading={isLoading}
/> />
<NotificationIntegrationModal
open={isNotificationModalOpen}
onClose={handleClosenNotificationModal}
monitor={monitor}
setMonitor={setMonitor}
/>
</Stack> </Stack>
); );
}; };