From 91a2a72bf2be06df7a0510991678a5a336f9544c Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Wed, 18 Sep 2024 19:39:33 -0400 Subject: [PATCH 001/108] Purged outdated code --- Client/src/App.jsx | 4 +- .../index.css | 0 .../Maintenance/CreateMaintenance/index.jsx | 22 ++ .../CreateMaintenanceWindow/index.jsx | 298 ------------------ .../Pages/Monitors/CreateMonitor/index.css | 34 -- 5 files changed, 24 insertions(+), 334 deletions(-) rename Client/src/Pages/Maintenance/{CreateMaintenanceWindow => CreateMaintenance}/index.css (100%) create mode 100644 Client/src/Pages/Maintenance/CreateMaintenance/index.jsx delete mode 100644 Client/src/Pages/Maintenance/CreateMaintenanceWindow/index.jsx diff --git a/Client/src/App.jsx b/Client/src/App.jsx index d6fca146f..3cc9e5bd6 100644 --- a/Client/src/App.jsx +++ b/Client/src/App.jsx @@ -25,7 +25,7 @@ import withAdminProp from "./HOC/withAdminProp"; import Configure from "./Pages/Monitors/Configure"; import PageSpeed from "./Pages/PageSpeed"; import CreatePageSpeed from "./Pages/PageSpeed/CreatePageSpeed"; -import CreateNewMaintenanceWindow from "./Pages/Maintenance/CreateMaintenanceWindow"; +import CreateMaintenance from "./Pages/Maintenance/CreateMaintenance"; import PageSpeedDetails from "./Pages/PageSpeed/Details"; import PageSpeedConfigure from "./Pages/PageSpeed/Configure"; import { ThemeProvider } from "@emotion/react"; @@ -89,7 +89,7 @@ function App() { /> } + element={} /> { + const theme = useTheme(); + + return ; +}; + +export default CreateMaintenance; diff --git a/Client/src/Pages/Maintenance/CreateMaintenanceWindow/index.jsx b/Client/src/Pages/Maintenance/CreateMaintenanceWindow/index.jsx deleted file mode 100644 index 43102ac21..000000000 --- a/Client/src/Pages/Maintenance/CreateMaintenanceWindow/index.jsx +++ /dev/null @@ -1,298 +0,0 @@ -import { Box, Button, Stack, Typography } from "@mui/material"; -import "./index.css"; -import { useState } from "react"; -import Back from "../../../assets/icons/left-arrow-long.svg?react"; -import Select from "../../../Components/Inputs/Select"; -import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"; -import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider"; -import dayjs from "dayjs"; -import { DatePicker } from "@mui/x-date-pickers/DatePicker"; -import { MobileTimePicker } from "@mui/x-date-pickers/MobileTimePicker"; -import Field from "../../../Components/Inputs/Field"; -import { maintenanceWindowValidation } from "../../../Validation/validation"; -import { logger } from "../../../Utils/Logger"; -import { createToast } from "../../../Utils/toastUtils"; -import { useTheme } from "@emotion/react"; - -const directory = { - title: "Create a maintenance window", - description: "Your pings won’t be sent in this time frame.", -}; - -const repeatOptions = [ - { _id: 1, name: "Don't repeat" }, - { _id: 2, name: "Repeat daily" }, - { _id: 3, name: "Repeat weekly" }, -]; - -const configOptionTitle = (title, description) => { - return ( - - - {title} - - {description && ( - - {description} - - )} - - ); -}; - -const durationOptions = [ - { _id: "minutes", name: "minutes" }, - { _id: "hours", name: "hours" }, - { _id: "days", name: "days" }, -]; - -const CreateNewMaintenanceWindow = () => { - const theme = useTheme(); - - const [values, setValues] = useState({ - repeat: 1, - date: dayjs(), - startTime: dayjs(), - duration: "60", - unit: "minutes", - displayName: "", - AddMonitors: "", - }); - const [errors, setErrors] = useState({}); - - const handleChange = (event, name) => { - const { value } = event.target; - setValues((prev) => ({ - ...prev, - [name]: value, - })); - }; - - const handleSubmit = async () => { - const data = { - repeat: values.repeat, - date: values.date.format("YYYY-MM-DD"), - startTime: values.startTime.format("HH:mm"), - duration: values.duration, - unit: values.unit, - displayName: values.displayName, - addMonitors: values.AddMonitors, - }; - - const { error } = maintenanceWindowValidation.validate(data, { - abortEarly: false, - }); - logger.log("error: ", error); - if (!error || error.details.length === 0) { - setErrors({}); - } else { - const newErrors = {}; - error.details.forEach((err) => { - newErrors[err.path[0]] = err.message; - }); - setErrors(newErrors); - createToast({ - body: - error.details && error.details.length > 0 - ? error.details[0].message - : "Error validating data", - }); - logger.error("Validation errors:", error.details); - } - - logger.log("Submitting data: ", data); - }; - - const configOptions = [ - { - title: "Repeat", - component: ( - handleChange(e, "unit")} - id="duration-unit" - items={durationOptions} - value={values.unit} - /> - - ), - }, - { - title: "Display name", - component: ( - handleChange(e, "displayName")} - error={errors.displayName} - /> - ), - }, - { - title: "Add monitors", - component: ( - - handleChange(e, "AddMonitors")} - error={errors.addMonitors} - /> - - Add all monitors to this maintenance window - - - ), - }, - ]; - - return ( -
- - - - - {directory.title} - - - - {directory.description} - - - - {configOptions.map((item, index) => ( - - {item.title && configOptionTitle(item.title, item.description)} - {item.component && item.component} - - ))} - - - - - - -
- ); -}; - -export default CreateNewMaintenanceWindow; diff --git a/Client/src/Pages/Monitors/CreateMonitor/index.css b/Client/src/Pages/Monitors/CreateMonitor/index.css index c38345be7..e69de29bb 100644 --- a/Client/src/Pages/Monitors/CreateMonitor/index.css +++ b/Client/src/Pages/Monitors/CreateMonitor/index.css @@ -1,34 +0,0 @@ -.create-monitor p.MuiTypography-root, -.create-monitor button.MuiButtonBase-root { - font-size: var(--env-var-font-size-medium); -} -.create-monitor h6.MuiTypography-root, -.create-monitor .MuiBox-root .field + p.MuiTypography-root { - font-size: var(--env-var-font-size-small-plus); - opacity: 0.8; -} -.create-monitor button.MuiButtonBase-root { - height: 34px; -} - -.create-monitor .error-container { - position: relative; -} -.create-monitor .error-container p.MuiTypography-root.input-error { - opacity: 0.8; - position: absolute; - top: 0; -} -.create-monitor .MuiStack-root:has(span.MuiTypography-root.input-error) { - position: relative; -} -.create-monitor span.MuiTypography-root.input-error { - position: absolute; - top: 100%; -} - -.create-monitor .MuiStack-root .MuiButtonGroup-root button { - font-size: var(--env-var-font-size-small); - height: 28px; - padding: 8px; -} From ee30f44062d00a0a13043077f19ee7286a54c3c6 Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Wed, 18 Sep 2024 19:50:01 -0400 Subject: [PATCH 002/108] Added basic layout --- .../Maintenance/CreateMaintenance/index.css | 72 +------------------ .../Maintenance/CreateMaintenance/index.jsx | 70 +++++++++++++++--- Client/src/Pages/Maintenance/index.css | 36 ---------- 3 files changed, 63 insertions(+), 115 deletions(-) diff --git a/Client/src/Pages/Maintenance/CreateMaintenance/index.css b/Client/src/Pages/Maintenance/CreateMaintenance/index.css index 4ee17db72..bf8514740 100644 --- a/Client/src/Pages/Maintenance/CreateMaintenance/index.css +++ b/Client/src/Pages/Maintenance/CreateMaintenance/index.css @@ -1,71 +1,3 @@ -.maintenance-options .MuiStack-root .MuiStack-root.select-wrapper, -.maintenance-options .MuiStack-root .field { - width: 60%; - max-width: 380px; -} - -.date-picker .MuiOutlinedInput-root, -.time-picker .MuiOutlinedInput-root { - height: 34px; - font-size: var(--env-var-font-size-medium); -} - -.date-picker .MuiOutlinedInput-root { - width: 140px; -} - -.time-picker .MuiOutlinedInput-root { - width: 90px; -} - -.maintenance-options .MuiInputAdornment-outlined .MuiIconButton-root svg { - width: 20px; -} - -.duration-config .field-text .MuiTextField-root, -.maintenance-options .duration-config .field { - width: 70px; - min-width: 70px; - max-width: 70px; -} - -.duration-config > .MuiStack-root.select-wrapper { - width: 100px; -} - -.duration-config - > .MuiStack-root.select-wrapper - > .MuiInputBase-root:has(> .MuiSelect-select) { - width: 100px; - min-width: 100px; -} - -.duration-config > .select-wrapper .select-component > .MuiSelect-select { - text-transform: none; -} - -.maintenance-options .add-monitors-fields .field.field-text { - width: 100%; -} - -.MuiPopover-paper.MuiMenu-paper.select-dropdown - .MuiMenu-list - .MuiButtonBase-root { - text-transform: none; -} - -.date-picker - .MuiOutlinedInput-root - .MuiInputAdornment-outlined - .MuiIconButton-root { - outline: none; - - &:hover { - background-color: transparent; - } -} - -.create-maintenance-window .MuiStack-root .MuiStack-root > button { - width: 110px; - height: 34px; +.create-maintenance button { + height: 35px; } diff --git a/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx b/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx index 3c51c420e..c4aa697f6 100644 --- a/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx +++ b/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx @@ -1,22 +1,74 @@ import { Box, Button, Stack, Typography } from "@mui/material"; import { useTheme } from "@emotion/react"; import { useState } from "react"; -import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"; -import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider"; -import { DatePicker } from "@mui/x-date-pickers/DatePicker"; -import { MobileTimePicker } from "@mui/x-date-pickers/MobileTimePicker"; -import { maintenanceWindowValidation } from "../../../Validation/validation"; -import { logger } from "../../../Utils/Logger"; -import { createToast } from "../../../Utils/toastUtils"; import Select from "../../../Components/Inputs/Select"; -import dayjs from "dayjs"; import Field from "../../../Components/Inputs/Field"; +import Breadcrumbs from "../../../Components/Breadcrumbs"; import "./index.css"; const CreateMaintenance = () => { const theme = useTheme(); - return ; + return ( + + + + + + Create a{" "} + + + maintenance{" "} + + + window + + + + + + + + + + ); }; export default CreateMaintenance; diff --git a/Client/src/Pages/Maintenance/index.css b/Client/src/Pages/Maintenance/index.css index 46ba8b0fa..e69de29bb 100644 --- a/Client/src/Pages/Maintenance/index.css +++ b/Client/src/Pages/Maintenance/index.css @@ -1,36 +0,0 @@ -.maintenance-checklist-main { - max-width: 350px; - min-height: 390px; - margin: auto; - padding: 5px; -} - -.maintenance-image { - width: 280px; - height: 150px; - background-color: whitesmoke; - border-radius: 10px; -} - -.maintenance-title { - color: var(--secondary-color-light); - font-size: 16px; - font-weight: bold; - margin-top: 40px; - margin-bottom: 30px; -} - -.checklist-item { - font-size: 13px; - color: var(--secondary-color-light); - display: flex; - margin-bottom: 10px; -} - -.checklist-item-text { - margin-left: 10px; -} - -.maintenance-checklist-main .maintenance-checklist-button { - margin-top: 30px; -} From 577bc9447daa407453fc8db6a70b7e055091d9f2 Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Wed, 18 Sep 2024 21:22:22 -0400 Subject: [PATCH 003/108] Added fields --- .../Maintenance/CreateMaintenance/index.jsx | 135 +++++++++++++++--- .../Maintenance/CreateMaintenance/styled.jsx | 20 +++ 2 files changed, 134 insertions(+), 21 deletions(-) create mode 100644 Client/src/Pages/Maintenance/CreateMaintenance/styled.jsx diff --git a/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx b/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx index c4aa697f6..724643f59 100644 --- a/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx +++ b/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx @@ -5,6 +5,25 @@ import Select from "../../../Components/Inputs/Select"; import Field from "../../../Components/Inputs/Field"; import Breadcrumbs from "../../../Components/Breadcrumbs"; import "./index.css"; +import { ConfigBox } from "./styled"; + +const repeatConfig = [ + { _id: 0, name: "Don't repeat" }, + { _id: 1, name: "Repeat daily" }, + { _id: 2, name: "Repeat weekly" }, +]; + +const durationConfig = [ + { _id: 0, name: "seconds" }, + { _id: 1, name: "minutes" }, + { _id: 2, name: "hours" }, + { _id: 3, name: "days" }, +]; + +const periodConfig = [ + { _id: 0, name: "AM" }, + { _id: 1, name: "PM" }, +]; const CreateMaintenance = () => { const theme = useTheme(); @@ -24,30 +43,104 @@ const CreateMaintenance = () => { gap={theme.spacing(12)} mt={theme.spacing(6)} > - - - Create a{" "} + + + + Create a{" "} + + + maintenance{" "} + + + window + - + Your pings won't be sent during this time frame + + + + + General Settings + + - maintenance{" "} + + + + + + + Duration + + + + + + { const theme = useTheme(); const itemStyles = { @@ -77,6 +79,7 @@ const Select = ({ value={value} onChange={onChange} displayEmpty + name={name} inputProps={{ id: id }} IconComponent={KeyboardArrowDownIcon} MenuProps={{ disableScrollLock: true }} @@ -127,6 +130,7 @@ const Select = ({ Select.propTypes = { id: PropTypes.string.isRequired, + name: PropTypes.string, label: PropTypes.string, placeholder: PropTypes.string, isHidden: PropTypes.bool, diff --git a/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx b/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx index a5e728cca..b7417377e 100644 --- a/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx +++ b/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx @@ -6,6 +6,10 @@ import { ConfigBox } from "./styled"; import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"; import { LocalizationProvider } from "@mui/x-date-pickers"; import { DatePicker } from "@mui/x-date-pickers/DatePicker"; +import { MobileTimePicker } from "@mui/x-date-pickers/MobileTimePicker"; + +import dayjs from "dayjs"; + import Select from "../../../Components/Inputs/Select"; import Field from "../../../Components/Inputs/Field"; import Breadcrumbs from "../../../Components/Breadcrumbs"; @@ -15,9 +19,9 @@ import Search from "../../../Components/Inputs/Search"; import { networkService } from "../../../main"; const repeatConfig = [ - { _id: 0, name: "Don't repeat" }, - { _id: 1, name: "Repeat daily" }, - { _id: 2, name: "Repeat weekly" }, + { _id: 0, name: "Don't repeat", value: "none" }, + { _id: 1, name: "Repeat daily", value: "daily" }, + { _id: 2, name: "Repeat weekly", value: "weekly" }, ]; const durationConfig = [ @@ -27,17 +31,33 @@ const durationConfig = [ { _id: 3, name: "days" }, ]; -const periodConfig = [ - { _id: 0, name: "AM" }, - { _id: 1, name: "PM" }, -]; +const getValueById = (config, id) => { + const item = config.find((config) => config._id === id); + return item ? (item.value ? item.value : item.name) : null; +}; + +const getIdByValue = (config, name) => { + const item = config.find((config) => { + if (config.value) return config.value === name; + else return config.name === name; + }); + return item ? item._id : null; +}; const CreateMaintenance = () => { const theme = useTheme(); const { user, authToken } = useSelector((state) => state.auth); const [monitors, setMonitors] = useState([]); const [search, setSearch] = useState(""); - const [selectedMonitor, setSelectedMonitor] = useState(null); + const [form, setForm] = useState({ + repeat: "none", + startDate: dayjs().toISOString(), + startTime: dayjs().toISOString(), + duration: "", + durationUnit: "seconds", + name: "", + monitors: [], + }); useEffect(() => { const fetchMonitors = async () => { @@ -56,9 +76,18 @@ const CreateMaintenance = () => { setSearch(value); }; - const handleSelectMonitor = (monitor) => { - setSelectedMonitor(monitor); + const handleSelectMonitors = (monitors) => { + setForm({ ...form, monitors }); }; + + const handleFormChange = (key, value) => { + setForm({ ...form, [key]: value }); + }; + + const handleTimeChange = (key, newTime) => { + setForm({ ...form, [key]: newTime }); + }; + return ( { > {}} - /> + + { + handleTimeChange("startTime", newTime.toISOString()); + }} + slotProps={{ + nextIconButton: { sx: { ml: theme.spacing(2) } }, + field: { + sx: { + width: "fit-content", + "& > .MuiOutlinedInput-root": { + flexDirection: "row-reverse", + }, + "& input": { + height: 34, + p: 0, + pl: theme.spacing(5), + }, + "& fieldset": { + borderColor: theme.palette.border.dark, + borderRadius: theme.shape.borderRadius, + }, + "&:not(:has(.Mui-disabled)):not(:has(.Mui-error)) .MuiOutlinedInput-root:not(:has(input:focus)):hover fieldset": + { + borderColor: theme.palette.border.dark, + }, + }, + }, + }} + /> + @@ -186,12 +251,25 @@ const CreateMaintenance = () => { Duration - + + { + handleFormChange("duration", event.target.value); + }} + /> { Date { }} sx={{}} onChange={(newDate) => { - handleTimeChange("startDate", newDate.toISOString()); + handleTimeChange("startDate", newDate); }} + error={errors["startDate"]} /> @@ -212,10 +300,10 @@ const CreateMaintenance = () => { { - handleTimeChange("startTime", newTime.toISOString()); + handleTimeChange("startTime", newTime); }} slotProps={{ nextIconButton: { sx: { ml: theme.spacing(2) } }, @@ -241,6 +329,7 @@ const CreateMaintenance = () => { }, }, }} + error={errors["startTime"]} /> @@ -254,14 +343,15 @@ const CreateMaintenance = () => { { handleFormChange("duration", event.target.value); }} + error={errors["duration"]} /> { + dispatch(setMode(e.target.value)); + }} + items={[{_id:'light', name:'Light'},{_id:'dark', name:'Dark'}]} + > + + + {isAdmin && ( From 56beeaf1baa55157c5e3dea4a879d562ac4791d9 Mon Sep 17 00:00:00 2001 From: Rishav Date: Fri, 11 Oct 2024 23:02:56 +0530 Subject: [PATCH 080/108] fix --- Client/src/Pages/Settings/index.jsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Client/src/Pages/Settings/index.jsx b/Client/src/Pages/Settings/index.jsx index 1021128cf..db3fe232b 100644 --- a/Client/src/Pages/Settings/index.jsx +++ b/Client/src/Pages/Settings/index.jsx @@ -187,8 +187,7 @@ const Settings = ({ isAdmin }) => { Appearance - Theme- The - timezone of the dashboard you publicly display. + Switch between light and dark mode. From 11abb4f07536859677614f3e5d63116006e615f9 Mon Sep 17 00:00:00 2001 From: Rishav Date: Sat, 12 Oct 2024 10:55:00 +0530 Subject: [PATCH 081/108] removed edit button --- Client/src/Components/TabPanels/Account/ProfilePanel.jsx | 8 -------- 1 file changed, 8 deletions(-) diff --git a/Client/src/Components/TabPanels/Account/ProfilePanel.jsx b/Client/src/Components/TabPanels/Account/ProfilePanel.jsx index 36441c53c..efc2db6ae 100644 --- a/Client/src/Components/TabPanels/Account/ProfilePanel.jsx +++ b/Client/src/Components/TabPanels/Account/ProfilePanel.jsx @@ -469,14 +469,6 @@ const ProfilePanel = () => { gap={theme.spacing(5)} justifyContent="flex-end" > - From 6e5d596e2fcd08f36d43207c00fc6fac788309a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivana=20=C5=A0tef=C3=A1nikov=C3=A1=C3=A1=C5=A0=C3=A1?= Date: Sat, 12 Oct 2024 10:21:11 +0200 Subject: [PATCH 082/108] adds pause to action menu --- .../src/Pages/Monitors/Home/actionsMenu.jsx | 41 ++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/Client/src/Pages/Monitors/Home/actionsMenu.jsx b/Client/src/Pages/Monitors/Home/actionsMenu.jsx index abb1af243..315f850f4 100644 --- a/Client/src/Pages/Monitors/Home/actionsMenu.jsx +++ b/Client/src/Pages/Monitors/Home/actionsMenu.jsx @@ -14,6 +14,7 @@ import { } from "@mui/material"; import { deleteUptimeMonitor, + pauseUptimeMonitor, getUptimeMonitorsByTeamId, } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; import Settings from "../../../assets/icons/settings-bold.svg?react"; @@ -26,6 +27,8 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => { const dispatch = useDispatch(); const theme = useTheme(); const authState = useSelector((state) => state.auth); + const authToken = authState.authToken; + const handleRemove = async (event) => { event.preventDefault(); @@ -44,6 +47,28 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => { } }; + const handlePause = async (event) => { + try { + const action = await dispatch( + pauseUptimeMonitor({ authToken, monitorId: monitor._id }) + ); + if (pauseUptimeMonitor.fulfilled.match(action)) { + updateCallback(); + //window.location.reload(); + if (monitor?.isActive){ + createToast({ body: "Monitor paused successfully." }); + }else{ + createToast({ body: "Monitor resume successfully." }); + } + } else { + throw new Error(action.error.message); + } + } catch (error) { + console.error("Error pausing monitor:", monitor._id, error); + createToast({ body: "Failed to pause monitor." }); + } + }; + const openMenu = (event, id, url) => { event.preventDefault(); event.stopPropagation(); @@ -155,6 +180,20 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => { Clone )} + {isAdmin && ( + { + e.stopPropagation(); + handlePause(e); + }} + > + {monitor?.isActive ? ( + "Pause" + ) : ( + "Resume" + )} + + )} {isAdmin && ( { @@ -164,7 +203,7 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => { > Remove - )} + )} Date: Sat, 12 Oct 2024 13:52:51 +0530 Subject: [PATCH 083/108] fix: give display as none or empty in Stack component and remove it from Field component --- Client/src/Components/Inputs/Field/index.jsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Client/src/Components/Inputs/Field/index.jsx b/Client/src/Components/Inputs/Field/index.jsx index 1843a411b..9dbf616a9 100644 --- a/Client/src/Components/Inputs/Field/index.jsx +++ b/Client/src/Components/Inputs/Field/index.jsx @@ -74,6 +74,7 @@ const Field = forwardRef( "&:has(.input-error) .MuiOutlinedInput-root fieldset": { borderColor: theme.palette.error.text, }, + display: hidden ? "none" : "", }} > {label && ( @@ -142,7 +143,7 @@ const Field = forwardRef( }, } : { - display: hidden ? "none" : "", + } } InputProps={{ From 56ddb374d00ff1399b686742dc9db8852a079c2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivana=20=C5=A0tef=C3=A1nikov=C3=A1=C3=A1=C5=A0=C3=A1?= Date: Sat, 12 Oct 2024 10:51:15 +0200 Subject: [PATCH 084/108] edits based on the comments --- Client/src/Pages/Monitors/Home/actionsMenu.jsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Client/src/Pages/Monitors/Home/actionsMenu.jsx b/Client/src/Pages/Monitors/Home/actionsMenu.jsx index 315f850f4..db57f44df 100644 --- a/Client/src/Pages/Monitors/Home/actionsMenu.jsx +++ b/Client/src/Pages/Monitors/Home/actionsMenu.jsx @@ -55,10 +55,10 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => { if (pauseUptimeMonitor.fulfilled.match(action)) { updateCallback(); //window.location.reload(); - if (monitor?.isActive){ + if (action.payload?.isActive === false){ createToast({ body: "Monitor paused successfully." }); }else{ - createToast({ body: "Monitor resume successfully." }); + createToast({ body: "Monitor resumed successfully." }); } } else { throw new Error(action.error.message); @@ -277,6 +277,7 @@ ActionsMenu.propTypes = { _id: PropTypes.string, url: PropTypes.string, type: PropTypes.string, + isActive: PropTypes.bool, }).isRequired, isAdmin: PropTypes.bool, updateCallback: PropTypes.func, From b191cf36a73fae71221bd9acb29a089048096ab4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivana=20=C5=A0tef=C3=A1nikov=C3=A1=C3=A1=C5=A0=C3=A1?= Date: Sat, 12 Oct 2024 14:32:15 +0200 Subject: [PATCH 085/108] Changes based on review --- .../src/Pages/Monitors/Home/actionsMenu.jsx | 22 +++++++------------ 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/Client/src/Pages/Monitors/Home/actionsMenu.jsx b/Client/src/Pages/Monitors/Home/actionsMenu.jsx index db57f44df..d2ccc0b88 100644 --- a/Client/src/Pages/Monitors/Home/actionsMenu.jsx +++ b/Client/src/Pages/Monitors/Home/actionsMenu.jsx @@ -3,6 +3,7 @@ import { useSelector, useDispatch } from "react-redux"; import { useTheme } from "@emotion/react"; import { useNavigate } from "react-router-dom"; import { createToast } from "../../../Utils/toastUtils"; +import { logger } from "../../../Utils/Logger"; import { Button, IconButton, @@ -47,24 +48,20 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => { } }; - const handlePause = async (event) => { + const handlePause = async () => { try { const action = await dispatch( pauseUptimeMonitor({ authToken, monitorId: monitor._id }) ); if (pauseUptimeMonitor.fulfilled.match(action)) { updateCallback(); - //window.location.reload(); - if (action.payload?.isActive === false){ - createToast({ body: "Monitor paused successfully." }); - }else{ - createToast({ body: "Monitor resumed successfully." }); - } + const state = action?.payload?.data.isActive === false ? "paused" : "resumed"; + createToast({ body: `Monitor ${state} successfully.` }); } else { - throw new Error(action.error.message); + throw new Error(action?.error?.message ?? "Failed to pause monitor."); } } catch (error) { - console.error("Error pausing monitor:", monitor._id, error); + logger.error("Error pausing monitor:", monitor._id, error); createToast({ body: "Failed to pause monitor." }); } }; @@ -187,11 +184,8 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => { handlePause(e); }} > - {monitor?.isActive ? ( - "Pause" - ) : ( - "Resume" - )} + {monitor?.isActive === true ? "Pause" : "Resume"} + )} {isAdmin && ( From e7ce9bdc22363fb36b51bb9735651bf0a8ede912 Mon Sep 17 00:00:00 2001 From: Abhimanue Date: Sat, 12 Oct 2024 23:49:39 +0530 Subject: [PATCH 086/108] Add Docs and Changelog to the main menu --- Client/src/Components/Sidebar/index.jsx | 33 +++++++++++++++++++++---- Client/src/assets/icons/changeLog.svg | 3 +++ Client/src/assets/icons/docs.svg | 3 +++ 3 files changed, 34 insertions(+), 5 deletions(-) create mode 100644 Client/src/assets/icons/changeLog.svg create mode 100644 Client/src/assets/icons/docs.svg diff --git a/Client/src/Components/Sidebar/index.jsx b/Client/src/Components/Sidebar/index.jsx index 80a47b68c..bb2097944 100644 --- a/Client/src/Components/Sidebar/index.jsx +++ b/Client/src/Components/Sidebar/index.jsx @@ -41,6 +41,8 @@ import ArrowUp from "../../assets/icons/up-arrow.svg?react"; import ArrowRight from "../../assets/icons/right-arrow.svg?react"; import ArrowLeft from "../../assets/icons/left-arrow.svg?react"; import DotsVertical from "../../assets/icons/dots-vertical.svg?react"; +import ChangeLog from "../../assets/icons/changeLog.svg?react"; +import Docs from "../../assets/icons/docs.svg?react"; import "./index.css"; @@ -71,6 +73,8 @@ const menu = [ const other = [ { name: "Support", path: "support", icon: }, { name: "Settings", path: "settings", icon: }, + { name: "Docs", path: "docs", icon: }, + { name: "Changelog", path: "changelog", icon: }, ]; /** @@ -498,14 +502,33 @@ function Sidebar() { className={ location.pathname.includes(item.path) ? "selected-path" : "" } - onClick={() => - item.path === "support" - ? window.open( + onClick={ + () => { + if (item.path === "support") { + window.open( "https://github.com/bluewave-labs/bluewave-uptime/issues", "_blank", "noreferrer" - ) - : navigate(`/${item.path}`) + ); + } + else if(item.path === "docs"){ + window.open( + "https://bluewavelabs.gitbook.io/uptime-manager", + "_blank", + "noreferrer" + ) + } + else if(item.path === "changelog"){ + window.open( + "https://github.com/bluewave-labs/bluewave-uptime/releases", + "_blank", + "noreferrer" + ) + } + else{ + navigate(`/${item.path}`) + } + } } sx={{ gap: theme.spacing(4), diff --git a/Client/src/assets/icons/changeLog.svg b/Client/src/assets/icons/changeLog.svg new file mode 100644 index 000000000..d12f6c10e --- /dev/null +++ b/Client/src/assets/icons/changeLog.svg @@ -0,0 +1,3 @@ + + + diff --git a/Client/src/assets/icons/docs.svg b/Client/src/assets/icons/docs.svg new file mode 100644 index 000000000..d36458de2 --- /dev/null +++ b/Client/src/assets/icons/docs.svg @@ -0,0 +1,3 @@ + + + From bb5a1959d0062c538b0710d6261e769c99dd0a77 Mon Sep 17 00:00:00 2001 From: Abhimanue Date: Sun, 13 Oct 2024 10:36:00 +0530 Subject: [PATCH 087/108] refractor code --- Client/src/Components/Sidebar/index.jsx | 42 +++++++++---------------- 1 file changed, 14 insertions(+), 28 deletions(-) diff --git a/Client/src/Components/Sidebar/index.jsx b/Client/src/Components/Sidebar/index.jsx index bb2097944..be7689235 100644 --- a/Client/src/Components/Sidebar/index.jsx +++ b/Client/src/Components/Sidebar/index.jsx @@ -71,12 +71,18 @@ const menu = [ ]; const other = [ - { name: "Support", path: "support", icon: }, { name: "Settings", path: "settings", icon: }, + { name: "Support", path: "support", icon: }, { name: "Docs", path: "docs", icon: }, { name: "Changelog", path: "changelog", icon: }, ]; +const URL_MAP = { + support: "https://github.com/bluewave-labs/bluewave-uptime/issues", + docs: "https://bluewavelabs.gitbook.io/uptime-manager", + changelog: "https://github.com/bluewave-labs/bluewave-uptime/releases", +}; + /** * @component * Sidebar component serves as a sidebar containing a menu. @@ -502,34 +508,14 @@ function Sidebar() { className={ location.pathname.includes(item.path) ? "selected-path" : "" } - onClick={ - () => { - if (item.path === "support") { - window.open( - "https://github.com/bluewave-labs/bluewave-uptime/issues", - "_blank", - "noreferrer" - ); - } - else if(item.path === "docs"){ - window.open( - "https://bluewavelabs.gitbook.io/uptime-manager", - "_blank", - "noreferrer" - ) - } - else if(item.path === "changelog"){ - window.open( - "https://github.com/bluewave-labs/bluewave-uptime/releases", - "_blank", - "noreferrer" - ) - } - else{ - navigate(`/${item.path}`) - } + onClick={() => { + const url = URL_MAP[item.path]; + if (url) { + window.open(url, "_blank", "noreferrer"); + } else { + navigate(`/${item.path}`); } - } + }} sx={{ gap: theme.spacing(4), borderRadius: theme.shape.borderRadius, From 13e3cd6391676dd87a1e73c88f86e1a5264e40c7 Mon Sep 17 00:00:00 2001 From: Rishav Date: Mon, 14 Oct 2024 02:08:14 +0530 Subject: [PATCH 088/108] added check for null value --- Client/src/Components/TabPanels/Account/TeamPanel.jsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Client/src/Components/TabPanels/Account/TeamPanel.jsx b/Client/src/Components/TabPanels/Account/TeamPanel.jsx index ac55cd5b1..23aa0008c 100644 --- a/Client/src/Components/TabPanels/Account/TeamPanel.jsx +++ b/Client/src/Components/TabPanels/Account/TeamPanel.jsx @@ -172,6 +172,10 @@ const TeamPanel = () => { }; const handleInviteMember = async () => { + if (!toInvite.email) { + setErrors((prev) => ({ ...prev, email: "Email is required." })); + return; + } setIsSendingInvite(true); if (!toInvite.role.includes("user") || !toInvite.role.includes("admin")) setToInvite((prev) => ({ ...prev, role: ["user"] })); From a0b651fd24119e4c8c2e797670acb2bd0e845171 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 09:43:47 +0800 Subject: [PATCH 089/108] Added getMoniotrsByTeamId tests --- Server/controllers/monitorController.js | 2 +- .../controllers/monitorController.test.js | 54 +++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/Server/controllers/monitorController.js b/Server/controllers/monitorController.js index 52a60307d..06800d5fc 100644 --- a/Server/controllers/monitorController.js +++ b/Server/controllers/monitorController.js @@ -208,7 +208,7 @@ const getMonitorsByTeamId = async (req, res, next) => { try { const teamId = req.params.teamId; const monitors = await req.db.getMonitorsByTeamId(req, res); - return res.json({ + return res.status(200).json({ success: true, msg: successMessages.MONITOR_GET_BY_USER_ID(teamId), data: monitors, diff --git a/Server/tests/controllers/monitorController.test.js b/Server/tests/controllers/monitorController.test.js index 971ee3c63..636c2beb9 100644 --- a/Server/tests/controllers/monitorController.test.js +++ b/Server/tests/controllers/monitorController.test.js @@ -321,3 +321,57 @@ describe("Monitor Controller - getMonitorsAndSummaryByTeamId", () => { ).to.be.true; }); }); + +describe("Monitor Controller - getMonitorsByTeamId", () => { + beforeEach(() => { + req = { + params: { + teamId: "123", + }, + query: {}, + body: {}, + db: { + getMonitorsByTeamId: sinon.stub(), + }, + }; + res = { + status: sinon.stub().returnsThis(), + json: sinon.stub(), + }; + next = sinon.stub(); + }); + afterEach(() => { + sinon.restore(); + }); + it("should reject with an error if param validation fails", async () => { + req.params = {}; + await getMonitorsByTeamId(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(422); + }); + it("should reject with an error if query validation fails", async () => { + req.query = { invalid: 1 }; + await getMonitorsByTeamId(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(422); + }); + it("should reject with an error if DB operations fail", async () => { + req.db.getMonitorsByTeamId.throws(new Error("DB error")); + await getMonitorsByTeamId(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("DB error"); + }); + it("should return success message and data if all operations succeed", async () => { + const data = { monitors: "data" }; + req.db.getMonitorsByTeamId.returns(data); + await getMonitorsByTeamId(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(200); + expect( + res.json.calledOnceWith({ + success: true, + msg: successMessages.MONITOR_GET_BY_USER_ID(req.params.teamId), + data: data, + }) + ).to.be.true; + }); +}); From 5d1ad0d92f51552ddc9c2c58f350f90f800554a4 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 09:53:08 +0800 Subject: [PATCH 090/108] Add tests for createMonitor --- .../controllers/monitorController.test.js | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/Server/tests/controllers/monitorController.test.js b/Server/tests/controllers/monitorController.test.js index 636c2beb9..3b6f57275 100644 --- a/Server/tests/controllers/monitorController.test.js +++ b/Server/tests/controllers/monitorController.test.js @@ -375,3 +375,64 @@ describe("Monitor Controller - getMonitorsByTeamId", () => { ).to.be.true; }); }); + +describe("Monitor Controller - createMonitor", () => { + beforeEach(() => { + req = { + params: {}, + query: {}, + body: { + userId: "123", + teamId: "123", + name: "test_monitor", + description: "test_monitor_desc", + type: "http", + url: "https://example.com", + notifications: [{ email: "example@example.com" }], + }, + db: { + createMonitor: sinon.stub(), + createNotification: sinon.stub(), + }, + }; + res = { + status: sinon.stub().returnsThis(), + json: sinon.stub(), + }; + next = sinon.stub(); + monitor = { + save: sinon.stub(), + }; + }); + afterEach(() => { + sinon.restore(); + }); + it("should reject with an error if body validation fails", async () => { + req.body = {}; + await createMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(422); + }); + it("should reject with an error if DB createMonitor operation fail", async () => { + req.db.createMonitor.throws(new Error("DB error")); + await createMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("DB error"); + }); + it("should reject with an error if DB createNotification operation fail", async () => { + req.db.createNotification.throws(new Error("DB error")); + req.db.createMonitor.returns({ _id: "123" }); + await createMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("DB error"); + }); + it("should reject with an error if DB createNotification operation fail", async () => { + req.db.createMonitor.returns({ + _id: "123", + save: sinon.stub().throws(new Error("DB error")), + }); + await createMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("DB error"); + }); +}); From 9daa6807019da23dd9bac0ad5303c34589c472e7 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 10:13:54 +0800 Subject: [PATCH 091/108] Add tests for deleteMonitor --- .../controllers/monitorController.test.js | 123 +++++++++++++++++- 1 file changed, 120 insertions(+), 3 deletions(-) diff --git a/Server/tests/controllers/monitorController.test.js b/Server/tests/controllers/monitorController.test.js index 3b6f57275..2a2e6d040 100644 --- a/Server/tests/controllers/monitorController.test.js +++ b/Server/tests/controllers/monitorController.test.js @@ -20,6 +20,8 @@ const sslCheckerStub = sinon.stub(); const monitorController = proxyquire("../../controllers/monitorController", { "ssl-checker": sslCheckerStub, }); +const logger = require("../../utils/logger"); +const SERVICE_NAME = "monitorController"; describe("Monitor Controller - getAllMonitors", () => { beforeEach(() => { @@ -400,9 +402,6 @@ describe("Monitor Controller - createMonitor", () => { json: sinon.stub(), }; next = sinon.stub(); - monitor = { - save: sinon.stub(), - }; }); afterEach(() => { sinon.restore(); @@ -436,3 +435,121 @@ describe("Monitor Controller - createMonitor", () => { expect(next.firstCall.args[0].message).to.equal("DB error"); }); }); + +describe("Monitor Controller - deleteMonitor", () => { + beforeEach(() => { + req = { + params: { + monitorId: "123", + }, + query: {}, + body: {}, + db: { + deleteMonitor: sinon.stub(), + deleteChecks: sinon.stub(), + deletePageSpeedChecksByMonitorId: sinon.stub(), + deleteNotificationsByMonitorId: sinon.stub(), + }, + jobQueue: { + deleteJob: sinon.stub(), + }, + }; + res = { + status: sinon.stub().returnsThis(), + json: sinon.stub(), + }; + next = sinon.stub(); + sinon.stub(logger, "error"); + }); + afterEach(() => { + sinon.restore(); + }); + it("should reject with an error if param validation fails", async () => { + req.params = {}; + await deleteMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(422); + }); + it("should reject with an error if DB deleteMonitor operation fail", async () => { + req.db.deleteMonitor.throws(new Error("DB error")); + await deleteMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("DB error"); + }); + it("should log an error if deleteJob throws an error", async () => { + const error = new Error("Job error"); + const monitor = { name: "test_monitor", _id: "123" }; + req.db.deleteMonitor.returns(monitor); + req.jobQueue.deleteJob.rejects(error); + await monitorController.deleteMonitor(req, res, next); + expect(logger.error.calledOnce).to.be.true; + expect(logger.error.firstCall.args[0]).to.equal( + `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}` + ); + expect(logger.error.firstCall.args[1]).to.deep.equal({ + method: "deleteMonitor", + service: SERVICE_NAME, + error: error.message, + }); + }); + it("should log an error if deleteChecks throws an error", async () => { + const error = new Error("Checks error"); + const monitor = { name: "test_monitor", _id: "123" }; + req.db.deleteMonitor.returns(monitor); + req.db.deleteChecks.rejects(error); + await monitorController.deleteMonitor(req, res, next); + expect(logger.error.calledOnce).to.be.true; + expect(logger.error.firstCall.args[0]).to.equal( + `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}` + ); + expect(logger.error.firstCall.args[1]).to.deep.equal({ + method: "deleteMonitor", + service: SERVICE_NAME, + error: error.message, + }); + }); + it("should log an error if deletePageSpeedChecksByMonitorId throws an error", async () => { + const error = new Error("PageSpeed error"); + const monitor = { name: "test_monitor", _id: "123" }; + req.db.deleteMonitor.returns(monitor); + req.db.deletePageSpeedChecksByMonitorId.rejects(error); + await monitorController.deleteMonitor(req, res, next); + expect(logger.error.calledOnce).to.be.true; + expect(logger.error.firstCall.args[0]).to.equal( + `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}` + ); + expect(logger.error.firstCall.args[1]).to.deep.equal({ + method: "deleteMonitor", + service: SERVICE_NAME, + error: error.message, + }); + }); + it("should log an error if deleteNotificationsByMonitorId throws an error", async () => { + const error = new Error("Notifications error"); + const monitor = { name: "test_monitor", _id: "123" }; + req.db.deleteMonitor.returns(monitor); + req.db.deleteNotificationsByMonitorId.rejects(error); + await monitorController.deleteMonitor(req, res, next); + expect(logger.error.calledOnce).to.be.true; + expect(logger.error.firstCall.args[0]).to.equal( + `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}` + ); + expect(logger.error.firstCall.args[1]).to.deep.equal({ + method: "deleteMonitor", + service: SERVICE_NAME, + error: error.message, + }); + }); + it("should return success message if all operations succeed", async () => { + const monitor = { name: "test_monitor", _id: "123" }; + req.db.deleteMonitor.returns(monitor); + await monitorController.deleteMonitor(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(200); + expect( + res.json.calledOnceWith({ + success: true, + msg: successMessages.MONITOR_DELETE, + }) + ).to.be.true; + }); +}); From bdde060f7f8a1c7f62f25c5cabd68a17080ab5f7 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 11:06:45 +0800 Subject: [PATCH 092/108] Add tests for deleteAllMonitors --- Server/controllers/controllerUtils.js | 4 +- Server/controllers/monitorController.js | 25 ++-- .../controllers/monitorController.test.js | 108 ++++++++++++++++++ 3 files changed, 127 insertions(+), 10 deletions(-) diff --git a/Server/controllers/controllerUtils.js b/Server/controllers/controllerUtils.js index 1b3994f2f..3238cd2a1 100644 --- a/Server/controllers/controllerUtils.js +++ b/Server/controllers/controllerUtils.js @@ -6,8 +6,8 @@ const handleValidationError = (error, serviceName) => { return error; }; -const handleError = (error, serviceName, method, code = 500) => { - error.code === undefined ? (error.code = code) : null; +const handleError = (error, serviceName, method, status = 500) => { + error.status === undefined ? (error.status = status) : null; error.service === undefined ? (error.service = serviceName) : null; error.method === undefined ? (error.method = method) : null; return error; diff --git a/Server/controllers/monitorController.js b/Server/controllers/monitorController.js index 06800d5fc..99d86a947 100644 --- a/Server/controllers/monitorController.js +++ b/Server/controllers/monitorController.js @@ -325,14 +325,23 @@ const deleteAllMonitors = async (req, res, next) => { const { jwtSecret } = req.settingsService.getSettings(); const { teamId } = jwt.verify(token, jwtSecret); const { monitors, deletedCount } = await req.db.deleteAllMonitors(teamId); - await monitors.forEach(async (monitor) => { - await req.jobQueue.deleteJob(monitor); - await req.db.deleteChecks(monitor._id); - await req.db.deleteAlertByMonitorId(monitor._id); - await req.db.deletePageSpeedChecksByMonitorId(monitor._id); - await req.db.deleteNotificationsByMonitorId(monitor._id); - }); - + await Promise.all( + monitors.map(async (monitor) => { + try { + await req.jobQueue.deleteJob(monitor); + await req.db.deleteChecks(monitor._id); + await req.db.deletePageSpeedChecksByMonitorId(monitor._id); + await req.db.deleteNotificationsByMonitorId(monitor._id); + } catch (error) { + logger.error( + `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`, + { + method: "deleteAllMonitors", + } + ); + } + }) + ); return res .status(200) .json({ success: true, msg: `Deleted ${deletedCount} monitors` }); diff --git a/Server/tests/controllers/monitorController.test.js b/Server/tests/controllers/monitorController.test.js index 2a2e6d040..d2c77bc9d 100644 --- a/Server/tests/controllers/monitorController.test.js +++ b/Server/tests/controllers/monitorController.test.js @@ -553,3 +553,111 @@ describe("Monitor Controller - deleteMonitor", () => { ).to.be.true; }); }); + +describe("Monitor Controller - deleteAllMonitors", () => { + beforeEach(() => { + stub = sinon.stub(jwt, "verify").callsFake(() => { + return { teamId: "123" }; + }); + req = { + headers: { + authorization: "Bearer token", + }, + params: { + monitorId: "123", + }, + query: {}, + body: {}, + db: { + deleteAllMonitors: sinon.stub(), + deleteChecks: sinon.stub(), + deletePageSpeedChecksByMonitorId: sinon.stub(), + deleteNotificationsByMonitorId: sinon.stub(), + }, + jobQueue: { + deleteJob: sinon.stub(), + }, + settingsService: { + getSettings: sinon.stub(), + }, + }; + res = { + status: sinon.stub().returnsThis(), + json: sinon.stub(), + }; + next = sinon.stub(); + sinon.stub(logger, "error"); + }); + afterEach(() => { + sinon.restore(); + stub.restore(); + }); + it("should reject with an error if getTokenFromHeaders throws an error", async () => { + req.headers = {}; + await monitorController.deleteAllMonitors(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("No auth headers"); + expect(next.firstCall.args[0].status).to.equal(500); + }); + it("should reject with an error if token validation fails", async () => { + stub.restore(); + req.settingsService.getSettings.returns({ jwtSecret: "my_secret" }); + await monitorController.deleteAllMonitors(req, res, next); + expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError); + }); + it("should reject with an error if DB deleteAllMonitors operation fail", async () => { + req.settingsService.getSettings.returns({ jwtSecret: "my_secret" }); + req.db.deleteAllMonitors.throws(new Error("DB error")); + await monitorController.deleteAllMonitors(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("DB error"); + }); + it("should log an error if deleteJob throws an error", async () => { + const monitors = [{ name: "test_monitor", _id: "123" }]; + req.settingsService.getSettings.returns({ jwtSecret: "my_secret" }); + req.db.deleteAllMonitors.returns({ monitors, deletedCount: 1 }); + const error = new Error("Job error"); + req.jobQueue.deleteJob.rejects(error); + await monitorController.deleteAllMonitors(req, res, next); + expect(logger.error.calledOnce).to.be.true; + expect(logger.error.firstCall.args[0]).to.deep.equal( + `Error deleting associated records for monitor ${monitors[0]._id} with name ${monitors[0].name}` + ); + }); + it("should log an error if deleteChecks throws an error", async () => { + const monitors = [{ name: "test_monitor", _id: "123" }]; + req.settingsService.getSettings.returns({ jwtSecret: "my_secret" }); + req.db.deleteAllMonitors.returns({ monitors, deletedCount: 1 }); + const error = new Error("Check error"); + req.db.deleteChecks.rejects(error); + await monitorController.deleteAllMonitors(req, res, next); + expect(logger.error.calledOnce).to.be.true; + expect(logger.error.firstCall.args[0]).to.deep.equal( + `Error deleting associated records for monitor ${monitors[0]._id} with name ${monitors[0].name}` + ); + }); + it("should log an error if deletePageSpeedChecksByMonitorId throws an error", async () => { + const monitors = [{ name: "test_monitor", _id: "123" }]; + req.settingsService.getSettings.returns({ jwtSecret: "my_secret" }); + req.db.deleteAllMonitors.returns({ monitors, deletedCount: 1 }); + const error = new Error("Pagespeed Check error"); + req.db.deletePageSpeedChecksByMonitorId.rejects(error); + await monitorController.deleteAllMonitors(req, res, next); + expect(logger.error.calledOnce).to.be.true; + expect(logger.error.firstCall.args[0]).to.deep.equal( + `Error deleting associated records for monitor ${monitors[0]._id} with name ${monitors[0].name}` + ); + }); + it("should log an error if deleteNotificationsByMonitorId throws an error", async () => { + const monitors = [{ name: "test_monitor", _id: "123" }]; + req.settingsService.getSettings.returns({ jwtSecret: "my_secret" }); + req.db.deleteAllMonitors.returns({ monitors, deletedCount: 1 }); + const error = new Error("Notifications Check error"); + req.db.deleteNotificationsByMonitorId.rejects(error); + await monitorController.deleteAllMonitors(req, res, next); + expect(logger.error.calledOnce).to.be.true; + expect(logger.error.firstCall.args[0]).to.deep.equal( + `Error deleting associated records for monitor ${monitors[0]._id} with name ${monitors[0].name}` + ); + }); +}); From 2cf4c93cb06fedf97624ac0c254644ad011514f0 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 11:18:23 +0800 Subject: [PATCH 093/108] Add tests for editMonitor --- .../controllers/monitorController.test.js | 107 ++++++++++++++++++ 1 file changed, 107 insertions(+) diff --git a/Server/tests/controllers/monitorController.test.js b/Server/tests/controllers/monitorController.test.js index d2c77bc9d..eab6ae9ea 100644 --- a/Server/tests/controllers/monitorController.test.js +++ b/Server/tests/controllers/monitorController.test.js @@ -661,3 +661,110 @@ describe("Monitor Controller - deleteAllMonitors", () => { ); }); }); + +describe("Monitor Controller - editMonitor", () => { + beforeEach(() => { + req = { + headers: {}, + params: { + monitorId: "123", + }, + query: {}, + body: { + notifications: [{ email: "example@example.com" }], + }, + db: { + getMonitorById: sinon.stub(), + editMonitor: sinon.stub(), + deleteNotificationsByMonitorId: sinon.stub(), + createNotification: sinon.stub(), + }, + jobQueue: { + deleteJob: sinon.stub(), + addJob: sinon.stub(), + }, + settingsService: { + getSettings: sinon.stub(), + }, + }; + res = { + status: sinon.stub().returnsThis(), + json: sinon.stub(), + }; + next = sinon.stub(); + }); + afterEach(() => { + sinon.restore(); + }); + it("should reject with an error if param validation fails", async () => { + req.params = {}; + await editMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(422); + }); + it("should reject with an error if body validation fails", async () => { + req.body = { invalid: 1 }; + await editMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(422); + }); + it("should reject with an error if getMonitorById operation fails", async () => { + req.db.getMonitorById.throws(new Error("DB error")); + await editMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("DB error"); + }); + it("should reject with an error if editMonitor operation fails", async () => { + req.db.getMonitorById.returns({ teamId: "123" }); + req.db.editMonitor.throws(new Error("DB error")); + await editMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("DB error"); + }); + it("should reject with an error if deleteNotificationsByMonitorId operation fails", async () => { + req.db.getMonitorById.returns({ teamId: "123" }); + req.db.editMonitor.returns({ _id: "123" }); + req.db.deleteNotificationsByMonitorId.throws(new Error("DB error")); + await editMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("DB error"); + }); + it("should reject with an error if createNotification operation fails", async () => { + req.db.getMonitorById.returns({ teamId: "123" }); + req.db.editMonitor.returns({ _id: "123" }); + req.db.createNotification.throws(new Error("DB error")); + await editMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("DB error"); + }); + it("should reject with an error if deleteJob operation fails", async () => { + req.db.getMonitorById.returns({ teamId: "123" }); + req.db.editMonitor.returns({ _id: "123" }); + req.jobQueue.deleteJob.throws(new Error("Job error")); + await editMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("Job error"); + }); + it("should reject with an error if addJob operation fails", async () => { + req.db.getMonitorById.returns({ teamId: "123" }); + req.db.editMonitor.returns({ _id: "123" }); + req.jobQueue.addJob.throws(new Error("Add Job error")); + await editMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("Add Job error"); + }); + it("should return success message with data if all operations succeed", async () => { + const monitor = { _id: "123" }; + req.db.getMonitorById.returns({ teamId: "123" }); + req.db.editMonitor.returns(monitor); + await editMonitor(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(200); + expect( + res.json.calledOnceWith({ + success: true, + msg: successMessages.MONITOR_EDIT, + data: monitor, + }) + ).to.be.true; + }); +}); From 516212b1b0af9d785ccf2b9e49072f4fa1563fdd Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 11:29:04 +0800 Subject: [PATCH 094/108] Add tests for pauseMonitor method --- .../controllers/monitorController.test.js | 106 ++++++++++++++++++ 1 file changed, 106 insertions(+) diff --git a/Server/tests/controllers/monitorController.test.js b/Server/tests/controllers/monitorController.test.js index eab6ae9ea..86bfb4e3c 100644 --- a/Server/tests/controllers/monitorController.test.js +++ b/Server/tests/controllers/monitorController.test.js @@ -768,3 +768,109 @@ describe("Monitor Controller - editMonitor", () => { ).to.be.true; }); }); + +describe("Monitor Controller - pauseMonitor", () => { + beforeEach(() => { + req = { + headers: {}, + params: { + monitorId: "123", + }, + query: {}, + body: {}, + db: { + getMonitorById: sinon.stub(), + }, + jobQueue: { + deleteJob: sinon.stub(), + addJob: sinon.stub(), + }, + settingsService: { + getSettings: sinon.stub(), + }, + }; + res = { + status: sinon.stub().returnsThis(), + json: sinon.stub(), + }; + next = sinon.stub(); + }); + afterEach(() => { + sinon.restore(); + }); + + it("should reject with an error if param validation fails", async () => { + req.params = {}; + await pauseMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(422); + }); + it("should reject with an error if getMonitorById operation fails", async () => { + req.db.getMonitorById.throws(new Error("DB error")); + await pauseMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("DB error"); + }); + "it should reject with an error if deleteJob operation fails", + async () => { + const monitor = { _id: req.params.monitorId, active: true }; + req.db.getMonitorById.returns(monitor); + req.jobQueue.deleteJob.throws(new Error("Delete Job error")); + await pauseMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("Delete Job error"); + }; + it("should reject with an error if addJob operation fails", async () => { + const monitor = { _id: req.params.monitorId, active: false }; + req.db.getMonitorById.returns(monitor); + req.jobQueue.addJob.throws(new Error("Add Job error")); + await pauseMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("Add Job error"); + }); + it("should reject with an error if monitor.save operation fails", async () => { + const monitor = { + _id: req.params.monitorId, + active: false, + save: sinon.stub().throws(new Error("Save error")), + }; + req.db.getMonitorById.returns(monitor); + await pauseMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("Save error"); + }); + it("should return success pause message with data if all operations succeed with inactive monitor", async () => { + const monitor = { + _id: req.params.monitorId, + active: false, + save: sinon.stub().resolves(), + }; + req.db.getMonitorById.returns(monitor); + await pauseMonitor(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(200); + expect( + res.json.calledOnceWith({ + success: true, + msg: successMessages.MONITOR_PAUSE, + data: monitor, + }) + ).to.be.true; + }); + it("should return success resume message with data if all operations succeed with active monitor", async () => { + const monitor = { + _id: req.params.monitorId, + active: true, + save: sinon.stub().resolves(), + }; + req.db.getMonitorById.returns(monitor); + await pauseMonitor(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(200); + expect( + res.json.calledOnceWith({ + success: true, + msg: successMessages.MONITOR_RESUME, + data: monitor, + }) + ).to.be.true; + }); +}); From 607b16d1cd5bdf3d9d7ef0136f16ca2a666079e9 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 11:36:49 +0800 Subject: [PATCH 095/108] Add tests for addDemoMonitors --- Server/controllers/monitorController.js | 2 +- .../controllers/monitorController.test.js | 82 +++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/Server/controllers/monitorController.js b/Server/controllers/monitorController.js index 99d86a947..9ef90fa4b 100644 --- a/Server/controllers/monitorController.js +++ b/Server/controllers/monitorController.js @@ -469,7 +469,7 @@ const addDemoMonitors = async (req, res, next) => { return res.status(200).json({ success: true, - message: successMessages.MONITOR_DEMO_ADDED, + msg: successMessages.MONITOR_DEMO_ADDED, data: demoMonitors.length, }); } catch (error) { diff --git a/Server/tests/controllers/monitorController.test.js b/Server/tests/controllers/monitorController.test.js index 86bfb4e3c..7e6b4fd8f 100644 --- a/Server/tests/controllers/monitorController.test.js +++ b/Server/tests/controllers/monitorController.test.js @@ -874,3 +874,85 @@ describe("Monitor Controller - pauseMonitor", () => { ).to.be.true; }); }); + +describe("Monitor Controller - addDemoMonitors", () => { + beforeEach(() => { + stub = sinon.stub(jwt, "verify").callsFake(() => { + return { _id: "123", teamId: "123" }; + }); + req = { + headers: { + authorization: "Bearer token", + }, + params: {}, + query: {}, + body: {}, + db: { + addDemoMonitors: sinon.stub(), + }, + settingsService: { + getSettings: sinon.stub(), + }, + jobQueue: { + addJob: sinon.stub(), + }, + }; + res = { + status: sinon.stub().returnsThis(), + json: sinon.stub(), + }; + next = sinon.stub(); + }); + afterEach(() => { + sinon.restore(); + stub.restore(); + }); + it("should reject with an error if getTokenFromHeaders fails", async () => { + req.headers = {}; + await addDemoMonitors(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("No auth headers"); + expect(next.firstCall.args[0].status).to.equal(500); + }); + it("should reject with an error if getting settings fails", async () => { + req.settingsService.getSettings.throws(new Error("Settings error")); + await addDemoMonitors(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("Settings error"); + }); + it("should reject with an error if JWT validation fails", async () => { + stub.restore(); + req.settingsService.getSettings.returns({ jwtSecret: "my_secret" }); + await addDemoMonitors(req, res, next); + expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError); + }); + it("should reject with an error if addDemoMonitors operation fails", async () => { + req.settingsService.getSettings.returns({ jwtSecret: "my_secret" }); + req.db.addDemoMonitors.throws(new Error("DB error")); + await addDemoMonitors(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("DB error"); + }); + it("should reject with an error if addJob operation fails", async () => { + req.settingsService.getSettings.returns({ jwtSecret: "my_secret" }); + req.db.addDemoMonitors.returns([{ _id: "123" }]); + req.jobQueue.addJob.throws(new Error("Add Job error")); + await addDemoMonitors(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("Add Job error"); + }); + it("should return success message with data if all operations succeed", async () => { + const monitors = [{ _id: "123" }]; + req.settingsService.getSettings.returns({ jwtSecret: "my_secret" }); + req.db.addDemoMonitors.returns(monitors); + await addDemoMonitors(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(200); + expect( + res.json.calledOnceWith({ + success: true, + msg: successMessages.MONITOR_DEMO_ADDED, + data: monitors.length, + }) + ).to.be.true; + }); +}); From 27d5bce9e3db7ce1e0db47b9b219b6d4300757ed Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 11:57:39 +0800 Subject: [PATCH 096/108] Add tests for complete coverage, fix active -> isActive --- .../tests/controllers/controllerUtils.test.js | 18 ++-- .../controllers/monitorController.test.js | 82 +++++++++++++++---- 2 files changed, 76 insertions(+), 24 deletions(-) diff --git a/Server/tests/controllers/controllerUtils.test.js b/Server/tests/controllers/controllerUtils.test.js index c18570a5f..71d134bb6 100644 --- a/Server/tests/controllers/controllerUtils.test.js +++ b/Server/tests/controllers/controllerUtils.test.js @@ -45,22 +45,22 @@ describe("controllerUtils - handleValidationError", () => { }); describe("handleError", () => { - it("should set code to the provided code if error.code is undefined", () => { + it("should set stats to the provided status if error.code is undefined", () => { const error = {}; const serviceName = "TestService"; const method = "testMethod"; - const code = 400; - const result = handleError(error, serviceName, method, code); - expect(result.code).to.equal(code); + const status = 400; + const result = handleError(error, serviceName, method, status); + expect(result.status).to.equal(status); }); it("should not overwrite error.code if it is already defined", () => { - const error = { code: 404 }; + const error = { status: 404 }; const serviceName = "TestService"; const method = "testMethod"; - const code = 400; - const result = handleError(error, serviceName, method, code); - expect(result.code).to.equal(404); + const status = 400; + const result = handleError(error, serviceName, method, status); + expect(result.status).to.equal(404); }); it("should set service to the provided serviceName if error.service is undefined", () => { @@ -100,6 +100,6 @@ describe("handleError", () => { const serviceName = "TestService"; const method = "testMethod"; const result = handleError(error, serviceName, method); - expect(result.code).to.equal(500); + expect(result.status).to.equal(500); }); }); diff --git a/Server/tests/controllers/monitorController.test.js b/Server/tests/controllers/monitorController.test.js index 7e6b4fd8f..12d97702c 100644 --- a/Server/tests/controllers/monitorController.test.js +++ b/Server/tests/controllers/monitorController.test.js @@ -396,6 +396,9 @@ describe("Monitor Controller - createMonitor", () => { createMonitor: sinon.stub(), createNotification: sinon.stub(), }, + jobQueue: { + addJob: sinon.stub(), + }, }; res = { status: sinon.stub().returnsThis(), @@ -425,14 +428,48 @@ describe("Monitor Controller - createMonitor", () => { expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0].message).to.equal("DB error"); }); - it("should reject with an error if DB createNotification operation fail", async () => { + it("should reject with an error if monitor.save operation fail", async () => { req.db.createMonitor.returns({ _id: "123", - save: sinon.stub().throws(new Error("DB error")), + save: sinon.stub().throws(new Error("Monitor save error")), }); await createMonitor(req, res, next); expect(next.firstCall.args[0]).to.be.an("error"); - expect(next.firstCall.args[0].message).to.equal("DB error"); + expect(next.firstCall.args[0].message).to.equal("Monitor save error"); + }); + it("should throw an error if addJob operation fails", async () => { + req.db.createMonitor.returns({ _id: "123", save: sinon.stub() }); + req.jobQueue.addJob.throws(new Error("Job error")); + await createMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("Job error"); + }); + it("should return success message and data if all operations succeed with empty notifications", async () => { + req.body.notifications = []; + const monitor = { _id: "123", save: sinon.stub() }; + req.db.createMonitor.returns(monitor); + await createMonitor(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(201); + expect( + res.json.calledOnceWith({ + success: true, + msg: successMessages.MONITOR_CREATE, + data: monitor, + }) + ).to.be.true; + }); + it("should return success message and data if all operations succeed", async () => { + const monitor = { _id: "123", save: sinon.stub() }; + req.db.createMonitor.returns(monitor); + await createMonitor(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(201); + expect( + res.json.calledOnceWith({ + success: true, + msg: successMessages.MONITOR_CREATE, + data: monitor, + }) + ).to.be.true; }); }); @@ -753,6 +790,21 @@ describe("Monitor Controller - editMonitor", () => { expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0].message).to.equal("Add Job error"); }); + it("should return success message with data if all operations succeed and empty notifications", async () => { + req.body.notifications = []; + const monitor = { _id: "123" }; + req.db.getMonitorById.returns({ teamId: "123" }); + req.db.editMonitor.returns(monitor); + await editMonitor(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(200); + expect( + res.json.calledOnceWith({ + success: true, + msg: successMessages.MONITOR_EDIT, + data: monitor, + }) + ).to.be.true; + }); it("should return success message with data if all operations succeed", async () => { const monitor = { _id: "123" }; req.db.getMonitorById.returns({ teamId: "123" }); @@ -811,17 +863,17 @@ describe("Monitor Controller - pauseMonitor", () => { expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0].message).to.equal("DB error"); }); - "it should reject with an error if deleteJob operation fails", - async () => { - const monitor = { _id: req.params.monitorId, active: true }; - req.db.getMonitorById.returns(monitor); - req.jobQueue.deleteJob.throws(new Error("Delete Job error")); - await pauseMonitor(req, res, next); - expect(next.firstCall.args[0]).to.be.an("error"); - expect(next.firstCall.args[0].message).to.equal("Delete Job error"); - }; + it("should reject with an error if deleteJob operation fails", async () => { + const monitor = { _id: req.params.monitorId, isActive: true }; + req.db.getMonitorById.returns(monitor); + req.jobQueue.deleteJob.throws(new Error("Delete Job error")); + await pauseMonitor(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("Delete Job error"); + }); + it("should reject with an error if addJob operation fails", async () => { - const monitor = { _id: req.params.monitorId, active: false }; + const monitor = { _id: req.params.monitorId, isActive: false }; req.db.getMonitorById.returns(monitor); req.jobQueue.addJob.throws(new Error("Add Job error")); await pauseMonitor(req, res, next); @@ -842,7 +894,7 @@ describe("Monitor Controller - pauseMonitor", () => { it("should return success pause message with data if all operations succeed with inactive monitor", async () => { const monitor = { _id: req.params.monitorId, - active: false, + isActive: false, save: sinon.stub().resolves(), }; req.db.getMonitorById.returns(monitor); @@ -859,7 +911,7 @@ describe("Monitor Controller - pauseMonitor", () => { it("should return success resume message with data if all operations succeed with active monitor", async () => { const monitor = { _id: req.params.monitorId, - active: true, + isActive: true, save: sinon.stub().resolves(), }; req.db.getMonitorById.returns(monitor); From 2ac60441a3cbff31b1fc545797ccf27fa4dec3bc Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 11:59:15 +0800 Subject: [PATCH 097/108] Fix deleteAllMonitors test --- Server/tests/controllers/monitorController.test.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Server/tests/controllers/monitorController.test.js b/Server/tests/controllers/monitorController.test.js index 12d97702c..e2855e81b 100644 --- a/Server/tests/controllers/monitorController.test.js +++ b/Server/tests/controllers/monitorController.test.js @@ -631,7 +631,7 @@ describe("Monitor Controller - deleteAllMonitors", () => { }); it("should reject with an error if getTokenFromHeaders throws an error", async () => { req.headers = {}; - await monitorController.deleteAllMonitors(req, res, next); + await deleteAllMonitors(req, res, next); expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0].message).to.equal("No auth headers"); expect(next.firstCall.args[0].status).to.equal(500); @@ -639,13 +639,13 @@ describe("Monitor Controller - deleteAllMonitors", () => { it("should reject with an error if token validation fails", async () => { stub.restore(); req.settingsService.getSettings.returns({ jwtSecret: "my_secret" }); - await monitorController.deleteAllMonitors(req, res, next); + await deleteAllMonitors(req, res, next); expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError); }); it("should reject with an error if DB deleteAllMonitors operation fail", async () => { req.settingsService.getSettings.returns({ jwtSecret: "my_secret" }); req.db.deleteAllMonitors.throws(new Error("DB error")); - await monitorController.deleteAllMonitors(req, res, next); + await deleteAllMonitors(req, res, next); expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0].message).to.equal("DB error"); }); @@ -655,7 +655,7 @@ describe("Monitor Controller - deleteAllMonitors", () => { req.db.deleteAllMonitors.returns({ monitors, deletedCount: 1 }); const error = new Error("Job error"); req.jobQueue.deleteJob.rejects(error); - await monitorController.deleteAllMonitors(req, res, next); + await deleteAllMonitors(req, res, next); expect(logger.error.calledOnce).to.be.true; expect(logger.error.firstCall.args[0]).to.deep.equal( `Error deleting associated records for monitor ${monitors[0]._id} with name ${monitors[0].name}` @@ -667,7 +667,7 @@ describe("Monitor Controller - deleteAllMonitors", () => { req.db.deleteAllMonitors.returns({ monitors, deletedCount: 1 }); const error = new Error("Check error"); req.db.deleteChecks.rejects(error); - await monitorController.deleteAllMonitors(req, res, next); + await deleteAllMonitors(req, res, next); expect(logger.error.calledOnce).to.be.true; expect(logger.error.firstCall.args[0]).to.deep.equal( `Error deleting associated records for monitor ${monitors[0]._id} with name ${monitors[0].name}` @@ -679,7 +679,7 @@ describe("Monitor Controller - deleteAllMonitors", () => { req.db.deleteAllMonitors.returns({ monitors, deletedCount: 1 }); const error = new Error("Pagespeed Check error"); req.db.deletePageSpeedChecksByMonitorId.rejects(error); - await monitorController.deleteAllMonitors(req, res, next); + await deleteAllMonitors(req, res, next); expect(logger.error.calledOnce).to.be.true; expect(logger.error.firstCall.args[0]).to.deep.equal( `Error deleting associated records for monitor ${monitors[0]._id} with name ${monitors[0].name}` @@ -691,7 +691,7 @@ describe("Monitor Controller - deleteAllMonitors", () => { req.db.deleteAllMonitors.returns({ monitors, deletedCount: 1 }); const error = new Error("Notifications Check error"); req.db.deleteNotificationsByMonitorId.rejects(error); - await monitorController.deleteAllMonitors(req, res, next); + await deleteAllMonitors(req, res, next); expect(logger.error.calledOnce).to.be.true; expect(logger.error.firstCall.args[0]).to.deep.equal( `Error deleting associated records for monitor ${monitors[0]._id} with name ${monitors[0].name}` From 22ac0bebbb58c55d63acbc600f99294fd705681c Mon Sep 17 00:00:00 2001 From: Rishav Date: Mon, 14 Oct 2024 10:42:55 +0530 Subject: [PATCH 098/108] fixes --- Client/src/Components/TabPanels/Account/TeamPanel.jsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Client/src/Components/TabPanels/Account/TeamPanel.jsx b/Client/src/Components/TabPanels/Account/TeamPanel.jsx index 23aa0008c..e5fd5d02b 100644 --- a/Client/src/Components/TabPanels/Account/TeamPanel.jsx +++ b/Client/src/Components/TabPanels/Account/TeamPanel.jsx @@ -49,6 +49,7 @@ const TeamPanel = () => { const [tableData, setTableData] = useState({}); const [members, setMembers] = useState([]); const [filter, setFilter] = useState("all"); + const [isDisabled, setIsDisabled] = useState(true); const [errors, setErrors] = useState({}); const [isSendingInvite, setIsSendingInvite] = useState(false); @@ -137,6 +138,9 @@ const TeamPanel = () => { setTableData(data); }, [members, filter]); + useEffect(() => { + setIsDisabled(Object.keys(errors).length !== 0 || toInvite.email === ""); + }, [errors, toInvite.email]); // RENAME ORGANIZATION const toggleEdit = () => { @@ -419,7 +423,7 @@ const TeamPanel = () => { color="primary" onClick={handleInviteMember} loading={isSendingInvite} - disabled={Object.keys(errors).length !== 0} + disabled={isDisabled} > Send invite From ed3b00801608d77190a869b4ff43dd10b8fb8861 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 13:13:13 +0800 Subject: [PATCH 099/108] Add queue controller tests for getMetrics and getJobs --- Server/.nycrc | 2 +- Server/controllers/queueController.js | 18 +++++++++++++----- Server/utils/messages.js | 4 ++++ 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/Server/.nycrc b/Server/.nycrc index da9bccbfc..d6406bf7e 100644 --- a/Server/.nycrc +++ b/Server/.nycrc @@ -1,6 +1,6 @@ { "all": true, - "include": ["**/*.js"], + "include": ["controllers/*.js"], "exclude": ["**/*.test.js"], "reporter": ["html", "text", "lcov"], "sourceMap": false, diff --git a/Server/controllers/queueController.js b/Server/controllers/queueController.js index 341c4b76b..68ab7b28d 100644 --- a/Server/controllers/queueController.js +++ b/Server/controllers/queueController.js @@ -1,13 +1,15 @@ const { handleError } = require("./controllerUtils"); - +const { errorMessages, successMessages } = require("../utils/messages"); const SERVICE_NAME = "JobQueueController"; const getMetrics = async (req, res, next) => { try { const metrics = await req.jobQueue.getMetrics(); - res - .status(200) - .json({ success: true, msg: "Metrics retrieved", data: metrics }); + res.status(200).json({ + success: true, + msg: successMessages.QUEUE_GET_METRICS, + data: metrics, + }); } catch (error) { next(handleError(error, SERVICE_NAME, "getMetrics")); return; @@ -17,7 +19,13 @@ const getMetrics = async (req, res, next) => { const getJobs = async (req, res, next) => { try { const jobs = await req.jobQueue.getJobStats(); - return res.status(200).json({ jobs }); + return res + .status(200) + .json({ + success: true, + msg: successMessages.QUEUE_GET_METRICS, + data: jobs, + }); } catch (error) { next(handleError(error, SERVICE_NAME, "getJobs")); return; diff --git a/Server/utils/messages.js b/Server/utils/messages.js index 16b2f7883..c1df6af3b 100644 --- a/Server/utils/messages.js +++ b/Server/utils/messages.js @@ -86,6 +86,10 @@ const successMessages = { MONITOR_CERTIFICATE: "Got monitor certificate successfully", MONITOR_DEMO_ADDED: "Successfully added demo monitors", + // Queue Controller + QUEUE_GET_METRICS: "Got metrics successfully", + QUEUE_GET_METRICS: "Got job stats successfully", + //Job Queue JOB_QUEUE_DELETE_JOB: "Job removed successfully", JOB_QUEUE_OBLITERATE: "Queue OBLITERATED!!!", From 61518f898ba8132986dc907b2980fa468e031927 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 13:13:36 +0800 Subject: [PATCH 100/108] Add queue controller tests for getMetrics and getJobs --- .../tests/controllers/queueController.test.js | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Server/tests/controllers/queueController.test.js diff --git a/Server/tests/controllers/queueController.test.js b/Server/tests/controllers/queueController.test.js new file mode 100644 index 000000000..584f240fc --- /dev/null +++ b/Server/tests/controllers/queueController.test.js @@ -0,0 +1,92 @@ +const { afterEach } = require("node:test"); +const { + getMetrics, + getJobs, + addJob, + obliterateQueue, +} = require("../../controllers/queueController"); +const SERVICE_NAME = "JobQueueController"; + +const { errorMessages, successMessages } = require("../../utils/messages"); +const sinon = require("sinon"); + +describe("Queue Controller - getMetrics", () => { + beforeEach(() => { + req = { + headers: {}, + params: {}, + body: {}, + db: {}, + jobQueue: { + getMetrics: sinon.stub(), + }, + }; + res = { + status: sinon.stub().returnsThis(), + json: sinon.stub(), + }; + next = sinon.stub(); + handleError = sinon.stub(); + }); + afterEach(() => { + sinon.restore(); + }); + it("should throw an error if getMetrics throws an error", async () => { + req.jobQueue.getMetrics.throws(new Error("getMetrics error")); + await getMetrics(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("getMetrics error"); + }); + + it("should return a success message and data if getMetrics is successful", async () => { + const data = { data: "metrics" }; + req.jobQueue.getMetrics.returns(data); + await getMetrics(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(200); + expect(res.json.firstCall.args[0]).to.deep.equal({ + success: true, + msg: successMessages.QUEUE_GET_METRICS, + data, + }); + }); +}); + +describe("Queue Controller - getJobs", () => { + beforeEach(() => { + req = { + headers: {}, + params: {}, + body: {}, + db: {}, + jobQueue: { + getJobStats: sinon.stub(), + }, + }; + res = { + status: sinon.stub().returnsThis(), + json: sinon.stub(), + }; + next = sinon.stub(); + handleError = sinon.stub(); + }); + afterEach(() => { + sinon.restore(); + }); + it("should reject with an error if getJobs throws an error", async () => { + req.jobQueue.getJobStats.throws(new Error("getJobs error")); + await getJobs(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("getJobs error"); + }); + it("should return a success message and data if getJobs is successful", async () => { + const data = { data: "jobs" }; + req.jobQueue.getJobStats.returns(data); + await getJobs(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(200); + expect(res.json.firstCall.args[0]).to.deep.equal({ + success: true, + msg: successMessages.QUEUE_GET_METRICS, + data, + }); + }); +}); From b063fa267a72a935c348297ae7299a9e669e3285 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 13:17:08 +0800 Subject: [PATCH 101/108] add test for addJob --- Server/controllers/queueController.js | 17 +++++---- .../tests/controllers/queueController.test.js | 38 +++++++++++++++++++ Server/utils/messages.js | 2 + 3 files changed, 49 insertions(+), 8 deletions(-) diff --git a/Server/controllers/queueController.js b/Server/controllers/queueController.js index 68ab7b28d..c49e72c62 100644 --- a/Server/controllers/queueController.js +++ b/Server/controllers/queueController.js @@ -19,13 +19,11 @@ const getMetrics = async (req, res, next) => { const getJobs = async (req, res, next) => { try { const jobs = await req.jobQueue.getJobStats(); - return res - .status(200) - .json({ - success: true, - msg: successMessages.QUEUE_GET_METRICS, - data: jobs, - }); + return res.status(200).json({ + success: true, + msg: successMessages.QUEUE_GET_METRICS, + data: jobs, + }); } catch (error) { next(handleError(error, SERVICE_NAME, "getJobs")); return; @@ -35,7 +33,10 @@ const getJobs = async (req, res, next) => { const addJob = async (req, res, next) => { try { await req.jobQueue.addJob(Math.random().toString(36).substring(7)); - return res.send("Added job"); + return res.status(200).json({ + success: true, + msg: successMessages.QUEUE_ADD_JOB, + }); } catch (error) { next(handleError(error, SERVICE_NAME, "addJob")); return; diff --git a/Server/tests/controllers/queueController.test.js b/Server/tests/controllers/queueController.test.js index 584f240fc..8c0e66ab8 100644 --- a/Server/tests/controllers/queueController.test.js +++ b/Server/tests/controllers/queueController.test.js @@ -90,3 +90,41 @@ describe("Queue Controller - getJobs", () => { }); }); }); + +describe("Queue Controller - addJob", () => { + beforeEach(() => { + req = { + headers: {}, + params: {}, + body: {}, + db: {}, + jobQueue: { + addJob: sinon.stub(), + }, + }; + res = { + status: sinon.stub().returnsThis(), + json: sinon.stub(), + }; + next = sinon.stub(); + handleError = sinon.stub(); + }); + afterEach(() => { + sinon.restore(); + }); + it("should reject with an error if addJob throws an error", async () => { + req.jobQueue.addJob.throws(new Error("addJob error")); + await addJob(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("addJob error"); + }); + it("should return a success message if addJob is successful", async () => { + req.jobQueue.addJob.resolves(); + await addJob(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(200); + expect(res.json.firstCall.args[0]).to.deep.equal({ + success: true, + msg: successMessages.QUEUE_ADD_JOB, + }); + }); +}); diff --git a/Server/utils/messages.js b/Server/utils/messages.js index c1df6af3b..d685e7326 100644 --- a/Server/utils/messages.js +++ b/Server/utils/messages.js @@ -89,6 +89,8 @@ const successMessages = { // Queue Controller QUEUE_GET_METRICS: "Got metrics successfully", QUEUE_GET_METRICS: "Got job stats successfully", + QUEUE_ADD_JOB: "Job added successfully", + QUEUE_OBLITERATE: "Queue obliterated", //Job Queue JOB_QUEUE_DELETE_JOB: "Job removed successfully", From fde9303b8f2963650c0fa225f88c657d631278f2 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 13:23:40 +0800 Subject: [PATCH 102/108] Add tests for obliterate --- Server/controllers/queueController.js | 4 +- .../tests/controllers/queueController.test.js | 38 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/Server/controllers/queueController.js b/Server/controllers/queueController.js index c49e72c62..3151816be 100644 --- a/Server/controllers/queueController.js +++ b/Server/controllers/queueController.js @@ -46,7 +46,9 @@ const addJob = async (req, res, next) => { const obliterateQueue = async (req, res, next) => { try { await req.jobQueue.obliterate(); - return res.status(200).send("Obliterated queue"); + return res + .status(200) + .json({ success: true, msg: successMessages.QUEUE_OBLITERATE }); } catch (error) { next(handleError(error, SERVICE_NAME, "obliterateQueue")); return; diff --git a/Server/tests/controllers/queueController.test.js b/Server/tests/controllers/queueController.test.js index 8c0e66ab8..8099c3e7e 100644 --- a/Server/tests/controllers/queueController.test.js +++ b/Server/tests/controllers/queueController.test.js @@ -127,4 +127,42 @@ describe("Queue Controller - addJob", () => { msg: successMessages.QUEUE_ADD_JOB, }); }); + + describe("Queue Controller - obliterateQueue", () => { + beforeEach(() => { + req = { + headers: {}, + params: {}, + body: {}, + db: {}, + jobQueue: { + obliterate: sinon.stub(), + }, + }; + res = { + status: sinon.stub().returnsThis(), + json: sinon.stub(), + }; + next = sinon.stub(); + handleError = sinon.stub(); + }); + afterEach(() => { + sinon.restore(); + }); + it("should reject with an error if obliterateQueue throws an error", async () => { + req.jobQueue.obliterate.throws(new Error("obliterateQueue error")); + await obliterateQueue(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("obliterateQueue error"); + }); + it("should return a success message if obliterateQueue is successful", async () => { + req.jobQueue.obliterate.resolves(); + await obliterateQueue(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(200); + expect(res.json.firstCall.args[0]).to.deep.equal({ + success: true, + msg: successMessages.QUEUE_OBLITERATE, + }); + }); + }); }); From 98136c5fb13c95a1627b89f45dc8923ddebd739e Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 13:27:03 +0800 Subject: [PATCH 103/108] fixed accidentally nested test --- .../tests/controllers/queueController.test.js | 70 +++++++++---------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/Server/tests/controllers/queueController.test.js b/Server/tests/controllers/queueController.test.js index 8099c3e7e..476905b54 100644 --- a/Server/tests/controllers/queueController.test.js +++ b/Server/tests/controllers/queueController.test.js @@ -127,42 +127,42 @@ describe("Queue Controller - addJob", () => { msg: successMessages.QUEUE_ADD_JOB, }); }); +}); - describe("Queue Controller - obliterateQueue", () => { - beforeEach(() => { - req = { - headers: {}, - params: {}, - body: {}, - db: {}, - jobQueue: { - obliterate: sinon.stub(), - }, - }; - res = { - status: sinon.stub().returnsThis(), - json: sinon.stub(), - }; - next = sinon.stub(); - handleError = sinon.stub(); - }); - afterEach(() => { - sinon.restore(); - }); - it("should reject with an error if obliterateQueue throws an error", async () => { - req.jobQueue.obliterate.throws(new Error("obliterateQueue error")); - await obliterateQueue(req, res, next); - expect(next.firstCall.args[0]).to.be.an("error"); - expect(next.firstCall.args[0].message).to.equal("obliterateQueue error"); - }); - it("should return a success message if obliterateQueue is successful", async () => { - req.jobQueue.obliterate.resolves(); - await obliterateQueue(req, res, next); - expect(res.status.firstCall.args[0]).to.equal(200); - expect(res.json.firstCall.args[0]).to.deep.equal({ - success: true, - msg: successMessages.QUEUE_OBLITERATE, - }); +describe("Queue Controller - obliterateQueue", () => { + beforeEach(() => { + req = { + headers: {}, + params: {}, + body: {}, + db: {}, + jobQueue: { + obliterate: sinon.stub(), + }, + }; + res = { + status: sinon.stub().returnsThis(), + json: sinon.stub(), + }; + next = sinon.stub(); + handleError = sinon.stub(); + }); + afterEach(() => { + sinon.restore(); + }); + it("should reject with an error if obliterateQueue throws an error", async () => { + req.jobQueue.obliterate.throws(new Error("obliterateQueue error")); + await obliterateQueue(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("obliterateQueue error"); + }); + it("should return a success message if obliterateQueue is successful", async () => { + req.jobQueue.obliterate.resolves(); + await obliterateQueue(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(200); + expect(res.json.firstCall.args[0]).to.deep.equal({ + success: true, + msg: successMessages.QUEUE_OBLITERATE, }); }); }); From e4c12bb3d9e41b1042e32d2e2d329ddf4af952e7 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 13:34:11 +0800 Subject: [PATCH 104/108] Add tests for getAppSettings --- .../controllers/settingsController.test.js | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Server/tests/controllers/settingsController.test.js diff --git a/Server/tests/controllers/settingsController.test.js b/Server/tests/controllers/settingsController.test.js new file mode 100644 index 000000000..387f19c21 --- /dev/null +++ b/Server/tests/controllers/settingsController.test.js @@ -0,0 +1,49 @@ +const { afterEach } = require("node:test"); +const { + getAppSettings, + updateAppSettings, +} = require("../../controllers/settingsController"); + +const { errorMessages, successMessages } = require("../../utils/messages"); +const sinon = require("sinon"); + +describe("Settings Controller - getAppSettings", () => { + beforeEach(() => { + req = { + headers: {}, + params: {}, + body: {}, + db: {}, + settingsService: { + getSettings: sinon.stub(), + }, + }; + res = { + status: sinon.stub().returnsThis(), + json: sinon.stub(), + }; + next = sinon.stub(); + handleError = sinon.stub(); + }); + afterEach(() => { + sinon.restore(); + }); + it("should throw an error if getSettings throws an error", async () => { + req.settingsService.getSettings.throws(new Error("getSettings error")); + await getAppSettings(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("getSettings error"); + }); + + it("should return a success message and data if getSettings is successful", async () => { + const data = { data: "settings" }; + req.settingsService.getSettings.returns(data); + await getAppSettings(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(200); + expect(res.json.firstCall.args[0]).to.deep.equal({ + success: true, + msg: successMessages.GET_APP_SETTINGS, + data, + }); + }); +}); From f34b8466cde1e07d30f52ae0995f8b18074db1cf Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 13:38:53 +0800 Subject: [PATCH 105/108] Add tests for updateAppSettings --- .../controllers/settingsController.test.js | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/Server/tests/controllers/settingsController.test.js b/Server/tests/controllers/settingsController.test.js index 387f19c21..b06565f38 100644 --- a/Server/tests/controllers/settingsController.test.js +++ b/Server/tests/controllers/settingsController.test.js @@ -47,3 +47,59 @@ describe("Settings Controller - getAppSettings", () => { }); }); }); + +describe("Settings Controller - updateAppSettings", () => { + beforeEach(() => { + req = { + headers: {}, + params: {}, + body: {}, + db: { + updateAppSettings: sinon.stub(), + }, + settingsService: { + reloadSettings: sinon.stub(), + }, + }; + res = { + status: sinon.stub().returnsThis(), + json: sinon.stub(), + }; + next = sinon.stub(); + handleError = sinon.stub(); + }); + afterEach(() => { + sinon.restore(); + }); + it("should reject with an error if body validation fails", async () => { + req.body = { invalid: 1 }; + await updateAppSettings(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(422); + }); + it("should reject with an error if updateAppSettings throws an error", async () => { + req.db.updateAppSettings.throws(new Error("updateAppSettings error")); + await updateAppSettings(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("updateAppSettings error"); + }); + it("should reject with an error if reloadSettings throws an error", async () => { + req.settingsService.reloadSettings.throws( + new Error("reloadSettings error") + ); + await updateAppSettings(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("reloadSettings error"); + }); + it("should return a success message and data if updateAppSettings is successful", async () => { + const data = { data: "settings" }; + req.settingsService.reloadSettings.returns(data); + await updateAppSettings(req, res, next); + expect(res.status.firstCall.args[0]).to.equal(200); + expect(res.json.firstCall.args[0]).to.deep.equal({ + success: true, + msg: successMessages.UPDATE_APP_SETTINGS, + data, + }); + }); +}); From 75238978e92ffe9fb5ea468ff262b51c3b36d501 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 14 Oct 2024 15:23:38 +0800 Subject: [PATCH 106/108] updated tests for full coverage --- Server/controllers/authController.js | 7 + .../tests/controllers/authController.test.js | 327 ++++++++++++++---- 2 files changed, 267 insertions(+), 67 deletions(-) diff --git a/Server/controllers/authController.js b/Server/controllers/authController.js index 36fdc73cb..136a05a7a 100644 --- a/Server/controllers/authController.js +++ b/Server/controllers/authController.js @@ -68,6 +68,7 @@ const registerUser = async (req, res, next) => { } const newUser = await req.db.insertUser({ ...req.body }, req.file); + logger.info(successMessages.AUTH_CREATE_USER, { service: SERVICE_NAME, userId: newUser._id, @@ -78,7 +79,9 @@ const registerUser = async (req, res, next) => { delete userForToken.avatarImage; const appSettings = await req.settingsService.getSettings(); + const token = issueToken(userForToken, appSettings); + req.emailService .buildAndSendEmail( "welcomeEmailTemplate", @@ -99,6 +102,7 @@ const registerUser = async (req, res, next) => { data: { user: newUser, token: token }, }); } catch (error) { + console.log("ERROR", error); next(handleError(error, SERVICE_NAME, "registerController")); } }; @@ -293,6 +297,8 @@ const requestRecovery = async (req, res, next) => { msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN, data: msgId, }); + } else { + throw new Error(errorMessages.FRIENDLY_ERROR); } } catch (error) { next(handleError(error, SERVICE_NAME, "recoveryRequestController")); @@ -435,6 +441,7 @@ const getAllUsers = async (req, res) => { }; module.exports = { + issueToken, registerUser, loginUser, editUser, diff --git a/Server/tests/controllers/authController.test.js b/Server/tests/controllers/authController.test.js index 5e5613972..842959415 100644 --- a/Server/tests/controllers/authController.test.js +++ b/Server/tests/controllers/authController.test.js @@ -1,4 +1,5 @@ const { + issueToken, registerUser, loginUser, editUser, @@ -12,11 +13,45 @@ const { const jwt = require("jsonwebtoken"); const { errorMessages, successMessages } = require("../../utils/messages"); const sinon = require("sinon"); +const logger = require("../../utils/logger"); + +describe("Auth Controller - issueToken", () => { + it("should reject with an error if jwt.sign fails", () => { + const error = new Error("jwt.sign error"); + stub = sinon.stub(jwt, "sign").throws(error); + const payload = { id: "123" }; + const appSettings = { jwtSecret: "my_secret" }; + expect(() => issueToken(payload, appSettings)).to.throw(error); + stub.restore(); + }); + + it("should return a token if jwt.sign is successful and appSettings.jtwTTL is not defined", () => { + const payload = { id: "123" }; + const appSettings = { jwtSecret: "my_secret" }; + const token = issueToken(payload, appSettings); + expect(token).to.be.a("string"); + }); + + it("should return a token if jwt.sign is successful and appSettings.jwtTTL is defined", () => { + const payload = { id: "123" }; + const appSettings = { jwtSecret: "my_secret", jwtTTL: "1s" }; + const token = issueToken(payload, appSettings); + expect(token).to.be.a("string"); + }); +}); describe("Auth Controller - registerUser", () => { - // Set up test beforeEach(() => { req = { + body: { + firstName: "firstname", + lastName: "lastname", + email: "test@test.com", + password: "Uptime1!", + role: ["admin"], + teamId: "123", + inviteToken: "invite", + }, db: { checkSuperadmin: sinon.stub(), getInviteTokenAndDelete: sinon.stub(), @@ -29,7 +64,7 @@ describe("Auth Controller - registerUser", () => { }), }, emailService: { - buildAndSendEmail: sinon.stub().returns(Promise.resolve()), + buildAndSendEmail: sinon.stub(), }, file: {}, }; @@ -38,72 +73,97 @@ describe("Auth Controller - registerUser", () => { json: sinon.stub(), }; next = sinon.stub(); + sinon.stub(logger, "error"); + }); + afterEach(() => { + sinon.restore(); }); - it("should register a valid user", async () => { - req.body = { - firstName: "John", - lastName: "Doe", - email: "john.doe@example.com", - password: "Uptime1!", - inviteToken: "someToken", - role: ["user"], - teamId: "123", - }; - req.db.checkSuperadmin.resolves(false); - req.db.insertUser.resolves({ - _id: "123", - _doc: { - firstName: "John", - lastName: "Doe", - email: "john.doe@example.com", - }, - }); + it("should reject with an error if body validation fails", async () => { + req.body = {}; + await registerUser(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(422); + }); + it("should reject with an error if checkSuperadmin fails", async () => { + req.db.checkSuperadmin.rejects(new Error("checkSuperadmin error")); + await registerUser(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("checkSuperadmin error"); + }); + + it("should reject with an error if getInviteTokenAndDelete fails", async () => { + req.db.checkSuperadmin.resolves(true); + req.db.getInviteTokenAndDelete.rejects( + new Error("getInviteTokenAndDelete error") + ); + await registerUser(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal( + "getInviteTokenAndDelete error" + ); + }); + + it("should reject with an error if updateAppSettings fails", async () => { + req.db.checkSuperadmin.resolves(false); + req.db.updateAppSettings.rejects(new Error("updateAppSettings error")); + await registerUser(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("updateAppSettings error"); + }); + + it("should reject with an error if insertUser fails", async () => { + req.db.checkSuperadmin.resolves(false); + req.db.updateAppSettings.resolves(); + req.db.insertUser.rejects(new Error("insertUser error")); + await registerUser(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("insertUser error"); + }); + + it("should reject with an error if settingsService.getSettings fails", async () => { + req.db.checkSuperadmin.resolves(false); + req.db.updateAppSettings.resolves(); + req.db.insertUser.resolves({ _id: "123" }); + req.settingsService.getSettings.rejects( + new Error("settingsService.getSettings error") + ); + await registerUser(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal( + "settingsService.getSettings error" + ); + }); + + it("should log an error if emailService.buildAndSendEmail fails", async () => { + req.db.checkSuperadmin.resolves(false); + req.db.updateAppSettings.resolves(); + req.db.insertUser.returns({ _id: "123" }); + req.settingsService.getSettings.returns({ jwtSecret: "my_secret" }); + req.emailService.buildAndSendEmail.rejects(new Error("emailService error")); + await registerUser(req, res, next); + expect(logger.error.calledOnce).to.be.true; + expect(logger.error.firstCall.args[1].error).to.equal("emailService error"); + }); + it("should return a success message and data if all operations are successful", async () => { + const user = { _id: "123" }; + req.db.checkSuperadmin.resolves(false); + req.db.updateAppSettings.resolves(); + req.db.insertUser.returns(user); + req.settingsService.getSettings.returns({ jwtSecret: "my_secret" }); + req.emailService.buildAndSendEmail.resolves("message-id"); await registerUser(req, res, next); expect(res.status.calledWith(200)).to.be.true; expect( - res.json.calledWith( - sinon.match({ - success: true, - msg: sinon.match.string, - data: { - user: sinon.match.object, - token: sinon.match.string, - }, - }) - ) + res.json.calledWith({ + success: true, + msg: successMessages.AUTH_CREATE_USER, + data: { user, token: sinon.match.string }, + }) ).to.be.true; expect(next.notCalled).to.be.true; }); - it("should reject a user with an invalid password", async () => { - req.body = { - firstName: "John", - lastName: "Doe", - email: "john.doe@example.com", - password: "bad_password", - inviteToken: "someToken", - role: ["user"], - teamId: "123", - }; - await registerUser(req, res, next); - expect(next.firstCall.args[0]).to.be.an("error"); - expect(next.firstCall.args[0].status).to.equal(422); - }); - it("should reject a user with an invalid role", async () => { - req.body = { - firstName: "John", - lastName: "Doe", - email: "john.doe@example.com", - password: "Uptime1!", - inviteToken: "someToken", - role: ["superman"], - teamId: "123", - }; - await registerUser(req, res, next); - expect(next.firstCall.args[0]).to.be.an("error"); - expect(next.firstCall.args[0].status).to.equal(422); - }); }); describe("Auth Controller - loginUser", () => { @@ -131,6 +191,20 @@ describe("Auth Controller - loginUser", () => { comparePassword: sinon.stub(), }; }); + it("should reject with an error if validation fails", async () => { + req.body = {}; + await loginUser(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(422); + }); + + it("should reject with an error if getUserByEmail fails", async () => { + req.db.getUserByEmail.rejects(new Error("getUserByEmail error")); + await loginUser(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("getUserByEmail error"); + }); + it("should login user successfully", async () => { req.db.getUserByEmail.resolves(user); user.comparePassword.resolves(true); @@ -186,10 +260,63 @@ describe("Auth Controller - editUser", async () => { json: sinon.stub(), }; next = sinon.stub(); + stub = sinon.stub(jwt, "verify").returns({ email: "test@example.com" }); + }); + afterEach(() => { + sinon.restore(); + stub.restore(); + }); + + it("should reject with an error if param validation fails", async () => { + req.params = {}; + await editUser(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(422); + }); + + it("should reject with an error if body validation fails", async () => { + req.body = { invalid: 1 }; + await editUser(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(422); + }); + + it("should reject with an error if param.userId !== req.user._id", async () => { + req.params = { userId: "456" }; + await editUser(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(401); + }); + + it("should reject with an error if !req.body.password and getUserByEmail fails", async () => { + req.db.getUserByEmail.rejects(new Error("getUserByEmail error")); + await editUser(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("getUserByEmail error"); + }); + + it("should reject with an error if user.comparePassword fails", async () => { + req.db.getUserByEmail.returns({ + comparePassword: sinon.stub().rejects(new Error("Bad Password Match")), + }); + await editUser(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("Bad Password Match"); + }); + + it("should reject with an error if user.comparePassword returns false", async () => { + req.db.getUserByEmail.returns({ + comparePassword: sinon.stub().returns(false), + }); + await editUser(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(403); + expect(next.firstCall.args[0].message).to.equal( + errorMessages.AUTH_INCORRECT_PASSWORD + ); }); it("should edit a user if it receives a proper request", async () => { - sinon.stub(jwt, "verify").returns({ email: "test@example.com" }); const user = { comparePassword: sinon.stub().resolves(true), }; @@ -211,6 +338,24 @@ describe("Auth Controller - editUser", async () => { expect(next.notCalled).to.be.true; }); + it("should edit a user if it receives a proper request and both password fields are undefined", async () => { + req.body.password = undefined; + req.body.newPassword = undefined; + req.db.getUserByEmail.resolves(user); + req.db.updateUser.resolves({ email: "test@example.com" }); + + await editUser(req, res, next); + expect(res.status.calledWith(200)).to.be.true; + expect( + res.json.calledWith({ + success: true, + msg: successMessages.AUTH_UPDATE_USER, + data: { email: "test@example.com" }, + }) + ).to.be.true; + expect(next.notCalled).to.be.true; + }); + it("should reject an edit request if password format is incorrect", async () => { req.body = { password: "bad_password", newPassword: "bad_password" }; const user = { @@ -239,6 +384,13 @@ describe("Auth Controller - checkSuperadminExists", async () => { next = sinon.stub(); }); + it("should reject with an error if checkSuperadmin fails", async () => { + req.db.checkSuperadmin.rejects(new Error("checkSuperadmin error")); + await checkSuperadminExists(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("checkSuperadmin error"); + }); + it("should return true if a superadmin exists", async () => { req.db.checkSuperadmin.resolves(true); await checkSuperadminExists(req, res, next); @@ -289,6 +441,30 @@ describe("Auth Controller - requestRecovery", async () => { }; next = sinon.stub(); }); + + it("should reject with an error if validation fails", async () => { + req.body = {}; + await requestRecovery(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].status).to.equal(422); + }); + + it("should reject with an error if getUserByEmail fails", async () => { + req.db.getUserByEmail.rejects(new Error("getUserByEmail error")); + await requestRecovery(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("getUserByEmail error"); + }); + + it("should throw an error if the user is not found", async () => { + req.db.getUserByEmail.resolves(null); + await requestRecovery(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + // expect(next.firstCall.args[0].message).to.equal( + // errorMessages.FRIENDLY_ERROR + // ); + }); + it("should throw an error if the email is not provided", async () => { req.body = {}; await requestRecovery(req, res, next); @@ -344,15 +520,24 @@ describe("Auth Controller - validateRecovery", async () => { next = sinon.stub(); }); - it("should call next with a validation error if the token is invalid", async () => { - req = { - body: {}, - }; + it("should reject with an error if validation fails", async () => { + req.body = {}; await validateRecovery(req, res, next); expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0].status).to.equal(422); }); + it("should reject with an error if validateRecoveryToken fails", async () => { + req.db.validateRecoveryToken.rejects( + new Error("validateRecoveryToken error") + ); + await validateRecovery(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal( + "validateRecoveryToken error" + ); + }); + it("should return a success message if the token is valid", async () => { req.db.validateRecoveryToken.resolves(); await validateRecovery(req, res, next); @@ -391,14 +576,23 @@ describe("Auth Controller - resetPassword", async () => { }; handleValidationError = sinon.stub(); handleError = sinon.stub(); - issueToken = sinon.stub(); }); - it("should call next with a validation error if the password is invalid", async () => { + it("should reject with an error if validation fails", async () => { req.body = { password: "bad_password" }; await resetPassword(req, res, next); expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0].status).to.equal(422); }); + + it("should reject with an error if resetPassword fails", async () => { + const error = new Error("resetPassword error"); + newPasswordValidation.validateAsync.resolves(); + req.db.resetPassword.rejects(error); + await resetPassword(req, res, next); + expect(next.firstCall.args[0]).to.be.an("error"); + expect(next.firstCall.args[0].message).to.equal("resetPassword error"); + }); + it("should reset password successfully", async () => { const user = { _doc: {} }; const appSettings = { jwtSecret: "my_secret" }; @@ -407,7 +601,6 @@ describe("Auth Controller - resetPassword", async () => { newPasswordValidation.validateAsync.resolves(); req.db.resetPassword.resolves(user); req.settingsService.getSettings.resolves(appSettings); - issueToken.returns(token); await resetPassword(req, res, next); From 4623aa89314a188029dd075a347886ff9a24cf87 Mon Sep 17 00:00:00 2001 From: Abhimanue Date: Mon, 14 Oct 2024 12:11:59 +0530 Subject: [PATCH 107/108] revamp side-menu --- Client/src/Components/Sidebar/index.jsx | 113 ++++++++---------------- Client/src/assets/icons/folder.svg | 4 + 2 files changed, 41 insertions(+), 76 deletions(-) create mode 100644 Client/src/assets/icons/folder.svg diff --git a/Client/src/Components/Sidebar/index.jsx b/Client/src/Components/Sidebar/index.jsx index be7689235..4e62bffe5 100644 --- a/Client/src/Components/Sidebar/index.jsx +++ b/Client/src/Components/Sidebar/index.jsx @@ -43,6 +43,7 @@ import ArrowLeft from "../../assets/icons/left-arrow.svg?react"; import DotsVertical from "../../assets/icons/dots-vertical.svg?react"; import ChangeLog from "../../assets/icons/changeLog.svg?react"; import Docs from "../../assets/icons/docs.svg?react"; +import Folder from "../../assets/icons/folder.svg?react"; import "./index.css"; @@ -68,13 +69,16 @@ const menu = [ { name: "Team", path: "account/team", icon: }, ], }, -]; - -const other = [ - { name: "Settings", path: "settings", icon: }, - { name: "Support", path: "support", icon: }, - { name: "Docs", path: "docs", icon: }, - { name: "Changelog", path: "changelog", icon: }, + { + name: "Other", + icon: , + nested: [ + { name: "Settings", path: "settings", icon: }, + { name: "Support", path: "support", icon: }, + { name: "Docs", path: "docs", icon: }, + { name: "Changelog", path: "changelog", icon: }, + ], + }, ]; const URL_MAP = { @@ -97,7 +101,7 @@ function Sidebar() { const dispatch = useDispatch(); const authState = useSelector((state) => state.auth); const collapsed = useSelector((state) => state.ui.sidebar.collapsed); - const [open, setOpen] = useState({ Dashboard: false, Account: false }); + const [open, setOpen] = useState({ Dashboard: false, Account: false, Other: false }); const [anchorEl, setAnchorEl] = useState(null); const [popup, setPopup] = useState(); const { user } = useSelector((state) => state.auth); @@ -137,6 +141,8 @@ function Sidebar() { setOpen((prev) => ({ ...prev, Dashboard: true })); else if (location.pathname.includes("/account")) setOpen((prev) => ({ ...prev, Account: true })); + else if (location.pathname.includes("/settings")) + setOpen((prev) => ({ ...prev, Other: true })); }, []); return ( @@ -212,7 +218,7 @@ function Sidebar() { }, }} onClick={() => { - setOpen({ Dashboard: false, Account: false }); + setOpen({ Dashboard: false, Account: false, Other: false }); dispatch(toggleSidebar()); }} > @@ -356,7 +362,12 @@ function Sidebar() { } key={child.path} onClick={() => { - navigate(`/${child.path}`); + const url = URL_MAP[child.path]; + if (url) { + window.open(url, "_blank", "noreferrer"); + } else { + navigate(`/${child.path}`); + } closePopup(); }} sx={{ @@ -382,8 +393,14 @@ function Sidebar() { setOpen((prev) => ({ - ...prev, - [`${item.name}`]: !prev[`${item.name}`], + ...Object.keys(prev).reduce( + (acc, key) => ({ + ...acc, + [key]: false, // close all other sections + }), + {} + ), + [`${item.name}`]: !prev[`${item.name}`], // toggle clicked section })) } sx={{ @@ -419,7 +436,14 @@ function Sidebar() { : "" } key={child.path} - onClick={() => navigate(`/${child.path}`)} + onClick={() => { + const url = URL_MAP[child.path]; + if (url) { + window.open(url, "_blank", "noreferrer"); + } else { + navigate(`/${child.path}`); + } + }} sx={{ gap: theme.spacing(4), borderRadius: theme.shape.borderRadius, @@ -465,69 +489,6 @@ function Sidebar() { ) )} - - {/* other */} - - Other - - } - sx={{ px: theme.spacing(6) }} - > - {other.map((item) => ( - - { - const url = URL_MAP[item.path]; - if (url) { - window.open(url, "_blank", "noreferrer"); - } else { - navigate(`/${item.path}`); - } - }} - sx={{ - gap: theme.spacing(4), - borderRadius: theme.shape.borderRadius, - px: theme.spacing(4), - }} - > - {item.icon} - {item.name} - - - ))} - + + + \ No newline at end of file From cefe93b8a1068a030712ee4b60935758413e2aa6 Mon Sep 17 00:00:00 2001 From: Abhimanue Date: Mon, 14 Oct 2024 22:02:51 +0530 Subject: [PATCH 108/108] improve maintainability --- Client/src/Components/Sidebar/index.jsx | 37 +++++++++++++------------ 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/Client/src/Components/Sidebar/index.jsx b/Client/src/Components/Sidebar/index.jsx index 4e62bffe5..0019a282a 100644 --- a/Client/src/Components/Sidebar/index.jsx +++ b/Client/src/Components/Sidebar/index.jsx @@ -87,6 +87,13 @@ const URL_MAP = { changelog: "https://github.com/bluewave-labs/bluewave-uptime/releases", }; +const PATH_MAP = { + monitors: "Dashboard", + pagespeed: "Dashboard", + account: "Account", + settings: "Other", +}; + /** * @component * Sidebar component serves as a sidebar containing a menu. @@ -134,15 +141,13 @@ function Sidebar() { }; useEffect(() => { - if ( - location.pathname.includes("monitors") || - location.pathname.includes("pagespeed") - ) - setOpen((prev) => ({ ...prev, Dashboard: true })); - else if (location.pathname.includes("/account")) - setOpen((prev) => ({ ...prev, Account: true })); - else if (location.pathname.includes("/settings")) - setOpen((prev) => ({ ...prev, Other: true })); + const matchedKey = Object.keys(PATH_MAP).find((key) => + location.pathname.includes(key) + ); + + if (matchedKey) { + setOpen((prev) => ({ ...prev, [PATH_MAP[matchedKey]]: true })); + } }, []); return ( @@ -218,7 +223,9 @@ function Sidebar() { }, }} onClick={() => { - setOpen({ Dashboard: false, Account: false, Other: false }); + setOpen(prev => + Object.fromEntries(Object.keys(prev).map(key => [key, false])) + ) dispatch(toggleSidebar()); }} > @@ -393,14 +400,8 @@ function Sidebar() { setOpen((prev) => ({ - ...Object.keys(prev).reduce( - (acc, key) => ({ - ...acc, - [key]: false, // close all other sections - }), - {} - ), - [`${item.name}`]: !prev[`${item.name}`], // toggle clicked section + ...Object.fromEntries(Object.keys(prev).map(key => [key, false])), + [item.name]: !prev[item.name] })) } sx={{