add notifications to pagespeed

This commit is contained in:
Alex Holliday committed 2025-06-09 14:22:11 +08:00
1 parent 4c3ea2fd65
commit de673ea5d1
7 files changed
+87 -198

No files matched your search

@@ -34,8 +34,8 @@ const ConfigButton = ({ shouldRender = true, monitorId, path }) => {
ConfigButton.propTypes = { ConfigButton.propTypes = {
shouldRender: PropTypes.bool, shouldRender: PropTypes.bool,
monitorId: PropTypes.string.isRequired, monitorId: PropTypes.string,
path: PropTypes.string.isRequired, path: PropTypes.string,
}; };
export default ConfigButton; export default ConfigButton;
+64 -140
View File
@@ -1,6 +1,19 @@
// Components
import { Box, Stack, Tooltip, Typography, Button } from "@mui/material";
import ConfigBox from "../../../Components/ConfigBox";
import Select from "../../../Components/Inputs/Select";
import TextInput from "../../../Components/Inputs/TextInput";
import PauseCircleOutlineIcon from "@mui/icons-material/PauseCircleOutline";
import Breadcrumbs from "../../../Components/Breadcrumbs";
import PulseDot from "../../../Components/Animated/PulseDot";
import PlayCircleOutlineRoundedIcon from "@mui/icons-material/PlayCircleOutlineRounded";
import SkeletonLayout from "./skeleton";
import NotificationsConfig from "../../../Components/NotificationConfig";
import Dialog from "../../../Components/Dialog";
// Utils
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { Box, Stack, Tooltip, Typography, Button } from "@mui/material";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router"; import { useNavigate, useParams } from "react-router";
import { import {
@@ -12,41 +25,31 @@ import {
} from "../../../Features/PageSpeedMonitor/pageSpeedMonitorSlice"; } from "../../../Features/PageSpeedMonitor/pageSpeedMonitorSlice";
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 TextInput from "../../../Components/Inputs/TextInput";
import Select from "../../../Components/Inputs/Select";
import Checkbox from "../../../Components/Inputs/Checkbox";
import PauseCircleOutlineIcon from "@mui/icons-material/PauseCircleOutline";
import Breadcrumbs from "../../../Components/Breadcrumbs";
import PulseDot from "../../../Components/Animated/PulseDot";
import PlayCircleOutlineRoundedIcon from "@mui/icons-material/PlayCircleOutlineRounded";
import SkeletonLayout from "./skeleton";
import useUtils from "../../Uptime/Monitors/Hooks/useUtils"; import useUtils from "../../Uptime/Monitors/Hooks/useUtils";
import "./index.css"; import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications";
import Dialog from "../../../Components/Dialog";
const PageSpeedConfigure = () => { const PageSpeedConfigure = () => {
// Redux state
const { isLoading } = useSelector((state) => state.pageSpeedMonitors);
// Local state
const [monitor, setMonitor] = useState({});
const [errors, setErrors] = useState({});
const [buttonLoading, setButtonLoading] = useState(false);
const [isOpen, setIsOpen] = useState(false);
// Utils
const theme = useTheme(); const theme = useTheme();
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
const dispatch = useDispatch(); const dispatch = useDispatch();
const MS_PER_MINUTE = 60000; const MS_PER_MINUTE = 60000;
const { user } = useSelector((state) => state.auth);
const { isLoading } = useSelector((state) => state.pageSpeedMonitors);
const { monitorId } = useParams(); const { monitorId } = useParams();
const [monitor, setMonitor] = useState({});
const [errors, setErrors] = useState({});
const { statusColor, pagespeedStatusMsg, determineState } = useUtils(); const { statusColor, pagespeedStatusMsg, determineState } = useUtils();
const [buttonLoading, setButtonLoading] = useState(false);
const idMap = { const [notifications, notificationsAreLoading, notificationsError] =
"monitor-url": "url", useGetNotificationsByTeamId();
"monitor-name": "name",
"monitor-checks-http": "type",
"monitor-checks-ping": "type",
"notify-email-default": "notification-email",
};
const frequencies = [ const frequencies = [
{ _id: 3, name: "3 minutes" }, { _id: 3, name: "3 minutes" },
@@ -77,57 +80,29 @@ const PageSpeedConfigure = () => {
fetchMonitor(); fetchMonitor();
}, [dispatch, monitorId, navigate]); }, [dispatch, monitorId, navigate]);
const handleChange = (event, name) => { const onChange = (event) => {
let { value, id } = event.target; let { value, name } = event.target;
if (!name) name = idMap[id];
if (name.includes("notification-")) { if (name === "interval") {
name = name.replace("notification-", ""); value = value * MS_PER_MINUTE;
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 {
return {
...prev,
notifications: [
...notifs,
name === "email"
? { type: name, address: value }
: // TODO - phone number
{ type: name, phone: value },
],
};
}
});
} else {
if (name === "interval") {
value = value * MS_PER_MINUTE;
}
setMonitor((prev) => ({
...prev,
[name]: value,
}));
const validation = monitorValidation.validate(
{ [name]: value },
{ abortEarly: false }
);
setErrors((prev) => {
const updatedErrors = { ...prev };
if (validation.error) updatedErrors[name] = validation.error.details[0].message;
else delete updatedErrors[name];
return updatedErrors;
});
} }
setMonitor((prev) => ({
...prev,
[name]: value,
}));
const validation = monitorValidation.validate(
{ [name]: value },
{ abortEarly: false }
);
setErrors((prev) => {
const updatedErrors = { ...prev };
if (validation.error) updatedErrors[name] = validation.error.details[0].message;
else delete updatedErrors[name];
return updatedErrors;
});
}; };
const handlePause = async () => { const handlePause = async () => {
@@ -142,12 +117,11 @@ const PageSpeedConfigure = () => {
throw new Error(action.error.message); throw new Error(action.error.message);
} }
} catch (error) { } catch (error) {
logger.error("Error pausing monitor: " + monitorId);
createToast({ body: "Failed to pause monitor" }); createToast({ body: "Failed to pause monitor" });
} }
}; };
const handleSave = async (event) => { const onSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
const action = await dispatch(updatePageSpeed({ monitor: monitor })); const action = await dispatch(updatePageSpeed({ monitor: monitor }));
if (action.meta.requestStatus === "fulfilled") { if (action.meta.requestStatus === "fulfilled") {
@@ -158,7 +132,6 @@ const PageSpeedConfigure = () => {
} }
}; };
const [isOpen, setIsOpen] = useState(false);
const handleRemove = async (event) => { const handleRemove = async (event) => {
event.preventDefault(); event.preventDefault();
setButtonLoading(true); setButtonLoading(true);
@@ -191,7 +164,7 @@ const PageSpeedConfigure = () => {
component="form" component="form"
noValidate noValidate
spellCheck="false" spellCheck="false"
onSubmit={handleSave} onSubmit={onSubmit}
flex={1} flex={1}
gap={theme.spacing(10)} gap={theme.spacing(10)}
> >
@@ -329,24 +302,24 @@ const PageSpeedConfigure = () => {
}} }}
> >
<TextInput <TextInput
name="url"
type="url" type="url"
id="monitor-url"
label={t("url")} label={t("url")}
placeholder="random.website.com" placeholder="random.website.com"
value={monitor?.url || ""} value={monitor?.url || ""}
onChange={handleChange} onChange={onChange}
error={errors.url ? true : false} error={errors.url ? true : false}
helperText={errors.url} helperText={errors.url}
disabled={true} disabled={true}
/> />
<TextInput <TextInput
name="name"
type="text" type="text"
id="monitor-name"
label={t("monitorDisplayName")} label={t("monitorDisplayName")}
placeholder="Example monitor" placeholder="Example monitor"
isOptional={true} isOptional={true}
value={monitor?.name || ""} value={monitor?.name || ""}
onChange={handleChange} onChange={onChange}
error={errors.name ? true : false} error={errors.name ? true : false}
helperText={errors.name} helperText={errors.name}
/> />
@@ -354,64 +327,16 @@ const PageSpeedConfigure = () => {
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography <Typography component="h2">{t("notificationConfig.title")}</Typography>
component="h2"
variant="h2"
>
{t("distributedUptimeCreateIncidentNotification")}
</Typography>
<Typography component="p"> <Typography component="p">
{t("distributedUptimeCreateIncidentDescription")} {t("notificationConfig.description")}
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(6)}> <NotificationsConfig
<Typography component="p">{t("whenNewIncident")}</Typography> notifications={notifications}
{/* Future Feature: Notify via SMS */} setMonitor={setMonitor}
{/* <Checkbox setNotifications={monitor.notifications}
id="notify-sms" />
label={t("notifySMS")}
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)}
/>
{/* Future Feature: Notify via Email */}
{/* <Checkbox
id="notify-email"
label={t("notifyEmails")}
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)}>{t("seperateEmails")}</Typography>
</Box>
) : (
""
)}
</Stack>
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
<Box> <Box>
@@ -424,11 +349,11 @@ const PageSpeedConfigure = () => {
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
<Select <Select
id="monitor-frequency" name="interval"
label={t("checkFrequency")} label={t("checkFrequency")}
items={frequencies} items={frequencies}
value={monitor?.interval / MS_PER_MINUTE || 3} value={monitor?.interval / MS_PER_MINUTE || 3}
onChange={(event) => handleChange(event, "interval")} onChange={onChange}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
@@ -442,7 +367,6 @@ const PageSpeedConfigure = () => {
type="submit" type="submit"
variant="contained" variant="contained"
color="accent" color="accent"
onClick={handleSave}
sx={{ px: theme.spacing(12) }} sx={{ px: theme.spacing(12) }}
> >
{t("settingsSave")} {t("settingsSave")}
+12 -47
View File
@@ -2,7 +2,6 @@
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useState } from "react"; import { useState } from "react";
import { useSelector, useDispatch } from "react-redux"; import { useSelector, useDispatch } from "react-redux";
// Utility and Network // Utility and Network
import { monitorValidation } from "../../../Validation/validation"; import { monitorValidation } from "../../../Validation/validation";
import { import {
@@ -11,6 +10,7 @@ import {
} from "../../../Features/PageSpeedMonitor/pageSpeedMonitorSlice"; } from "../../../Features/PageSpeedMonitor/pageSpeedMonitorSlice";
import { parseDomainName } from "../../../Utils/monitorUtils"; import { parseDomainName } from "../../../Utils/monitorUtils";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications";
// MUI // MUI
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
@@ -23,8 +23,8 @@ import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments";
import ConfigBox from "../../../Components/ConfigBox"; import ConfigBox from "../../../Components/ConfigBox";
import { createToast } from "../../../Utils/toastUtils"; import { createToast } from "../../../Utils/toastUtils";
import Radio from "../../../Components/Inputs/Radio"; import Radio from "../../../Components/Inputs/Radio";
import Checkbox from "../../../Components/Inputs/Checkbox";
import Select from "../../../Components/Inputs/Select"; import Select from "../../../Components/Inputs/Select";
import NotificationsConfig from "../../../Components/NotificationConfig";
const MS_PER_MINUTE = 60000; const MS_PER_MINUTE = 60000;
@@ -57,6 +57,7 @@ const CreatePageSpeed = () => {
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const { user } = useSelector((state) => state.auth); const { user } = useSelector((state) => state.auth);
const { isLoading } = useSelector((state) => state.pageSpeedMonitors); const { isLoading } = useSelector((state) => state.pageSpeedMonitors);
const [notifications, notificationsAreLoading, error] = useGetNotificationsByTeamId();
// Setup // Setup
const dispatch = useDispatch(); const dispatch = useDispatch();
@@ -64,7 +65,7 @@ const CreatePageSpeed = () => {
const theme = useTheme(); const theme = useTheme();
// Handlers // Handlers
const handleCreateMonitor = async (event) => { const onSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
let form = { let form = {
url: `http${https ? "s" : ""}://` + monitor.url, url: `http${https ? "s" : ""}://` + monitor.url,
@@ -134,32 +135,6 @@ const CreatePageSpeed = () => {
})); }));
}; };
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;
}
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 });
}
setMonitor((prev) => ({
...prev,
notifications,
}));
};
const handleBlur = (event) => { const handleBlur = (event) => {
const { name } = event.target; const { name } = event.target;
if (name === "url") { if (name === "url") {
@@ -189,7 +164,7 @@ const CreatePageSpeed = () => {
<Stack <Stack
component="form" component="form"
className="create-monitor-form" className="create-monitor-form"
onSubmit={handleCreateMonitor} onSubmit={onSubmit}
noValidate noValidate
spellCheck="false" spellCheck="false"
gap={theme.spacing(12)} gap={theme.spacing(12)}
@@ -312,24 +287,14 @@ const CreatePageSpeed = () => {
component="h2" component="h2"
variant="h2" variant="h2"
> >
{t("distributedUptimeCreateIncidentNotification")} {t("notificationConfig.title")}
</Typography>
<Typography component="p">
{t("distributedUptimeCreateIncidentDescription")}
</Typography> </Typography>
<Typography component="p">{t("notificationConfig.description")}</Typography>
</Box> </Box>
<Stack gap={theme.spacing(6)}> <NotificationsConfig
<Typography component="p">{t("whenNewIncident")}</Typography> notifications={notifications}
<Checkbox setMonitor={setMonitor}
id="notify-email-default" />
label={`Notify via email (to ${user.email})`}
isChecked={monitor.notifications.some(
(notification) => notification.type === "email"
)}
value={user?.email}
onChange={(event) => handleNotifications(event, "email")}
/>
</Stack>
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
<Box> <Box>
@@ -356,9 +321,9 @@ const CreatePageSpeed = () => {
justifyContent="flex-end" justifyContent="flex-end"
> >
<Button <Button
type="submit"
variant="contained" variant="contained"
color="accent" color="accent"
onClick={handleCreateMonitor}
disabled={!Object.values(errors).every((value) => value === undefined)} disabled={!Object.values(errors).every((value) => value === undefined)}
loading={isLoading} loading={isLoading}
> >
+2 -4
View File
@@ -383,10 +383,8 @@ const Configure = () => {
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography component="h2">Notifications</Typography> <Typography component="h2">{t("notificationConfig.title")}</Typography>
<Typography component="p"> <Typography component="p">{t("notificationConfig.description")}</Typography>
Select the notifications you want to send out
</Typography>
</Box> </Box>
<NotificationsConfig <NotificationsConfig
notifications={notifications} notifications={notifications}
+2 -4
View File
@@ -349,10 +349,8 @@ const CreateMonitor = () => {
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography component="h2">Notifications</Typography> <Typography component="h2">{t("notificationConfig.title")}</Typography>
<Typography component="p"> <Typography component="p">{t("notificationConfig.description")}</Typography>
Select the notifications you want to send out
</Typography>
</Box> </Box>
<NotificationsConfig <NotificationsConfig
notifications={notifications} notifications={notifications}
+4
View File
@@ -166,6 +166,10 @@
"integrationKeyPlaceholder": "1234567890" "integrationKeyPlaceholder": "1234567890"
} }
}, },
"notificationConfig": {
"title": "Notifications",
"description": "Select the notifications channels you want to use"
},
"notifications": { "notifications": {
"fallback": { "fallback": {
"title": "Notification", "title": "Notification",
+1 -1
View File
@@ -42,7 +42,7 @@ const MonitorSchema = mongoose.Schema(
}, },
matchMethod: { matchMethod: {
type: String, type: String,
enum: ["equal", "include", "regex"], enum: ["equal", "include", "regex", ""],
}, },
url: { url: {
type: String, type: String,