From 50986d44938243351e98214371cad3b5cff18cbc Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Thu, 12 Jun 2025 12:44:46 +0800 Subject: [PATCH] use hooks --- .../src/Components/Inputs/Checkbox/index.jsx | 2 +- .../MonitorDetailsControlHeader/index.jsx | 13 +- .../MonitorDetailsControlHeader/status.jsx | 5 +- .../Components/MonitorStatusHeader/index.jsx | 4 +- client/src/Components/StatBox/index.jsx | 4 +- .../src/Pages/Infrastructure/Create/index.jsx | 37 ++---- .../Details/Components/StatusBoxes/index.jsx | 4 +- .../Pages/Infrastructure/Details/index.jsx | 4 +- .../Components/MonitorsTable/index.jsx | 4 +- .../Pages/Infrastructure/Monitors/index.jsx | 12 +- .../src/Pages/PageSpeed/Configure/index.jsx | 91 ++++---------- client/src/Pages/PageSpeed/Create/index.jsx | 61 +++------ client/src/Pages/PageSpeed/Details/index.jsx | 10 +- .../Monitors/Components/Card/index.jsx | 8 +- client/src/Pages/PageSpeed/Monitors/index.jsx | 17 ++- .../Status/Components/MonitorsList/index.jsx | 4 +- client/src/Pages/Uptime/Configure/index.jsx | 116 +++++++++--------- client/src/Pages/Uptime/Create/index.jsx | 47 ++++--- .../Components/UptimeStatusBoxes/index.jsx | 4 +- client/src/Pages/Uptime/Details/index.jsx | 13 +- .../Components/UptimeDataTable/index.jsx | 4 +- client/src/Pages/Uptime/Monitors/index.jsx | 8 +- client/src/locales/en.json | 1 + 23 files changed, 204 insertions(+), 269 deletions(-) diff --git a/client/src/Components/Inputs/Checkbox/index.jsx b/client/src/Components/Inputs/Checkbox/index.jsx index 58b83c7c7..1497c44fb 100644 --- a/client/src/Components/Inputs/Checkbox/index.jsx +++ b/client/src/Components/Inputs/Checkbox/index.jsx @@ -105,7 +105,7 @@ const Checkbox = ({ }; Checkbox.propTypes = { - id: PropTypes.string.isRequired, + id: PropTypes.string, name: PropTypes.string, label: PropTypes.oneOfType([PropTypes.string, PropTypes.node]).isRequired, size: PropTypes.oneOf(["small", "medium", "large"]), diff --git a/client/src/Components/MonitorDetailsControlHeader/index.jsx b/client/src/Components/MonitorDetailsControlHeader/index.jsx index aa9ef91b9..8c9f845e9 100644 --- a/client/src/Components/MonitorDetailsControlHeader/index.jsx +++ b/client/src/Components/MonitorDetailsControlHeader/index.jsx @@ -11,10 +11,9 @@ import EmailIcon from "@mui/icons-material/Email"; import PropTypes from "prop-types"; import { useNavigate } from "react-router-dom"; import { useTheme } from "@mui/material/styles"; -import { usePauseMonitor } from "../../Hooks/useMonitorControls"; +import { usePauseMonitor } from "../../Hooks/monitorHooks"; import { useSendTestEmail } from "../../Hooks/useSendTestEmail"; import { useTranslation } from "react-i18next"; - /** * MonitorDetailsControlHeader component displays the control header for monitor details. * It includes status display, pause/resume button, and a configure button for admins. @@ -38,10 +37,7 @@ const MonitorDetailsControlHeader = ({ const navigate = useNavigate(); const theme = useTheme(); const { t } = useTranslation(); - const [pauseMonitor, isPausing, error] = usePauseMonitor({ - monitorId: monitor?._id, - triggerUpdate, - }); + const [pauseMonitor, isPausing, error] = usePauseMonitor(); const [isSending, emailError, sendTestEmail] = useSendTestEmail(); @@ -88,7 +84,10 @@ const MonitorDetailsControlHeader = ({ monitor?.isActive ? : } onClick={() => { - pauseMonitor(); + pauseMonitor({ + monitorId: monitor?._id, + triggerUpdate, + }); }} > {monitor?.isActive ? "Pause" : "Resume"} diff --git a/client/src/Components/MonitorDetailsControlHeader/status.jsx b/client/src/Components/MonitorDetailsControlHeader/status.jsx index 3d6e62c60..fdfb955f4 100644 --- a/client/src/Components/MonitorDetailsControlHeader/status.jsx +++ b/client/src/Components/MonitorDetailsControlHeader/status.jsx @@ -7,8 +7,7 @@ import Dot from "../../Components/Dot"; import { formatDurationRounded } from "../../Utils/timeUtils"; import PropTypes from "prop-types"; import { useTheme } from "@emotion/react"; -import useUtils from "../../Pages/Uptime/Monitors/Hooks/useUtils"; - +import { useMonitorUtils } from "../../Hooks/useMonitorUtils"; /** * Status component displays the status information of a monitor. * It includes the monitor's name, URL, and check interval. @@ -23,7 +22,7 @@ import useUtils from "../../Pages/Uptime/Monitors/Hooks/useUtils"; */ const Status = ({ monitor }) => { const theme = useTheme(); - const { statusColor, determineState } = useUtils(); + const { statusColor, determineState } = useMonitorUtils(); return ( diff --git a/client/src/Components/MonitorStatusHeader/index.jsx b/client/src/Components/MonitorStatusHeader/index.jsx index 7ea95410b..a81131152 100644 --- a/client/src/Components/MonitorStatusHeader/index.jsx +++ b/client/src/Components/MonitorStatusHeader/index.jsx @@ -2,7 +2,7 @@ import { Stack, Typography } from "@mui/material"; import PulseDot from "../Animated/PulseDot"; import Dot from "../Dot"; import { useTheme } from "@emotion/react"; -import useUtils from "../../Pages/Uptime/Monitors/Hooks/useUtils"; +import { useMonitorUtils } from "../../Hooks/useMonitorUtils"; import { formatDurationRounded } from "../../Utils/timeUtils"; import ConfigButton from "./ConfigButton"; import SkeletonLayout from "./skeleton"; @@ -12,7 +12,7 @@ import { useTranslation } from "react-i18next"; const MonitorStatusHeader = ({ path, isLoading = false, isAdmin, monitor }) => { const theme = useTheme(); const { t } = useTranslation(); - const { statusColor, determineState } = useUtils(); + const { statusColor, determineState } = useMonitorUtils(); if (isLoading) { return ; } diff --git a/client/src/Components/StatBox/index.jsx b/client/src/Components/StatBox/index.jsx index 673736ea9..93fa46c2b 100644 --- a/client/src/Components/StatBox/index.jsx +++ b/client/src/Components/StatBox/index.jsx @@ -2,7 +2,7 @@ import { Stack, Typography } from "@mui/material"; import Image from "../Image"; import { useTheme } from "@mui/material/styles"; import PropTypes from "prop-types"; -import useUtils from "../../Pages/Uptime/Monitors/Hooks/useUtils"; +import { useMonitorUtils } from "../../Hooks/useMonitorUtils"; /** * StatBox Component @@ -41,7 +41,7 @@ const StatBox = ({ sx, }) => { const theme = useTheme(); - const { statusToTheme } = useUtils(); + const { statusToTheme } = useMonitorUtils(); const themeColor = statusToTheme[status]; const statusBoxStyles = gradient diff --git a/client/src/Pages/Infrastructure/Create/index.jsx b/client/src/Pages/Infrastructure/Create/index.jsx index 9425b7429..fa63dd4dc 100644 --- a/client/src/Pages/Infrastructure/Create/index.jsx +++ b/client/src/Pages/Infrastructure/Create/index.jsx @@ -1,20 +1,17 @@ // React, Redux, Router import { useTheme } from "@emotion/react"; -import { useNavigate, useParams } from "react-router-dom"; +import { useParams } from "react-router-dom"; import { useState, useEffect } from "react"; -import { useSelector, useDispatch } from "react-redux"; +import { useSelector } from "react-redux"; // Utility and Network import { infrastructureMonitorValidation } from "../../../Validation/validation"; -import { - createInfrastructureMonitor, - updateInfrastructureMonitor, -} from "../../../Features/InfrastructureMonitors/infrastructureMonitorsSlice"; -import { useHardwareMonitorsFetch } from "../Details/Hooks/useHardwareMonitorsFetch"; +import { useFetchHardwareMonitorById } from "../../../Hooks/monitorHooks"; import { capitalizeFirstLetter } from "../../../Utils/stringUtils"; import { useTranslation } from "react-i18next"; import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications"; import NotificationsConfig from "../../../Components/NotificationConfig"; +import { useUpdateMonitor, useCreateMonitor } from "../../../Hooks/monitorHooks"; // MUI import { Box, Stack, Typography, Button, ButtonGroup } from "@mui/material"; @@ -55,9 +52,6 @@ const getAlertError = (errors) => { const CreateInfrastructureMonitor = () => { const theme = useTheme(); const { user } = useSelector((state) => state.auth); - const monitorState = useSelector((state) => state.infrastructureMonitor); - const dispatch = useDispatch(); - const navigate = useNavigate(); const { monitorId } = useParams(); const { t } = useTranslation(); @@ -65,9 +59,11 @@ const CreateInfrastructureMonitor = () => { const isCreate = typeof monitorId === "undefined"; // Fetch monitor details if editing - const { monitor, isLoading, networkError } = useHardwareMonitorsFetch({ monitorId }); + const [monitor, isLoading, networkError] = useFetchHardwareMonitorById({ monitorId }); const [notifications, notificationsAreLoading, notificationsError] = useGetNotificationsByTeamId(); + const [updateMonitor, isUpdating] = useUpdateMonitor(); + const [createMonitor, isCreating] = useCreateMonitor(); // State const [errors, setErrors] = useState({}); @@ -187,6 +183,7 @@ const CreateInfrastructureMonitor = () => { }; form = { + ...(isCreate ? {} : { _id: monitorId }), ...rest, description: form.name, teamId: user.teamId, @@ -197,19 +194,9 @@ const CreateInfrastructureMonitor = () => { }; // Handle create or update - const action = isCreate - ? await dispatch(createInfrastructureMonitor({ monitor: form })) - : await dispatch(updateInfrastructureMonitor({ monitorId, monitor: form })); - if (action.meta.requestStatus === "fulfilled") { - createToast({ - body: isCreate - ? t("infrastructureMonitorCreated") - : t("infrastructureMonitorUpdated"), - }); - navigate("/infrastructure"); - } else { - createToast({ body: "Failed to save monitor." }); - } + isCreate + ? await createMonitor({ monitor: form, redirect: "/infrastructure" }) + : await updateMonitor({ monitor: form, redirect: "/infrastructure" }); }; const onChange = (event) => { @@ -448,7 +435,7 @@ const CreateInfrastructureMonitor = () => { type="submit" variant="contained" color="accent" - loading={monitorState?.isLoading} + loading={isLoading || isUpdating || isCreating || notificationsAreLoading} > {t(isCreate ? "infrastructureCreateMonitor" : "infrastructureEditMonitor")} diff --git a/client/src/Pages/Infrastructure/Details/Components/StatusBoxes/index.jsx b/client/src/Pages/Infrastructure/Details/Components/StatusBoxes/index.jsx index 66483d448..6c11e7c82 100644 --- a/client/src/Pages/Infrastructure/Details/Components/StatusBoxes/index.jsx +++ b/client/src/Pages/Infrastructure/Details/Components/StatusBoxes/index.jsx @@ -4,14 +4,14 @@ import StatusBoxes from "../../../../../Components/StatusBoxes"; import StatBox from "../../../../../Components/StatBox"; //Utils -import useUtils from "../../../../../Pages/Uptime/Monitors/Hooks/useUtils"; +import { useMonitorUtils } from "../../../../../Hooks/useMonitorUtils"; import { useHardwareUtils } from "../../Hooks/useHardwareUtils"; import { useTranslation } from "react-i18next"; const InfraStatBoxes = ({ shouldRender, monitor }) => { // Utils const { formatBytes } = useHardwareUtils(); - const { determineState } = useUtils(); + const { determineState } = useMonitorUtils(); const { t } = useTranslation(); const { stats } = monitor ?? {}; diff --git a/client/src/Pages/Infrastructure/Details/index.jsx b/client/src/Pages/Infrastructure/Details/index.jsx index fefb7d2aa..842e0f6d9 100644 --- a/client/src/Pages/Infrastructure/Details/index.jsx +++ b/client/src/Pages/Infrastructure/Details/index.jsx @@ -11,7 +11,7 @@ import GenericFallback from "../../../Components/GenericFallback"; // Utils import { useTheme } from "@emotion/react"; import { useIsAdmin } from "../../../Hooks/useIsAdmin"; -import { useHardwareMonitorsFetch } from "./Hooks/useHardwareMonitorsFetch"; +import { useFetchHardwareMonitorById } from "../../../Hooks/monitorHooks"; import { useState } from "react"; import { useTranslation } from "react-i18next"; import { useParams } from "react-router-dom"; @@ -33,7 +33,7 @@ const InfrastructureDetails = () => { const { t } = useTranslation(); const isAdmin = useIsAdmin(); - const { isLoading, networkError, monitor } = useHardwareMonitorsFetch({ + const [monitor, isLoading, networkError] = useFetchHardwareMonitorById({ monitorId, dateRange, }); diff --git a/client/src/Pages/Infrastructure/Monitors/Components/MonitorsTable/index.jsx b/client/src/Pages/Infrastructure/Monitors/Components/MonitorsTable/index.jsx index 0ec435c60..761ecaa0e 100644 --- a/client/src/Pages/Infrastructure/Monitors/Components/MonitorsTable/index.jsx +++ b/client/src/Pages/Infrastructure/Monitors/Components/MonitorsTable/index.jsx @@ -10,7 +10,7 @@ import CustomGauge from "../../../../../Components/Charts/CustomGauge"; // Utils import { useTheme } from "@emotion/react"; -import useUtils from "../../../../Uptime/Monitors/Hooks/useUtils"; +import { useMonitorUtils } from "../../../../../Hooks/useMonitorUtils"; import { useNavigate } from "react-router-dom"; import PropTypes from "prop-types"; import { useTranslation } from "react-i18next"; @@ -19,7 +19,7 @@ const MonitorsTable = ({ shouldRender, monitors, isAdmin, handleActionMenuDelete // Utils const theme = useTheme(); const { t } = useTranslation(); - const { determineState } = useUtils(); + const { determineState } = useMonitorUtils(); const navigate = useNavigate(); // Handlers diff --git a/client/src/Pages/Infrastructure/Monitors/index.jsx b/client/src/Pages/Infrastructure/Monitors/index.jsx index bfba843c0..6d49f64a7 100644 --- a/client/src/Pages/Infrastructure/Monitors/index.jsx +++ b/client/src/Pages/Infrastructure/Monitors/index.jsx @@ -10,15 +10,20 @@ import Fallback from "../../../Components/Fallback"; import Filter from "./Components/Filters"; // Utils import { useTheme } from "@emotion/react"; -import { useMonitorFetch } from "./Hooks/useMonitorFetch"; import { useState } from "react"; +import { useSelector } from "react-redux"; import { useIsAdmin } from "../../../Hooks/useIsAdmin"; import { useTranslation } from "react-i18next"; +import { useFetchMonitorsByTeamId } from "../../../Hooks/monitorHooks"; // Constants +const TYPES = ["hardware"]; const BREADCRUMBS = [{ name: `infrastructure`, path: "/infrastructure" }]; const InfrastructureMonitors = () => { // Redux state + const { user } = useSelector((state) => state.auth); + + // Local state const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const [updateTrigger, setUpdateTrigger] = useState(false); @@ -50,7 +55,10 @@ const InfrastructureMonitors = () => { const field = toFilterStatus !== undefined ? "status" : undefined; - const { monitors, summary, isLoading, networkError } = useMonitorFetch({ + const [monitors, summary, isLoading, networkError] = useFetchMonitorsByTeamId({ + teamId: user.teamId, + limit: 1, + types: TYPES, page, field: field, filter: toFilterStatus, diff --git a/client/src/Pages/PageSpeed/Configure/index.jsx b/client/src/Pages/PageSpeed/Configure/index.jsx index 487106247..71e1e111e 100644 --- a/client/src/Pages/PageSpeed/Configure/index.jsx +++ b/client/src/Pages/PageSpeed/Configure/index.jsx @@ -12,45 +12,43 @@ import NotificationsConfig from "../../../Components/NotificationConfig"; import Dialog from "../../../Components/Dialog"; // Utils -import { useEffect, useState } from "react"; +import { useState } from "react"; import { useTheme } from "@emotion/react"; -import { useDispatch, useSelector } from "react-redux"; -import { useNavigate, useParams } from "react-router"; -import { - deletePageSpeed, - getPagespeedMonitorById, - getPageSpeedByTeamId, - updatePageSpeed, - pausePageSpeed, -} from "../../../Features/PageSpeedMonitor/pageSpeedMonitorSlice"; +import { useParams } from "react-router"; import { monitorValidation } from "../../../Validation/validation"; -import { createToast } from "../../../Utils/toastUtils"; import { useTranslation } from "react-i18next"; -import useUtils from "../../Uptime/Monitors/Hooks/useUtils"; +import { useMonitorUtils } from "../../../Hooks/useMonitorUtils"; import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications"; - +import { + useFetchMonitorById, + useDeleteMonitor, + useUpdateMonitor, + usePauseMonitor, +} from "../../../Hooks/monitorHooks"; 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); + const [updateTrigger, setUpdateTrigger] = useState(false); // Utils const theme = useTheme(); const { t } = useTranslation(); - const navigate = useNavigate(); - const dispatch = useDispatch(); const MS_PER_MINUTE = 60000; const { monitorId } = useParams(); - const { statusColor, pagespeedStatusMsg, determineState } = useUtils(); + const { statusColor, pagespeedStatusMsg, determineState } = useMonitorUtils(); const [notifications, notificationsAreLoading, notificationsError] = useGetNotificationsByTeamId(); + const [isLoading] = useFetchMonitorById({ monitorId, setMonitor, updateTrigger }); + const [deleteMonitor, isDeleting] = useDeleteMonitor(); + const [updateMonitor, isUpdating] = useUpdateMonitor(); + const [pauseMonitor, isPausing] = usePauseMonitor(); + const frequencies = [ { _id: 3, name: "3 minutes" }, { _id: 5, name: "5 minutes" }, @@ -61,24 +59,10 @@ const PageSpeedConfigure = () => { { _id: 10080, name: "1 week" }, ]; - useEffect(() => { - const fetchMonitor = async () => { - try { - const action = await dispatch(getPagespeedMonitorById({ monitorId })); - - if (getPagespeedMonitorById.fulfilled.match(action)) { - const monitor = action.payload.data; - setMonitor(monitor); - } else if (getPagespeedMonitorById.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(); - }, [dispatch, monitorId, navigate]); + // Handlers + const triggerUpdate = () => { + setUpdateTrigger(!updateTrigger); + }; const onChange = (event) => { let { value, name } = event.target; @@ -106,42 +90,17 @@ const PageSpeedConfigure = () => { }; const handlePause = async () => { - try { - const action = await dispatch(pausePageSpeed({ monitorId })); - if (pausePageSpeed.fulfilled.match(action)) { - const monitor = action.payload.data; - setMonitor(monitor); - const state = action?.payload?.data.isActive === false ? "paused" : "resumed"; - createToast({ body: `Monitor ${state} successfully.` }); - } else if (pausePageSpeed.rejected.match(action)) { - throw new Error(action.error.message); - } - } catch (error) { - createToast({ body: "Failed to pause monitor" }); - } + await pauseMonitor({ monitorId, triggerUpdate }); }; const onSubmit = async (event) => { event.preventDefault(); - const action = await dispatch(updatePageSpeed({ monitor: monitor })); - if (action.meta.requestStatus === "fulfilled") { - createToast({ body: "Monitor updated successfully!" }); - dispatch(getPageSpeedByTeamId()); - } else { - createToast({ body: "Failed to update monitor." }); - } + await updateMonitor({ monitor, redirect: "/pagespeed" }); }; const handleRemove = async (event) => { event.preventDefault(); - setButtonLoading(true); - const action = await dispatch(deletePageSpeed({ monitor })); - if (action.meta.requestStatus === "fulfilled") { - navigate("/pagespeed"); - } else { - createToast({ body: "Failed to delete monitor." }); - } - setButtonLoading(false); + await deleteMonitor({ monitor, redirect: "/pagespeed" }); }; return ( @@ -363,7 +322,7 @@ const PageSpeedConfigure = () => { mt="auto" > diff --git a/client/src/Pages/PageSpeed/Details/index.jsx b/client/src/Pages/PageSpeed/Details/index.jsx index 5724f12a1..e8afcf8c8 100644 --- a/client/src/Pages/PageSpeed/Details/index.jsx +++ b/client/src/Pages/PageSpeed/Details/index.jsx @@ -11,8 +11,7 @@ import GenericFallback from "../../../Components/GenericFallback"; import { useTheme } from "@emotion/react"; import { useIsAdmin } from "../../../Hooks/useIsAdmin"; import { useParams } from "react-router-dom"; -import { useSelector } from "react-redux"; -import { useMonitorFetch } from "./Hooks/useMonitorFetch"; +import { useFetchStatsByMonitorId } from "../../../Hooks/monitorHooks"; import { useState } from "react"; import { useTranslation } from "react-i18next"; // Constants @@ -28,8 +27,13 @@ const PageSpeedDetails = () => { const isAdmin = useIsAdmin(); const { monitorId } = useParams(); - const { monitor, audits, isLoading, networkError } = useMonitorFetch({ + const [monitor, audits, isLoading, networkError] = useFetchStatsByMonitorId({ monitorId, + sortOrder: "desc", + limit: 50, + dateRange: "day", + numToDisplay: null, + normalize: null, }); const [metrics, setMetrics] = useState({ diff --git a/client/src/Pages/PageSpeed/Monitors/Components/Card/index.jsx b/client/src/Pages/PageSpeed/Monitors/Components/Card/index.jsx index 8c83f102a..2220a4b16 100644 --- a/client/src/Pages/PageSpeed/Monitors/Components/Card/index.jsx +++ b/client/src/Pages/PageSpeed/Monitors/Components/Card/index.jsx @@ -8,7 +8,7 @@ import { useTheme } from "@emotion/react"; import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip } from "recharts"; import { useSelector } from "react-redux"; import { formatDateWithTz, formatDurationSplit } from "../../../../../Utils/timeUtils"; -import useUtils from "../../../../Uptime/Monitors/Hooks/useUtils"; +import { useMonitorUtils } from "../../../../../Hooks/useMonitorUtils"; import { useState } from "react"; import { useTranslation } from "react-i18next"; import IconBox from "../../../../../Components/IconBox"; @@ -118,7 +118,7 @@ const processData = (data) => { const PagespeedAreaChart = ({ data, status }) => { const theme = useTheme(); const [isHovered, setIsHovered] = useState(false); - const { statusToTheme } = useUtils(); + const { statusToTheme } = useMonitorUtils(); const themeColor = statusToTheme[status]; @@ -206,7 +206,7 @@ PagespeedAreaChart.propTypes = { * @returns {JSX.Element} - The rendered card. */ const Card = ({ monitor }) => { - const { determineState, pagespeedStatusMsg } = useUtils(); + const { determineState, pagespeedStatusMsg } = useMonitorUtils(); const theme = useTheme(); const { t } = useTranslation(); const navigate = useNavigate(); @@ -275,7 +275,7 @@ const Card = ({ monitor }) => { sx={{ gridColumnStart: 1, gridColumnEnd: 4 }} > diff --git a/client/src/Pages/PageSpeed/Monitors/index.jsx b/client/src/Pages/PageSpeed/Monitors/index.jsx index 808541cee..319b0da21 100644 --- a/client/src/Pages/PageSpeed/Monitors/index.jsx +++ b/client/src/Pages/PageSpeed/Monitors/index.jsx @@ -5,17 +5,17 @@ import CreateMonitorHeader from "../../../Components/MonitorCreateHeader"; import MonitorCountHeader from "../../../Components/MonitorCountHeader"; import MonitorGrid from "./Components/MonitorGrid"; import Fallback from "../../../Components/Fallback"; +import GenericFallback from "../../../Components/GenericFallback"; // Utils import { useTheme } from "@emotion/react"; import { useSelector } from "react-redux"; import { useIsAdmin } from "../../../Hooks/useIsAdmin"; -import useMonitorsFetch from "./Hooks/useMonitorsFetch"; -import GenericFallback from "../../../Components/GenericFallback"; import { useTranslation } from "react-i18next"; +import { useFetchMonitorsByTeamId } from "../../../Hooks/monitorHooks"; // Constants const BREADCRUMBS = [{ name: `pagespeed`, path: "/pagespeed" }]; - +const TYPES = ["pagespeed"]; const PageSpeed = () => { const theme = useTheme(); const { t } = useTranslation(); @@ -23,8 +23,15 @@ const PageSpeed = () => { const { user } = useSelector((state) => state.auth); const { pagespeedApiKey } = useSelector((state) => state.settings); - const { isLoading, monitors, summary, networkError } = useMonitorsFetch({ + const [monitors, monitorsSummary, isLoading, networkError] = useFetchMonitorsByTeamId({ teamId: user.teamId, + limit: 10, + types: TYPES, + page: null, + rowsPerPage: null, + filter: null, + field: null, + order: null, }); if (networkError === true) { @@ -68,7 +75,7 @@ const PageSpeed = () => { /> { const theme = useTheme(); - const { determineState } = useUtils(); + const { determineState } = useMonitorUtils(); const { showURL } = useSelector((state) => state.ui); diff --git a/client/src/Pages/Uptime/Configure/index.jsx b/client/src/Pages/Uptime/Configure/index.jsx index 8718a2209..5a380f8e5 100644 --- a/client/src/Pages/Uptime/Configure/index.jsx +++ b/client/src/Pages/Uptime/Configure/index.jsx @@ -1,37 +1,37 @@ -import { useNavigate, useParams } from "react-router"; -import { useTheme } from "@emotion/react"; -import { useDispatch, useSelector } from "react-redux"; -import { useState, useEffect } from "react"; -import { - Box, - Stack, - Tooltip, - Typography, - Button, - FormControlLabel, - Switch, -} from "@mui/material"; -import { monitorValidation } from "../../../Validation/validation"; -import { createToast } from "../../../Utils/toastUtils"; -import { useTranslation } from "react-i18next"; +// Components +import Box from "@mui/material/Box"; +import Stack from "@mui/material/Stack"; +import Tooltip from "@mui/material/Tooltip"; +import Typography from "@mui/material/Typography"; +import Button from "@mui/material/Button"; +import FormControlLabel from "@mui/material/FormControlLabel"; +import Switch from "@mui/material/Switch"; import ConfigBox from "../../../Components/ConfigBox"; -import { - updateUptimeMonitor, - deleteUptimeMonitor, -} from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; +import Breadcrumbs from "../../../Components/Breadcrumbs"; import TextInput from "../../../Components/Inputs/TextInput"; import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments"; import Select from "../../../Components/Inputs/Select"; -import Breadcrumbs from "../../../Components/Breadcrumbs"; -import PulseDot from "../../../Components/Animated/PulseDot"; -import "./index.css"; import Dialog from "../../../Components/Dialog"; -import { usePauseMonitor } from "../../../Hooks/useMonitorControls"; +import PulseDot from "../../../Components/Animated/PulseDot"; +import Checkbox from "../../../Components/Inputs/Checkbox"; + +// Utils +import { useParams } from "react-router"; +import { useTheme } from "@emotion/react"; +import { useState } from "react"; +import { monitorValidation } from "../../../Validation/validation"; +import { createToast } from "../../../Utils/toastUtils"; +import { useTranslation } from "react-i18next"; import PauseOutlinedIcon from "@mui/icons-material/PauseOutlined"; import PlayArrowOutlinedIcon from "@mui/icons-material/PlayArrowOutlined"; import { useMonitorUtils } from "../../../Hooks/useMonitorUtils"; -import { useFetchUptimeMonitorById } from "../../../Hooks/useFetchUptimeMonitorById"; import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications"; +import { + useDeleteMonitor, + useUpdateMonitor, + usePauseMonitor, + useFetchMonitorById, +} from "../../../Hooks/monitorHooks"; import NotificationsConfig from "../../../Components/NotificationConfig"; /** @@ -76,18 +76,19 @@ const Configure = () => { }; // Network - const [monitor, isLoading, error] = useFetchUptimeMonitorById(monitorId, updateTrigger); const [notifications, notificationsAreLoading, notificationsError] = useGetNotificationsByTeamId(); - const [pauseMonitor, isPausing, pauseError] = usePauseMonitor({ - monitorId: monitor?._id, - triggerUpdate, + const [pauseMonitor, isPausing, pauseError] = usePauseMonitor({}); + const [deleteMonitor, isDeleting] = useDeleteMonitor(); + const [updateMonitor, isUpdating] = useUpdateMonitor(); + const [isLoading] = useFetchMonitorById({ + monitorId, + setMonitor: setForm, + updateTrigger, }); const MS_PER_MINUTE = 60000; - const navigate = useNavigate(); const theme = useTheme(); - const dispatch = useDispatch(); const matchMethodOptions = [ { _id: "equal", name: "Equal" }, @@ -111,7 +112,7 @@ const Configure = () => { // Handlers const handlePause = async () => { - const res = await pauseMonitor(); + const res = await pauseMonitor({ monitorId: form?._id, triggerUpdate }); if (typeof res !== "undefined") { triggerUpdate(); } @@ -119,12 +120,7 @@ const Configure = () => { const handleRemove = async (event) => { event.preventDefault(); - const action = await dispatch(deleteUptimeMonitor({ monitor })); - if (action.meta.requestStatus === "fulfilled") { - navigate("/uptime"); - } else { - createToast({ body: "Failed to delete monitor." }); - } + await deleteMonitor({ monitor: form, redirect: "/uptime" }); }; const onChange = (event) => { @@ -134,6 +130,17 @@ const Configure = () => { value = checked; } + if (name === "useAdvancedMatching") { + setForm((prevForm) => { + return { + ...prevForm, + matchMethod: "equal", + }; + }); + setUseAdvancedMatching(!useAdvancedMatching); + return; + } + if (name === "interval") { value = value * MS_PER_MINUTE; } @@ -146,7 +153,6 @@ const Configure = () => { setErrors((prev) => { const updatedErrors = { ...prev }; - if (validation.error) updatedErrors[name] = validation.error.details[0].message; else delete updatedErrors[name]; return updatedErrors; @@ -183,7 +189,7 @@ const Configure = () => { if (validation.error) { const newErrors = {}; - error.details.forEach((err) => { + validation.error.details.forEach((err) => { newErrors[err.path[0]] = err.message; }); setErrors(newErrors); @@ -192,27 +198,12 @@ const Configure = () => { } toSubmit.notifications = form.notifications; - const action = await dispatch(updateUptimeMonitor({ monitor: toSubmit })); - if (action.meta.requestStatus === "fulfilled") { - createToast({ body: "Monitor updated successfully!" }); - } else { - createToast({ body: "Failed to update monitor." }); - } + console.log(JSON.stringify(toSubmit, null, 2)); + // await updateMonitor({ monitor: toSubmit, redirect: "/uptime" }); }; - // Effects - useEffect(() => { - if (monitor?.matchMethod) { - setUseAdvancedMatching(true); - } - - setForm({ - ...monitor, - }); - }, [monitor, notifications]); - // Parse the URL - const parsedUrl = parseUrl(monitor?.url); + const parsedUrl = parseUrl(form?.url); const protocol = parsedUrl?.protocol?.replace(":", "") || ""; const { determineState, statusColor } = useMonitorUtils(); @@ -434,7 +425,13 @@ const Configure = () => { onChange={onChange} items={frequencies} /> - {form.type === "http" && ( + + {form.type === "http" && useAdvancedMatching && ( <>