diff --git a/Client/src/Pages/Incidents/index.jsx b/Client/src/Pages/Incidents/index.jsx index da9851d11..17f0323aa 100644 --- a/Client/src/Pages/Incidents/index.jsx +++ b/Client/src/Pages/Incidents/index.jsx @@ -1,180 +1,135 @@ -import * as React from "react"; -import TextField from "@mui/material/TextField"; -import Autocomplete, { createFilterOptions } from "@mui/material/Autocomplete"; -import { useTheme } from "@mui/material/styles"; -import Box from "@mui/material/Box"; -import Typography from "@mui/material/Typography"; -import TuneIcon from "@mui/icons-material/Tune"; -import { StatusLabel } from "../../Components/Label/"; +import { useState, useEffect } from "react"; +import { useSelector } from "react-redux"; +import { Select, MenuItem, Typography, ButtonGroup } from "@mui/material"; -const filterOptions = createFilterOptions({ - matchFrom: "start", - stringify: (option) => option.title, -}); +import Button from "../../Components/Button"; +import axiosInstance from "../../Utils/axiosConfig"; +import BasicTable from "../../Components/BasicTable"; +import { StatusLabel } from "../../Components/Label"; -const titles = [ - { title: "Down" }, - { title: "Cannot resolve" }, - { title: "Clear / show all" }, -]; +const Incidents = () => { + const authState = useSelector((state) => state.auth); + const [monitors, setMonitors] = useState({}); + const [selectedMonitor, setSelectedMonitor] = useState("0"); -/** - * Filter component with autocomplete for status filtering. - * @returns {JSX.Element} The JSX element representing the filter component. - */ -function Filter() { - return ( - option.title} - filterOptions={filterOptions} - sx={{ - width: 170, - "& .MuiAutocomplete-inputRoot": { - height: "50px", - }, - "& .MuiAutocomplete-listbox": { - maxHeight: "200px", - }, - }} - disableClearable - renderInput={(params) => ( - - { + const fetchIncidents = async () => { + const res = await axiosInstance.get( + `/monitors/incidents/user/${authState.user._id}`, + { + headers: { + Authorization: `Bearer ${authState.authToken}`, + }, + } + ); + + // Reduce to a lookup object for 0(1) lookup + if (res.data && res.data.data.length > 0) { + const monitorLookup = res.data.data.reduce((acc, monitor) => { + acc[monitor._id] = monitor; + return acc; + }, {}); + setMonitors(monitorLookup); + } + }; + + fetchIncidents(); + }, [authState]); + + const handleSelect = (event) => { + setSelectedMonitor(event.target.value); + }; + let incidents = []; + if (selectedMonitor === "0") { + Object.values(monitors).forEach((monitor) => { + incidents = incidents.concat(monitor.checks); + }); + } else { + const monitor = monitors[selectedMonitor]; + incidents = monitor.checks; + } + incidents = incidents + .sort((a, b) => { + return new Date(b.createdAt) - new Date(a.createdAt); + }) + .map((incident, idx) => { + const params = { + status: "Down", + backgroundColor: "var(--env-var-color-21)", + statusDotColor: "var(--env-var-color-19)", + }; + + return { + id: idx, + data: [ + { + id: idx + 0, + data: ( + - Filter by status - - } - InputProps={{ ...params.InputProps, endAdornment: null }} - /> - )} - /> - ); -} - -const sampleData = [ - { - name: ( - - ), - date: "2024-03-14 21:41:09", - message: "HTTP 350 - NOK", - }, - { - name: ( - - ), - date: "2024-03-14 21:41:09", - message: "timeout of 48000ms exceeded", - }, - { - name: ( - - ), - date: "2024-03-14 21:41:09", - message: "timeout of 48000ms exceeded", - }, - { - name: ( - - ), - date: "2024-03-14 21:41:09", - message: "timeout of 48000ms exceeded", - }, - { - name: ( - - ), - date: "2024-03-14 21:41:09", - message: "HTTP 350 - NOK", - }, -]; - -const columns = [ - { id: "name", header: "Status" }, - { id: "date", header: "Date & Time" }, - { id: "message", header: "Message" }, -]; - -/** - * Customized table component displaying incident history with a filter. - * @returns {JSX.Element} The JSX element representing the customized table with a filter. - */ -export default function CustomizedTables() { - const theme = useTheme(); + ), + }, + { id: idx + 1, data: new Date(incident.createdAt).toLocaleString() }, + { id: idx + 2, data: incident.statusCode }, + { id: idx + 3, data: monitors[incident.monitorId].name }, + ], + }; + }); + data.rows = incidents; return ( - - - - Incident History - - - - {/* TODO Replace with BasicTable */} - {/* */} - +
+
+
+ Incident history for: + +
+ +
+ +
); -} +}; + +export default Incidents; diff --git a/Server/controllers/monitorController.js b/Server/controllers/monitorController.js index 52433c8d7..45a55a973 100644 --- a/Server/controllers/monitorController.js +++ b/Server/controllers/monitorController.js @@ -98,6 +98,60 @@ const getMonitorsByUserId = async (req, res, next) => { } }; +/** + * Returns monitor with matching ID and incidents + * @async + * @param {Express.Request} req + * @param {Express.Response} res + * @returns {Promise} + * @throws {Error} + */ +const getMonitorByIdForIncidents = async (req, res, next) => { + try { + await getMonitorByIdValidation.validateAsync(req.params); + + let monitorWithIncidents = await req.db.getMonitorByIdForIncidents( + req, + res + ); + + return res.json({ + success: true, + msg: successMessages.MONTIOR_GET_BY_ID, + data: monitorWithIncidents, + }); + } catch (error) { + error.service = SERVICE_NAME; + next(error); + } +}; + +/** + * Returns all monitors with incidents that belong to User with UserID + * @async + * @param {Express.Request} req + * @param {Express.Response} res + * @returns {Promise} + * @throws {Error} + */ +const getMonitorsByUserIdForIncidents = async (req, res, next) => { + try { + await getMonitorsByUserIdValidation.validateAsync(req.params); + let monitorsWithIncidents = await req.db.getMonitorsByUserIdForIncidents( + req, + res + ); + return res.json({ + success: true, + msg: successMessages.MONITOR_GET_BY_USER_ID(req.params.userId), + data: monitorsWithIncidents, + }); + } catch (error) { + error.service = SERVICE_NAME; + next(error); + } +}; + /** * Creates a new monitor * @async @@ -227,6 +281,8 @@ module.exports = { getAllMonitors, getMonitorById, getMonitorsByUserId, + getMonitorByIdForIncidents, + getMonitorsByUserIdForIncidents, createMonitor, deleteMonitor, deleteAllMonitors, diff --git a/Server/db/MongoDB.js b/Server/db/MongoDB.js index 52dc59084..104e49f38 100644 --- a/Server/db/MongoDB.js +++ b/Server/db/MongoDB.js @@ -131,7 +131,6 @@ const updateUser = async (req, res) => { ) .select("-password") .select("-profileImage"); - console.log(updatedUser); return updatedUser; } catch (error) { throw error; @@ -349,6 +348,59 @@ const getMonitorsByUserId = async (req, res) => { } }; +/** + * Get monitors by UserID + * @async + * @param {Express.Request} req + * @param {Express.Response} res + * @returns {Promise} + * @throws {Error} + */ +const getMonitorByIdForIncidents = async (req, res, next) => { + try { + const monitor = await Monitor.findById(req.params.monitorId); + const checks = await Check.find({ + monitorId: monitor._id, + status: false, + }).sort({ + createdAt: 1, + }); + const monitorWithChecks = { ...monitor.toObject(), checks }; + return monitorWithChecks; + } catch (error) { + throw error; + } +}; + +/** + * Get monitors by UserID + * @async + * @param {Express.Request} req + * @param {Express.Response} res + * @returns {Promise>} + * @throws {Error} + */ +const getMonitorsByUserIdForIncidents = async (req, res) => { + try { + const monitors = await Monitor.find({ userId: req.params.userId }); + // Map each monitor to include its associated checks + const monitorsWithChecks = await Promise.all( + monitors.map(async (monitor) => { + const checks = await Check.find({ + monitorId: monitor._id, + status: false, + }).sort({ + createdAt: 1, + }); + return { ...monitor.toObject(), checks }; + }) + ); + return monitorsWithChecks; + } catch (error) { + throw error; + } +}; + /** * Create a monitor * @async @@ -459,7 +511,6 @@ const editMonitor = async (req, res) => { const createCheck = async (checkData) => { try { - console.log(checkData); const check = await new Check({ ...checkData }).save(); return check; } catch (error) { @@ -649,6 +700,8 @@ module.exports = { getAllMonitors, getMonitorById, getMonitorsByUserId, + getMonitorByIdForIncidents, + getMonitorsByUserIdForIncidents, createMonitor, deleteMonitor, deleteAllMonitors, diff --git a/Server/routes/monitorRoute.js b/Server/routes/monitorRoute.js index ae7a5852e..9ba703244 100644 --- a/Server/routes/monitorRoute.js +++ b/Server/routes/monitorRoute.js @@ -7,6 +7,15 @@ router.get("/", monitorController.getAllMonitors); router.get("/:monitorId", monitorController.getMonitorById); router.get("/user/:userId", monitorController.getMonitorsByUserId); +router.get( + "/incidents/:monitorId", + monitorController.getMonitorByIdForIncidents +); +router.get( + "/incidents/user/:userId", + monitorController.getMonitorsByUserIdForIncidents +); + router.post("/", monitorController.createMonitor); router.post( "/delete/:monitorId",