Merge pull request #420 from bluewave-labs/feat/incidents

Feat/incidents
This commit is contained in:
Alexander Holliday authored and GitHub committed 2024-07-22 19:34:42 -07:00
commit 6911e67b8c
4 files changed
+248 -175

No files matched your search

+128 -173
View File
@@ -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 (
<Autocomplete
id="filter-demo"
options={titles}
getOptionLabel={(option) => option.title}
filterOptions={filterOptions}
sx={{
width: 170,
"& .MuiAutocomplete-inputRoot": {
height: "50px",
},
"& .MuiAutocomplete-listbox": {
maxHeight: "200px",
},
}}
disableClearable
renderInput={(params) => (
<TextField
{...params}
size="small"
label={
<React.Fragment>
<TuneIcon
sx={{ marginRight: "0.5rem", position: "relative", top: "6px" }}
// TODO do something with these filters
const [filter, setFilter] = useState("all");
let data = {
cols: [
{ id: 1, name: "Status" },
{ id: 2, name: "Timestamp" },
{ id: 3, name: "Monitor" },
{ id: 4, name: "Message" },
],
rows: [],
};
useEffect(() => {
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: (
<StatusLabel
status={params.status}
dot={params.statusDotColor}
customStyles={{ backgroundColor: params.backgroundColor }}
/>
Filter by status
</React.Fragment>
}
InputProps={{ ...params.InputProps, endAdornment: null }}
/>
)}
/>
);
}
const sampleData = [
{
name: (
<StatusLabel
status="Down"
customStyles={{
backgroundColor: "#fff9f9",
borderColor: "#ffcac6",
color: "#344054",
}}
/>
),
date: "2024-03-14 21:41:09",
message: "HTTP 350 - NOK",
},
{
name: (
<StatusLabel
status="Down"
customStyles={{
backgroundColor: "#fff9f9",
borderColor: "#ffcac6",
color: "#344054",
}}
/>
),
date: "2024-03-14 21:41:09",
message: "timeout of 48000ms exceeded",
},
{
name: (
<StatusLabel
status="Cannot resolve"
customStyles={{
backgroundColor: "#f2f4f7",
borderColor: "#d2d6de",
color: "#344054",
}}
/>
),
date: "2024-03-14 21:41:09",
message: "timeout of 48000ms exceeded",
},
{
name: (
<StatusLabel
status="Cannot resolve"
customStyles={{
backgroundColor: "#f2f4f7",
borderColor: "#d2d6de",
color: "#344054",
}}
/>
),
date: "2024-03-14 21:41:09",
message: "timeout of 48000ms exceeded",
},
{
name: (
<StatusLabel
status="Down"
customStyles={{
backgroundColor: "#fff9f9",
borderColor: "#ffcac6",
color: "#344054",
}}
/>
),
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 (
<Box
sx={{
marginTop: theme.spacing(4),
marginX: "auto",
width: "80%",
paddingX: theme.spacing(6),
[theme.breakpoints.down("md")]: {
width: "100%",
},
}}
>
<Box
sx={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: theme.spacing(2),
}}
>
<Typography
variant="h6"
component="div"
sx={{ fontWeight: 600, fontSize: 16 }}
>
Incident History
</Typography>
<Filter />
</Box>
{/* TODO Replace with BasicTable */}
{/* <StatusTable data={sampleData} columns={columns} /> */}
</Box>
<div>
<div style={{ display: "flex", justifyContent: "space-between" }}>
<div style={{ display: "flex" }}>
<Typography>Incident history for: </Typography>
<Select value={selectedMonitor} onChange={handleSelect}>
<MenuItem value={"0"}>All servers</MenuItem>
{Object.values(monitors).map((monitor) => {
return (
<MenuItem key={monitor._id} value={monitor._id}>
{monitor.name}
</MenuItem>
);
})}
</Select>
</div>
<ButtonGroup>
<Button
level="secondary"
label="All"
onClick={() => setFilter("all")}
/>
<Button
level="secondary"
label="Down"
onClick={() => setFilter("down")}
/>
<Button
level="secondary"
label="Cannot Resolve"
onClick={() => setFilter("resolve")}
/>
</ButtonGroup>
</div>
<BasicTable data={data} paginated={true} />
</div>
);
}
};
export default Incidents;
+56
View File
@@ -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<Express.Response>}
* @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<Express.Response>}
* @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,
+55 -2
View File
@@ -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<Monitor>}
* @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<Array<Monitor>>}
* @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,
+9
View File
@@ -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",