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/Maintenance/MaintenanceTable/ActionsMenu/index.jsx b/Client/src/Pages/Maintenance/MaintenanceTable/ActionsMenu/index.jsx
new file mode 100644
index 000000000..ba8082504
--- /dev/null
+++ b/Client/src/Pages/Maintenance/MaintenanceTable/ActionsMenu/index.jsx
@@ -0,0 +1,229 @@
+import { useState } from "react";
+import { useTheme } from "@emotion/react";
+import { useNavigate } from "react-router-dom";
+import { useSelector } from "react-redux";
+import {
+ Button,
+ IconButton,
+ Menu,
+ MenuItem,
+ Modal,
+ Stack,
+ Typography,
+} from "@mui/material";
+import LoadingButton from "@mui/lab/LoadingButton";
+import { logger } from "../../../../Utils/Logger";
+import Settings from "../../../../assets/icons/settings-bold.svg?react";
+import PropTypes from "prop-types";
+import { networkService } from "../../../../main";
+import { createToast } from "../../../../Utils/toastUtils";
+
+const ActionsMenu = ({ isAdmin, maintenanceWindow, updateCallback }) => {
+ maintenanceWindow;
+ const { authToken } = useSelector((state) => state.auth);
+ const [anchorEl, setAnchorEl] = useState(null);
+ const [isOpen, setIsOpen] = useState(false);
+ const [isLoading, setIsLoading] = useState(false);
+
+ const theme = useTheme();
+
+ const handleRemove = async (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ try {
+ setIsLoading(true);
+ await networkService.deleteMaintenanceWindow({
+ authToken,
+ maintenanceWindowId: maintenanceWindow._id,
+ });
+ updateCallback();
+ createToast({ body: "Maintenance window deleted successfully." });
+ } catch (error) {
+ createToast({ body: "Failed to delete maintenance window." });
+ logger.error("Failed to delete maintenance window", error);
+ } finally {
+ setIsLoading(false);
+ }
+ setIsOpen(false);
+ };
+
+ const handlePause = async () => {
+ try {
+ setIsLoading(true);
+ const data = {
+ active: !maintenanceWindow.active,
+ };
+ await networkService.editMaintenanceWindow({
+ authToken,
+ maintenanceWindowId: maintenanceWindow._id,
+ maintenanceWindow: data,
+ });
+ updateCallback();
+ } catch (error) {
+ logger.error(error);
+ createToast({ body: "Failed to pause maintenance window." });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleEdit = () => {
+ navigate(`/maintenance/create/${maintenanceWindow._id}`);
+ };
+
+ const openMenu = (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setAnchorEl(event.currentTarget);
+ };
+
+ const openRemove = (e) => {
+ closeMenu(e);
+ setIsOpen(true);
+ };
+
+ const closeMenu = (e) => {
+ e.stopPropagation();
+ setAnchorEl(null);
+ };
+
+ const navigate = useNavigate();
+
+ return (
+ <>
+ {
+ event.stopPropagation();
+ openMenu(event);
+ }}
+ sx={{
+ "&:focus": {
+ outline: "none",
+ },
+ "& svg path": {
+ stroke: theme.palette.other.icon,
+ },
+ }}
+ >
+
+
+
+
+ {
+ e.stopPropagation();
+ setIsOpen(false);
+ }}
+ >
+
+
+ Do you really want to remove this maintenance window?
+
+
+
+ {
+ e.stopPropagation(e);
+ handleRemove(e);
+ }}
+ >
+ Delete
+
+
+
+
+ >
+ );
+};
+
+ActionsMenu.propTypes = {
+ maintenanceWindow: PropTypes.object,
+ isAdmin: PropTypes.bool,
+ updateCallback: PropTypes.func,
+};
+
+export default ActionsMenu;
diff --git a/Client/src/Pages/Maintenance/MaintenanceTable/index.jsx b/Client/src/Pages/Maintenance/MaintenanceTable/index.jsx
new file mode 100644
index 000000000..af9d15ca9
--- /dev/null
+++ b/Client/src/Pages/Maintenance/MaintenanceTable/index.jsx
@@ -0,0 +1,363 @@
+import PropTypes from "prop-types";
+import {
+ TableContainer,
+ Table,
+ TableHead,
+ TableRow,
+ TableCell,
+ TableBody,
+ Paper,
+ Box,
+ TablePagination,
+ Stack,
+ Typography,
+ Button,
+} from "@mui/material";
+import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded";
+import ArrowUpwardRoundedIcon from "@mui/icons-material/ArrowUpwardRounded";
+import ActionsMenu from "./ActionsMenu";
+import { useState, useEffect, memo, useCallback, useRef } from "react";
+import { useDispatch, useSelector } from "react-redux";
+import { useTheme } from "@emotion/react";
+import LeftArrowDouble from "../../../assets/icons/left-arrow-double.svg?react";
+import RightArrowDouble from "../../../assets/icons/right-arrow-double.svg?react";
+import LeftArrow from "../../../assets/icons/left-arrow.svg?react";
+import RightArrow from "../../../assets/icons/right-arrow.svg?react";
+import SelectorVertical from "../../../assets/icons/selector-vertical.svg?react";
+import { formatDurationRounded } from "../../../Utils/timeUtils";
+import { StatusLabel } from "../../../Components/Label";
+import { setRowsPerPage } from "../../../Features/UI/uiSlice";
+import dayjs from "dayjs";
+
+/**
+ * Component for pagination actions (first, previous, next, last).
+ *
+ * @component
+ * @param {Object} props
+ * @param {number} props.count - Total number of items.
+ * @param {number} props.page - Current page number.
+ * @param {number} props.rowsPerPage - Number of rows per page.
+ * @param {function} props.onPageChange - Callback function to handle page change.
+ *
+ * @returns {JSX.Element} Pagination actions component.
+ */
+const TablePaginationActions = (props) => {
+ const { count, page, rowsPerPage, onPageChange } = props;
+ const handleFirstPageButtonClick = (event) => {
+ onPageChange(event, 0);
+ };
+ const handleBackButtonClick = (event) => {
+ onPageChange(event, page - 1);
+ };
+ const handleNextButtonClick = (event) => {
+ onPageChange(event, page + 1);
+ };
+ const handleLastPageButtonClick = (event) => {
+ onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
+ };
+
+ return (
+
+
+
+
+
+
+ );
+};
+
+TablePaginationActions.propTypes = {
+ count: PropTypes.number.isRequired,
+ page: PropTypes.number.isRequired,
+ rowsPerPage: PropTypes.number.isRequired,
+ onPageChange: PropTypes.func.isRequired,
+};
+
+const MaintenanceTable = ({
+ page,
+ setPage,
+ sort,
+ setSort,
+ maintenanceWindows,
+ maintenanceWindowCount,
+ updateCallback,
+}) => {
+ const { rowsPerPage } = useSelector((state) => state.ui.maintenance);
+ const theme = useTheme();
+ const dispatch = useDispatch();
+
+ const handleChangePage = (event, newPage) => {
+ setPage(newPage);
+ };
+
+ const getTimeToNextWindow = (startTime, endTime, repeat) => {
+ //1. Advance time closest to next window as possible
+ const now = dayjs();
+ let start = dayjs(startTime);
+ let end = dayjs(endTime);
+ if (repeat > 0) {
+ // Advance time closest to next window as possible
+ while (start.isBefore(now) && end.isBefore(now)) {
+ start = start.add(repeat, "milliseconds");
+ end = end.add(repeat, "milliseconds");
+ }
+ }
+
+ //Check if we are in a window
+ if (now.isAfter(start) && now.isBefore(end)) {
+ return "In maintenance window";
+ }
+
+ if (start.isAfter(now)) {
+ const diffInMinutes = start.diff(now, "minutes");
+ const diffInHours = start.diff(now, "hours");
+ const diffInDays = start.diff(now, "days");
+
+ if (diffInMinutes < 60) {
+ return diffInMinutes + " minutes";
+ } else if (diffInHours < 24) {
+ return diffInHours + " hours";
+ } else if (diffInDays < 7) {
+ return diffInDays + " days";
+ } else {
+ return diffInDays + " days";
+ }
+ }
+ };
+
+ const handleChangeRowsPerPage = (event) => {
+ dispatch(
+ setRowsPerPage({
+ value: parseInt(event.target.value, 10),
+ table: "maintenance",
+ })
+ );
+ setPage(0);
+ };
+
+ /**
+ * Helper function to calculate the range of displayed rows.
+ * @returns {string}
+ */
+ const getRange = () => {
+ let start = page * rowsPerPage + 1;
+ let end = Math.min(
+ page * rowsPerPage + rowsPerPage,
+ maintenanceWindowCount
+ );
+ return `${start} - ${end}`;
+ };
+
+ const handleSort = async (field) => {
+ let order = "";
+ if (sort.field !== field) {
+ order = "desc";
+ } else {
+ order = sort.order === "asc" ? "desc" : "asc";
+ }
+ setSort({ field, order });
+ };
+
+ return (
+ <>
+
+
+
+
+ handleSort("name")}
+ >
+
+ Maintenance Window Name
+
+ {sort.order === "asc" ? (
+
+ ) : (
+
+ )}
+
+
+
+ handleSort("status")}
+ >
+ {" "}
+
+ {" "}
+ Status
+
+ {sort.order === "asc" ? (
+
+ ) : (
+
+ )}
+
+
+
+ Next Window
+ Repeat
+ Actions
+
+
+
+ {maintenanceWindows.map((maintenanceWindow) => {
+ const text = maintenanceWindow.active ? "active" : "paused";
+ const status = maintenanceWindow.active ? "up" : "paused";
+ return (
+
+ {maintenanceWindow.name}
+
+
+
+
+ {getTimeToNextWindow(
+ maintenanceWindow.start,
+ maintenanceWindow.end,
+ maintenanceWindow.repeat
+ )}
+
+
+ {maintenanceWindow.repeat === 0
+ ? "N/A"
+ : formatDurationRounded(maintenanceWindow.repeat)}
+
+
+
+
+
+ );
+ })}
+
+
+
+
+
+ Showing {getRange()} of {maintenanceWindowCount} maintenance window(s)
+
+
+ `Page ${page + 1} of ${Math.max(0, Math.ceil(count / rowsPerPage))}`
+ }
+ slotProps={{
+ select: {
+ MenuProps: {
+ keepMounted: true,
+ disableScrollLock: true,
+ PaperProps: {
+ className: "pagination-dropdown",
+ sx: {
+ mt: 0,
+ mb: theme.spacing(2),
+ },
+ },
+ transformOrigin: { vertical: "bottom", horizontal: "left" },
+ anchorOrigin: { vertical: "top", horizontal: "left" },
+ sx: { mt: theme.spacing(-2) },
+ },
+ inputProps: { id: "pagination-dropdown" },
+ IconComponent: SelectorVertical,
+ sx: {
+ ml: theme.spacing(4),
+ mr: theme.spacing(12),
+ minWidth: theme.spacing(20),
+ textAlign: "left",
+ "&.Mui-focused > div": {
+ backgroundColor: theme.palette.background.main,
+ },
+ },
+ },
+ }}
+ sx={{
+ mt: theme.spacing(6),
+ color: theme.palette.text.secondary,
+ "& svg path": {
+ stroke: theme.palette.text.tertiary,
+ strokeWidth: 1.3,
+ },
+ "& .MuiSelect-select": {
+ border: 1,
+ borderColor: theme.palette.border.light,
+ borderRadius: theme.shape.borderRadius,
+ },
+ }}
+ />
+
+ >
+ );
+};
+
+MaintenanceTable.propTypes = {
+ isAdmin: PropTypes.bool,
+ page: PropTypes.number,
+ setPage: PropTypes.func,
+ rowsPerPage: PropTypes.number,
+ setRowsPerPage: PropTypes.func,
+ sort: PropTypes.object,
+ setSort: PropTypes.func,
+ maintenanceWindows: PropTypes.array,
+ maintenanceWindowCount: PropTypes.number,
+ updateCallback: PropTypes.func,
+};
+
+const MemoizedMaintenanceTable = memo(MaintenanceTable);
+export default MemoizedMaintenanceTable;
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;
-}
diff --git a/Client/src/Pages/Maintenance/index.jsx b/Client/src/Pages/Maintenance/index.jsx
index 5c23a789c..3f9a9a047 100644
--- a/Client/src/Pages/Maintenance/index.jsx
+++ b/Client/src/Pages/Maintenance/index.jsx
@@ -1,10 +1,48 @@
-import { Box } from "@mui/material";
+import { Box, Stack, Button } from "@mui/material";
import { useTheme } from "@emotion/react";
import Fallback from "../../Components/Fallback";
+import { useState, useEffect } from "react";
import "./index.css";
+import MaintenanceTable from "./MaintenanceTable";
+import { useSelector } from "react-redux";
+import { networkService } from "../../main";
+import Breadcrumbs from "../../Components/Breadcrumbs";
+import { useNavigate } from "react-router-dom";
const Maintenance = ({ isAdmin }) => {
const theme = useTheme();
+ const navigate = useNavigate();
+ const { authToken } = useSelector((state) => state.auth);
+ const { rowsPerPage } = useSelector((state) => state.ui.maintenance);
+
+ const [maintenanceWindows, setMaintenanceWindows] = useState([]);
+ const [maintenanceWindowCount, setMaintenanceWindowCount] = useState(0);
+ const [page, setPage] = useState(0);
+ const [sort, setSort] = useState({});
+ const [updateTrigger, setUpdateTrigger] = useState(false);
+
+ const handleActionMenuDelete = () => {
+ setUpdateTrigger((prev) => !prev);
+ };
+
+ useEffect(() => {
+ const fetchMaintenanceWindows = async () => {
+ try {
+ const response = await networkService.getMaintenanceWindowsByTeamId({
+ authToken: authToken,
+ page: page,
+ rowsPerPage: rowsPerPage,
+ });
+ const { maintenanceWindows, maintenanceWindowCount } =
+ response.data.data;
+ setMaintenanceWindows(maintenanceWindows);
+ setMaintenanceWindowCount(maintenanceWindowCount);
+ } catch (error) {
+ console.log(error);
+ }
+ };
+ fetchMaintenanceWindows();
+ }, [authToken, page, rowsPerPage, updateTrigger]);
return (
{
},
}}
>
-
+ {maintenanceWindows.length > 0 && (
+
+
+
+
+
+
+
+ )}
+ {isAdmin && maintenanceWindows.length === 0 && (
+
+ )}
);
};
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;
-}
diff --git a/Client/src/Pages/Monitors/CreateMonitor/index.jsx b/Client/src/Pages/Monitors/CreateMonitor/index.jsx
index ef07d8e77..ac68ea7eb 100644
--- a/Client/src/Pages/Monitors/CreateMonitor/index.jsx
+++ b/Client/src/Pages/Monitors/CreateMonitor/index.jsx
@@ -112,7 +112,7 @@ const CreateMonitor = () => {
{ [name]: value },
{ abortEarly: false }
);
-
+ console.log(error);
setErrors((prev) => {
const updatedErrors = { ...prev };
if (error) updatedErrors[name] = error.details[0].message;
diff --git a/Client/src/Pages/Monitors/Home/index.jsx b/Client/src/Pages/Monitors/Home/index.jsx
index a03959076..4e72f0346 100644
--- a/Client/src/Pages/Monitors/Home/index.jsx
+++ b/Client/src/Pages/Monitors/Home/index.jsx
@@ -136,7 +136,7 @@ const Monitors = ({ isAdmin }) => {
diff --git a/Client/src/Utils/Logger.js b/Client/src/Utils/Logger.js
index 79b2ed4f9..a3cb9bc16 100644
--- a/Client/src/Utils/Logger.js
+++ b/Client/src/Utils/Logger.js
@@ -1,5 +1,7 @@
import store from "../store";
const LOG_LEVEL = import.meta.env.VITE_APP_LOG_LEVEL || "debug";
+const NO_OP = () => {};
+
class Logger {
constructor() {
let logLevel = LOG_LEVEL;
@@ -11,29 +13,37 @@ class Logger {
}
updateLogLevel(logLevel) {
- const NO_OP = () => {};
-
if (logLevel === "none") {
+ this.info = NO_OP;
this.error = NO_OP;
this.warn = NO_OP;
this.log = NO_OP;
return;
}
- this.error = console.error.bind(console);
-
if (logLevel === "error") {
+ this.error = console.error.bind(console);
+ this.info = NO_OP;
this.warn = NO_OP;
this.log = NO_OP;
return;
}
- this.warn = console.warn.bind(console);
if (logLevel === "warn") {
+ this.error = console.error.bind(console);
+ this.warn = console.warn.bind(console);
+ this.info = NO_OP;
+ this.log = NO_OP;
+ return;
+ }
+
+ if (logLevel === "info") {
+ this.error = console.error.bind(console);
+ this.warn = console.warn.bind(console);
+ this.info = console.info.bind(console);
this.log = NO_OP;
return;
}
- this.log = console.log.bind(console);
}
cleanup() {
diff --git a/Client/src/Utils/NetworkService.js b/Client/src/Utils/NetworkService.js
index 460befc0b..573651f58 100644
--- a/Client/src/Utils/NetworkService.js
+++ b/Client/src/Utils/NetworkService.js
@@ -130,7 +130,7 @@ class NetworkService {
* @param {Object} config - The configuration object.
* @param {string} config.authToken - The authorization token to be used in the request header.
* @param {string} config.teamId - The ID of the team whose monitors are to be retrieved.
- * @param {number} [config.limit] - The maximum number of monitors to retrieve.
+ * @param {number} [config.limit] - The maximum number of checks to retrieve. 0 for all, -1 for none
* @param {Array} [config.types] - The types of monitors to retrieve.
* @param {string} [config.status] - The status of the monitors to retrieve.
* @param {string} [config.checkOrder] - The order in which to sort the retrieved monitors.
@@ -690,6 +690,148 @@ class NetworkService {
},
});
}
+
+ /**
+ * ************************************
+ * Creates a maintenance window
+ * ************************************
+ *
+ * @async
+ * @param {Object} config - The configuration object.
+ * @param {string} config.authToken - The authorization token to be used in the request header.
+ * @param {Object} config.maintenanceWindow - The maintenance window object to be sent in the request body.
+ * @returns {Promise} The response from the axios POST request.
+ *
+ */
+
+ async createMaintenanceWindow(config) {
+ return this.axiosInstance.post(
+ `/maintenance-window`,
+ config.maintenanceWindow,
+ {
+ headers: {
+ Authorization: `Bearer ${config.authToken}`,
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ }
+
+ /**
+ * ************************************
+ * Edits a maintenance window
+ * ************************************
+ *
+ * @async
+ * @param {Object} config - The configuration object.
+ * @param {string} config.authToken - The authorization token to be used in the request header.
+ * @param {Object} config.maintenanceWindowId - The maintenance window id.
+ * @param {Object} config.maintenanceWindow - The maintenance window object to be sent in the request body.
+ * @returns {Promise} The response from the axios POST request.
+ *
+ */
+
+ async editMaintenanceWindow(config) {
+ return this.axiosInstance.put(
+ `/maintenance-window/${config.maintenanceWindowId}`,
+ config.maintenanceWindow,
+ {
+ headers: {
+ Authorization: `Bearer ${config.authToken}`,
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ }
+
+ /**
+ * ************************************
+ * Get maintenance window by id
+ * ************************************
+ *
+ * @async
+ * @param {Object} config - The configuration object.
+ * @param {string} config.authToken - The authorization token to be used in the request header.
+ * @param {string} [config.maintenanceWindowId] - The id of the maintenance window to delete.
+ * @returns {Promise} The response from the axios POST request.
+ *
+ */
+
+ async getMaintenanceWindowById(config) {
+ const { authToken, maintenanceWindowId } = config;
+ return this.axiosInstance.get(
+ `/maintenance-window/${maintenanceWindowId}`,
+ {
+ headers: {
+ Authorization: `Bearer ${authToken}`,
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ }
+
+ /**
+ * ************************************
+ * Get maintenance windows by teamId
+ * ************************************
+ *
+ * @async
+ * @param {Object} config - The configuration object.
+ * @param {string} config.authToken - The authorization token to be used in the request header.
+ * @param {string} [config.active] - The status of the maintenance windows to retrieve.
+ * @param {number} [config.page] - The page number for pagination.
+ * @param {number} [config.rowsPerPage] - The number of rows per page for pagination.
+ * @param {string} [config.field] - The field to sort by.
+ * @param {string} [config.order] - The order in which to sort the field.
+ * @returns {Promise} The response from the axios POST request.
+ *
+ */
+
+ async getMaintenanceWindowsByTeamId(config) {
+ const { authToken, active, page, rowsPerPage, field, order } = config;
+ const params = new URLSearchParams();
+
+ if (active) params.append("status", active);
+ if (page) params.append("page", page);
+ if (rowsPerPage) params.append("rowsPerPage", rowsPerPage);
+ if (field) params.append("field", field);
+ if (order) params.append("order", order);
+
+ return this.axiosInstance.get(
+ `/maintenance-window/team?${params.toString()}`,
+ {
+ headers: {
+ Authorization: `Bearer ${authToken}`,
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ }
+ /**
+ * ************************************
+ * Delete maintenance window by id
+ * ************************************
+ *
+ * @async
+ * @param {Object} config - The configuration object.
+ * @param {string} config.authToken - The authorization token to be used in the request header.
+ * @param {string} [config.maintenanceWindowId] - The id of the maintenance window to delete.
+ * @returns {Promise} The response from the axios POST request.
+ *
+ */
+
+ async deleteMaintenanceWindow(config) {
+ const { authToken, maintenanceWindowId } = config;
+ return this.axiosInstance.delete(
+ `/maintenance-window/${maintenanceWindowId}`,
+ {
+ headers: {
+ Authorization: `Bearer ${authToken}`,
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ }
}
export default NetworkService;
diff --git a/Client/src/Utils/timeUtils.js b/Client/src/Utils/timeUtils.js
index da2f7f9bb..87f85e37a 100644
--- a/Client/src/Utils/timeUtils.js
+++ b/Client/src/Utils/timeUtils.js
@@ -4,6 +4,12 @@ import timezone from "dayjs/plugin/timezone";
dayjs.extend(utc);
dayjs.extend(timezone);
+export const MS_PER_SECOND = 1000;
+export const MS_PER_MINUTE = 60 * MS_PER_SECOND;
+export const MS_PER_HOUR = 60 * MS_PER_MINUTE;
+export const MS_PER_DAY = 24 * MS_PER_HOUR;
+export const MS_PER_WEEK = MS_PER_DAY * 7;
+
export const formatDuration = (ms) => {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
diff --git a/Client/src/Validation/validation.js b/Client/src/Validation/validation.js
index 25ad79923..89b1d0f8f 100644
--- a/Client/src/Validation/validation.js
+++ b/Client/src/Validation/validation.js
@@ -1,4 +1,5 @@
import joi from "joi";
+import dayjs from "dayjs";
const nameSchema = joi
.string()
@@ -113,50 +114,33 @@ const imageValidation = joi.object({
}),
});
-const maintenanceWindowValidation = joi.object({
- repeat: joi.number().valid(1, 2, 3).required().messages({
- "number.base": "Repeat must be a number.",
- "any.only": "Repeat must be one of [1, 2, 3].",
- "any.required": "Repeat is required.",
- }),
- date: joi.date().required().messages({
- "date.base": "Date must be a valid date.",
- "any.required": "Date is required.",
- }),
- startTime: joi.string().required().messages({
- "string.base": "Start time must be a valid time.",
- "any.required": "Start time is required.",
- }),
- duration: joi.number().required().messages({
- "number.empty": "duration is required.",
- "number.base": "Duration must be a number.",
- "any.required": "Duration is required.",
- }),
- unit: joi.string().valid("minutes", "hours", "days").required().messages({
- "string.base": "Unit must be a string.",
- "any.only": "Unit must be one of ['minutes', 'hours', 'days'].",
- "any.required": "Unit is required.",
- }),
- displayName: joi.string().max(50).required().messages({
- "string.empty": "Display name is required.",
- "string.max": "Display name must be less than 50 characters long",
- }),
- addMonitors: joi.string().max(50).required().messages({
- "string.empty": "Add monitors is required.",
- "string.max": "Add monitors must be less than 50 characters long",
- }),
-});
-
const settingsValidation = joi.object({
ttl: joi.number().required().messages({
"string.empty": "TTL is required",
}),
});
+const dayjsValidator = (value, helpers) => {
+ if (!dayjs(value).isValid()) {
+ return helpers.error("any.invalid");
+ }
+ return value;
+};
+
+const maintenanceWindowValidation = joi.object({
+ repeat: joi.string(),
+ startDate: joi.custom(dayjsValidator, "Day.js date validation"),
+ startTime: joi.custom(dayjsValidator, "Day.js date validation"),
+ duration: joi.number(),
+ durationUnit: joi.string(),
+ name: joi.string(),
+ monitors: joi.array().min(1),
+});
+
export {
credentials,
imageValidation,
monitorValidation,
- maintenanceWindowValidation,
settingsValidation,
+ maintenanceWindowValidation,
};
diff --git a/Client/src/assets/icons/calendar.svg b/Client/src/assets/icons/calendar.svg
new file mode 100644
index 000000000..be023a4de
--- /dev/null
+++ b/Client/src/assets/icons/calendar.svg
@@ -0,0 +1,3 @@
+
diff --git a/Server/controllers/maintenanceWindowController.js b/Server/controllers/maintenanceWindowController.js
index 775c04728..7dc130b7c 100644
--- a/Server/controllers/maintenanceWindowController.js
+++ b/Server/controllers/maintenanceWindowController.js
@@ -1,17 +1,19 @@
const {
- createMaintenanceWindowParamValidation,
createMaintenanceWindowBodyValidation,
- getMaintenanceWindowsByUserIdParamValidation,
+ editMaintenanceWindowByIdParamValidation,
+ editMaintenanceByIdWindowBodyValidation,
+ getMaintenanceWindowByIdParamValidation,
getMaintenanceWindowsByMonitorIdParamValidation,
+ getMaintenanceWindowsByTeamIdQueryValidation,
+ deleteMaintenanceWindowByIdParamValidation,
} = require("../validation/joi");
-
-const {successMessages} = require("../utils/messages")
-
+const jwt = require("jsonwebtoken");
+const { getTokenFromHeaders } = require("../utils/utils");
+const { successMessages } = require("../utils/messages");
const SERVICE_NAME = "maintenanceWindowController";
-const createMaintenanceWindow = async (req, res, next) => {
+const createMaintenanceWindows = async (req, res, next) => {
try {
- await createMaintenanceWindowParamValidation.validateAsync(req.params);
await createMaintenanceWindowBodyValidation.validateAsync(req.body);
} catch (error) {
error.status = 422;
@@ -21,23 +23,26 @@ const createMaintenanceWindow = async (req, res, next) => {
next(error);
return;
}
-
try {
- const data = {
- monitorId: req.params.monitorId,
- ...req.body,
- };
-
- if (data.oneTime === true) {
- data.expiry = data.end;
- }
-
- const maintenanceWindow = await req.db.createMaintenanceWindow(data);
-
+ const token = getTokenFromHeaders(req.headers);
+ const { jwtSecret } = req.settingsService.getSettings();
+ const { teamId } = jwt.verify(token, jwtSecret);
+ const monitorIds = req.body.monitors;
+ const dbTransactions = monitorIds.map((monitorId) => {
+ return req.db.createMaintenanceWindow({
+ teamId,
+ monitorId,
+ name: req.body.name,
+ active: req.body.active ? req.body.active : true,
+ repeat: req.body.repeat,
+ start: req.body.start,
+ end: req.body.end,
+ });
+ });
+ await Promise.all(dbTransactions);
return res.status(201).json({
success: true,
msg: successMessages.MAINTENANCE_WINDOW_CREATE,
- data: maintenanceWindow,
});
} catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
@@ -48,11 +53,9 @@ const createMaintenanceWindow = async (req, res, next) => {
}
};
-const getMaintenanceWindowsByUserId = async (req, res, next) => {
+const getMaintenanceWindowById = async (req, res, next) => {
try {
- await getMaintenanceWindowsByUserIdParamValidation.validateAsync(
- req.params
- );
+ await getMaintenanceWindowByIdParamValidation.validateAsync(req.params);
} catch (error) {
error.status = 422;
error.service = SERVICE_NAME;
@@ -62,13 +65,47 @@ const getMaintenanceWindowsByUserId = async (req, res, next) => {
return;
}
try {
- const maintenanceWindows = await req.db.getMaintenanceWindowsByUserId(
- req.params.userId
+ const maintenanceWindow = await req.db.getMaintenanceWindowById(
+ req.params.id
+ );
+ return res.status(200).json({
+ success: true,
+ msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID,
+ data: maintenanceWindow,
+ });
+ } catch (error) {
+ error.service === undefined ? (error.service = SERVICE_NAME) : null;
+ error.method === undefined
+ ? (error.method = "getMaintenanceWindowById")
+ : null;
+ next(error);
+ }
+};
+
+const getMaintenanceWindowsByTeamId = async (req, res, next) => {
+ try {
+ await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query);
+ } catch (error) {
+ error.status = 422;
+ error.service = SERVICE_NAME;
+ error.message =
+ error.details?.[0]?.message || error.message || "Validation Error";
+ next(error);
+ return;
+ }
+
+ try {
+ const token = getTokenFromHeaders(req.headers);
+ const { jwtSecret } = req.settingsService.getSettings();
+ const { teamId } = jwt.verify(token, jwtSecret);
+ const maintenanceWindows = await req.db.getMaintenanceWindowsByTeamId(
+ teamId,
+ req.query
);
return res.status(201).json({
success: true,
- msg: successMessages.MAINTENANCE_WINDOW_GET_BY_USER,
+ msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM,
data: maintenanceWindows,
});
} catch (error) {
@@ -112,8 +149,67 @@ const getMaintenanceWindowsByMonitorId = async (req, res, next) => {
next(error);
}
};
-module.exports = {
- createMaintenanceWindow,
- getMaintenanceWindowsByUserId,
- getMaintenanceWindowsByMonitorId,
+
+const deleteMaintenanceWindow = async (req, res, next) => {
+ try {
+ await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params);
+ } catch (error) {
+ error.status = 422;
+ error.service = SERVICE_NAME;
+ error.message =
+ error.details?.[0]?.message || error.message || "Validation Error";
+ next(error);
+ return;
+ }
+ try {
+ await req.db.deleteMaintenanceWindowById(req.params.id);
+ return res.status(201).json({
+ success: true,
+ msg: successMessages.MAINTENANCE_WINDOW_DELETE,
+ });
+ } catch (error) {
+ error.service === undefined ? (error.service = SERVICE_NAME) : null;
+ error.method === undefined
+ ? (error.method = "deleteMaintenanceWindow")
+ : null;
+ }
+};
+
+const editMaintenanceWindow = async (req, res, next) => {
+ try {
+ await editMaintenanceWindowByIdParamValidation.validateAsync(req.params);
+ await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body);
+ } catch (error) {
+ error.status = 422;
+ error.service = SERVICE_NAME;
+ error.message =
+ error.details?.[0]?.message || error.message || "Validation Error";
+ next(error);
+ return;
+ }
+ try {
+ const editedMaintenanceWindow = await req.db.editMaintenanceWindowById(
+ req.params.id,
+ req.body
+ );
+ return res.status(200).json({
+ success: true,
+ msg: successMessages.MAINTENANCE_WINDOW_EDIT,
+ data: editedMaintenanceWindow,
+ });
+ } catch (error) {
+ error.service === undefined ? (error.service = SERVICE_NAME) : null;
+ error.method === undefined
+ ? (error.method = "editMaintenanceWindow")
+ : null;
+ }
+};
+
+module.exports = {
+ createMaintenanceWindows,
+ getMaintenanceWindowById,
+ getMaintenanceWindowsByTeamId,
+ getMaintenanceWindowsByMonitorId,
+ deleteMaintenanceWindow,
+ editMaintenanceWindow,
};
diff --git a/Server/db/models/MaintenanceWindow.js b/Server/db/models/MaintenanceWindow.js
index f6be12f67..3727d3b40 100644
--- a/Server/db/models/MaintenanceWindow.js
+++ b/Server/db/models/MaintenanceWindow.js
@@ -6,7 +6,7 @@ const mongoose = require("mongoose");
* @typedef {Object} MaintenanceWindow
* @property {mongoose.Schema.Types.ObjectId} monitorId - The ID of the monitor. This is a reference to the Monitor model and is immutable.
* @property {Boolean} active - Indicates whether the maintenance window is active.
- * @property {Boolean} oneTime - Indicates whether the maintenance window is a one-time event.
+ * @property {Number} repeat - Indicates how often this maintenance window should repeat.
* @property {Date} start - The start date and time of the maintenance window.
* @property {Date} end - The end date and time of the maintenance window.
* @property {Date} expiry - The expiry date and time of the maintenance window. This is used for MongoDB's TTL index to automatically delete the document at this time. This field is set to the same value as `end` when `oneTime` is `true`.
@@ -16,12 +16,12 @@ const mongoose = require("mongoose");
* let maintenanceWindow = new MaintenanceWindow({
* monitorId: monitorId,
* active: active,
- * oneTime: oneTime,
+ * repeat: repeat,
* start: start,
* end: end,
* });
*
- * if (oneTime) {
+ * if (repeat === 0) {
* maintenanceWindow.expiry = end;
* }
*
@@ -34,16 +34,20 @@ const MaintenanceWindow = mongoose.Schema(
ref: "Monitor",
immutable: true,
},
- userId: {
+ teamId: {
type: mongoose.Schema.Types.ObjectId,
- ref: "User",
+ ref: "Team",
immutable: true,
},
active: {
type: Boolean,
+ default: true,
},
- oneTime: {
- type: Boolean,
+ name: {
+ type: String,
+ },
+ repeat: {
+ type: Number,
},
start: {
type: Date,
diff --git a/Server/db/mongo/MongoDB.js b/Server/db/mongo/MongoDB.js
index aeb993433..21d3b8c46 100644
--- a/Server/db/mongo/MongoDB.js
+++ b/Server/db/mongo/MongoDB.js
@@ -118,12 +118,14 @@ const {
//****************************************
const {
createMaintenanceWindow,
- getMaintenanceWindowsByUserId,
+ getMaintenanceWindowById,
+ getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId,
- deleteMaintenaceWindowById,
+ deleteMaintenanceWindowById,
deleteMaintenanceWindowByMonitorId,
deleteMaintenanceWindowByUserId,
-} = require("./modules/maintenaceWindowModule");
+ editMaintenanceWindowById,
+} = require("./modules/maintenanceWindowModule");
//****************************************
// Notifications
@@ -181,11 +183,13 @@ module.exports = {
getPageSpeedChecks,
deletePageSpeedChecksByMonitorId,
createMaintenanceWindow,
- getMaintenanceWindowsByUserId,
+ getMaintenanceWindowsByTeamId,
+ getMaintenanceWindowById,
getMaintenanceWindowsByMonitorId,
- deleteMaintenaceWindowById,
+ deleteMaintenanceWindowById,
deleteMaintenanceWindowByMonitorId,
deleteMaintenanceWindowByUserId,
+ editMaintenanceWindowById,
createNotification,
getNotificationsByMonitorId,
deleteNotificationsByMonitorId,
diff --git a/Server/db/mongo/modules/maintenaceWindowModule.js b/Server/db/mongo/modules/maintenanceWindowModule.js
similarity index 73%
rename from Server/db/mongo/modules/maintenaceWindowModule.js
rename to Server/db/mongo/modules/maintenanceWindowModule.js
index f49c9dca4..5eb3e1ea7 100644
--- a/Server/db/mongo/modules/maintenaceWindowModule.js
+++ b/Server/db/mongo/modules/maintenanceWindowModule.js
@@ -36,7 +36,7 @@ const createMaintenanceWindow = async (maintenanceWindowData) => {
if (maintenanceWindowData.oneTime) {
maintenanceWindow.expiry = maintenanceWindowData.end;
}
- const result = maintenanceWindow.save();
+ const result = await maintenanceWindow.save();
return result;
} catch (error) {
error.service = SERVICE_NAME;
@@ -45,22 +45,60 @@ const createMaintenanceWindow = async (maintenanceWindowData) => {
}
};
+const getMaintenanceWindowById = async (maintenanceWindowId) => {
+ try {
+ const maintenanceWindow = await MaintenanceWindow.findById({
+ _id: maintenanceWindowId,
+ });
+ return maintenanceWindow;
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "getMaintenanceWindowById";
+ throw error;
+ }
+};
+
/**
- * Asynchronously retrieves all MaintenanceWindow documents associated with a specific user ID.
+ * Asynchronously retrieves all MaintenanceWindow documents associated with a specific team ID.
* @async
* @function getMaintenanceWindowByUserId
- * @param {String} userId - The ID of the user.
+ * @param {String} teamId - The ID of the team.
+ * @param {Object} query - The request body.
* @returns {Promise>} An array of MaintenanceWindow documents.
* @throws {Error} If there is an error retrieving the documents.
* @example
- * getMaintenanceWindowByUserId('userId')
+ * getMaintenanceWindowByUserId(teamId)
* .then(maintenanceWindows => console.log(maintenanceWindows))
* .catch(error => console.error(error));
*/
-const getMaintenanceWindowsByUserId = async (userId) => {
+const getMaintenanceWindowsByTeamId = async (teamId, query) => {
try {
- const maintenanceWindows = await MaintenanceWindow.find({ userId: userId });
- return maintenanceWindows;
+ let { active, page, rowsPerPage, field, order } = query || {};
+ const maintenanceQuery = { teamId };
+
+ if (active !== undefined) maintenanceQuery.active = active;
+
+ const maintenanceWindowCount =
+ await MaintenanceWindow.countDocuments(maintenanceQuery);
+
+ // Pagination
+ let skip = 0;
+ if (page && rowsPerPage) {
+ skip = page * rowsPerPage;
+ }
+
+ // Sorting
+ let sort = {};
+ if (field !== undefined && order !== undefined) {
+ sort[field] = order === "asc" ? 1 : -1;
+ }
+
+ const maintenanceWindows = await MaintenanceWindow.find(maintenanceQuery)
+ .skip(skip)
+ .limit(rowsPerPage)
+ .sort(sort);
+
+ return { maintenanceWindows, maintenanceWindowCount };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowByUserId";
@@ -96,23 +134,23 @@ const getMaintenanceWindowsByMonitorId = async (monitorId) => {
/**
* Asynchronously deletes a MaintenanceWindow document by its ID.
* @async
- * @function deleteMaintenaceWindowById
+ * @function deleteMaintenanceWindowById
* @param {mongoose.Schema.Types.ObjectId} maintenanceWindowId - The ID of the MaintenanceWindow document to delete.
* @returns {Promise} The deleted MaintenanceWindow document.
* @throws {Error} If there is an error deleting the document.
* @example
- * deleteMaintenaceWindowById('maintenanceWindowId')
+ * deleteMaintenanceWindowById('maintenanceWindowId')
* .then(maintenanceWindow => console.log(maintenanceWindow))
* .catch(error => console.error(error));
*/
-const deleteMaintenaceWindowById = async (maintenanceWindowId) => {
+const deleteMaintenanceWindowById = async (maintenanceWindowId) => {
try {
const maintenanceWindow =
await MaintenanceWindow.findByIdAndDelete(maintenanceWindowId);
return maintenanceWindow;
} catch (error) {
error.service = SERVICE_NAME;
- error.method = "deleteMaintenaceWindowById";
+ error.method = "deleteMaintenanceWindowById";
throw error;
}
};
@@ -163,11 +201,32 @@ const deleteMaintenanceWindowByUserId = async (userId) => {
}
};
+const editMaintenanceWindowById = async (
+ maintenanceWindowId,
+ maintenanceWindowData
+) => {
+ console.log(maintenanceWindowData);
+ try {
+ const editedMaintenanceWindow = MaintenanceWindow.findByIdAndUpdate(
+ maintenanceWindowId,
+ maintenanceWindowData,
+ { new: true }
+ );
+ return editedMaintenanceWindow;
+ } catch (error) {
+ error.service = SERVICE_NAME;
+ error.method = "editMaintenanceWindowById";
+ throw error;
+ }
+};
+
module.exports = {
createMaintenanceWindow,
- getMaintenanceWindowsByUserId,
+ getMaintenanceWindowById,
+ getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId,
- deleteMaintenaceWindowById,
+ deleteMaintenanceWindowById,
deleteMaintenanceWindowByMonitorId,
deleteMaintenanceWindowByUserId,
+ editMaintenanceWindowById,
};
diff --git a/Server/routes/maintenanceWindowRoute.js b/Server/routes/maintenanceWindowRoute.js
index 8ed15b609..ceb27d548 100644
--- a/Server/routes/maintenanceWindowRoute.js
+++ b/Server/routes/maintenanceWindowRoute.js
@@ -3,21 +3,20 @@ const maintenanceWindowController = require("../controllers/maintenanceWindowCon
const { verifyOwnership } = require("../middleware/verifyOwnership");
const Monitor = require("../db/models/Monitor");
+router.post("/", maintenanceWindowController.createMaintenanceWindows);
+
router.get(
"/monitor/:monitorId",
verifyOwnership(Monitor, "monitorId"),
maintenanceWindowController.getMaintenanceWindowsByMonitorId
);
-router.post(
- "/monitor/:monitorId",
- verifyOwnership(Monitor, "monitorId"),
- maintenanceWindowController.createMaintenanceWindow
-);
+router.get("/team/", maintenanceWindowController.getMaintenanceWindowsByTeamId);
-router.get(
- "/user/:userId",
- maintenanceWindowController.getMaintenanceWindowsByUserId
-);
+router.get("/:id", maintenanceWindowController.getMaintenanceWindowById);
+
+router.put("/:id", maintenanceWindowController.editMaintenanceWindow);
+
+router.delete("/:id", maintenanceWindowController.deleteMaintenanceWindow);
module.exports = router;
diff --git a/Server/service/jobQueue.js b/Server/service/jobQueue.js
index 58d628a2e..66db548db 100644
--- a/Server/service/jobQueue.js
+++ b/Server/service/jobQueue.js
@@ -77,14 +77,21 @@ class JobQueue {
const monitorId = job.data._id;
const maintenanceWindows =
await this.db.getMaintenanceWindowsByMonitorId(monitorId);
-
// Check for active maintenance window:
const maintenanceWindowActive = maintenanceWindows.reduce(
(acc, window) => {
if (window.active) {
const start = new Date(window.start);
const end = new Date(window.end);
- if (start < new Date() && end > new Date()) {
+ const now = new Date();
+ const repeatInterval = window.repeat || 0;
+
+ while ((start < now) & (repeatInterval !== 0)) {
+ start.setTime(start.getTime() + repeatInterval);
+ end.setTime(end.getTime() + repeatInterval);
+ }
+
+ if (start < now && end > now) {
return true;
}
}
@@ -139,9 +146,7 @@ class JobQueue {
return { jobs, load };
} catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
- error.method === undefined
- ? (error.method = "getWorkerStats")
- : null;
+ error.method === undefined ? (error.method = "getWorkerStats") : null;
throw error;
}
}
diff --git a/Server/utils/messages.js b/Server/utils/messages.js
index f9d345c74..16b2f7883 100644
--- a/Server/utils/messages.js
+++ b/Server/utils/messages.js
@@ -93,9 +93,12 @@ const successMessages = {
JOB_QUEUE_RESUME_JOB: "Job resumed successfully",
//Maintenance Window Controller
+ MAINTENANCE_WINDOW_GET_BY_ID: "Got Maintenance Window by Id successfully",
MAINTENANCE_WINDOW_CREATE: "Maintenance Window created successfully",
- MAINTENANCE_WINDOW_GET_BY_USER:
- "Got Maintenance Windows by User successfully",
+ MAINTENANCE_WINDOW_GET_BY_TEAM:
+ "Got Maintenance Windows by Team successfully",
+ MAINTENANCE_WINDOW_DELETE: "Maintenance Window deleted successfully",
+ MAINTENANCE_WINDOW_EDIT: "Maintenance Window edited successfully",
//Ping Operations
PING_SUCCESS: "Success",
diff --git a/Server/validation/joi.js b/Server/validation/joi.js
index 1af324008..3133da80a 100644
--- a/Server/validation/joi.js
+++ b/Server/validation/joi.js
@@ -1,5 +1,7 @@
+const exp = require("constants");
const joi = require("joi");
const { normalize } = require("path");
+const { start } = require("repl");
//****************************************
// Custom Validators
@@ -361,27 +363,51 @@ const deletePageSpeedCheckParamValidation = joi.object({
//****************************************
// MaintenanceWindowValidation
//****************************************
-const createMaintenanceWindowParamValidation = joi.object({
- monitorId: joi.string().required(),
-});
const createMaintenanceWindowBodyValidation = joi.object({
- userId: joi.string().required(),
- active: joi.boolean().required(),
- oneTime: joi.boolean().required(),
+ monitors: joi.array().items(joi.string()).required(),
+ name: joi.string().required(),
+ active: joi.boolean(),
start: joi.date().required(),
end: joi.date().required(),
+ repeat: joi.number().required(),
expiry: joi.date(),
});
-const getMaintenanceWindowsByUserIdParamValidation = joi.object({
- userId: joi.string().required(),
+const getMaintenanceWindowByIdParamValidation = joi.object({
+ id: joi.string().required(),
+});
+
+const getMaintenanceWindowsByTeamIdQueryValidation = joi.object({
+ active: joi.boolean(),
+ page: joi.number(),
+ rowsPerPage: joi.number(),
+ field: joi.string(),
+ order: joi.string().valid("asc", "desc"),
});
const getMaintenanceWindowsByMonitorIdParamValidation = joi.object({
monitorId: joi.string().required(),
});
+const deleteMaintenanceWindowByIdParamValidation = joi.object({
+ id: joi.string().required(),
+});
+
+const editMaintenanceWindowByIdParamValidation = joi.object({
+ id: joi.string().required(),
+});
+
+const editMaintenanceByIdWindowBodyValidation = joi.object({
+ active: joi.boolean(),
+ name: joi.string(),
+ repeat: joi.number(),
+ start: joi.date(),
+ end: joi.date(),
+ expiry: joi.date(),
+ monitors: joi.array(),
+});
+
//****************************************
// SettingsValidation
//****************************************
@@ -447,9 +473,12 @@ module.exports = {
createPageSpeedCheckParamValidation,
deletePageSpeedCheckParamValidation,
createPageSpeedCheckBodyValidation,
- createMaintenanceWindowParamValidation,
createMaintenanceWindowBodyValidation,
- getMaintenanceWindowsByUserIdParamValidation,
+ getMaintenanceWindowByIdParamValidation,
+ getMaintenanceWindowsByTeamIdQueryValidation,
getMaintenanceWindowsByMonitorIdParamValidation,
+ deleteMaintenanceWindowByIdParamValidation,
+ editMaintenanceWindowByIdParamValidation,
+ editMaintenanceByIdWindowBodyValidation,
updateAppSettingsBodyValidation,
};