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 { useState, useEffect } from "react";
import TextField from "@mui/material/TextField"; import { useSelector } from "react-redux";
import Autocomplete, { createFilterOptions } from "@mui/material/Autocomplete"; import { Select, MenuItem, Typography, ButtonGroup } from "@mui/material";
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/";
const filterOptions = createFilterOptions({ import Button from "../../Components/Button";
matchFrom: "start", import axiosInstance from "../../Utils/axiosConfig";
stringify: (option) => option.title, import BasicTable from "../../Components/BasicTable";
}); import { StatusLabel } from "../../Components/Label";
const titles = [ const Incidents = () => {
{ title: "Down" }, const authState = useSelector((state) => state.auth);
{ title: "Cannot resolve" }, const [monitors, setMonitors] = useState({});
{ title: "Clear / show all" }, const [selectedMonitor, setSelectedMonitor] = useState("0");
];
/** // TODO do something with these filters
* Filter component with autocomplete for status filtering. const [filter, setFilter] = useState("all");
* @returns {JSX.Element} The JSX element representing the filter component.
*/ let data = {
function Filter() { cols: [
return ( { id: 1, name: "Status" },
<Autocomplete { id: 2, name: "Timestamp" },
id="filter-demo" { id: 3, name: "Monitor" },
options={titles} { id: 4, name: "Message" },
getOptionLabel={(option) => option.title} ],
filterOptions={filterOptions} rows: [],
sx={{ };
width: 170,
"& .MuiAutocomplete-inputRoot": { useEffect(() => {
height: "50px", const fetchIncidents = async () => {
}, const res = await axiosInstance.get(
"& .MuiAutocomplete-listbox": { `/monitors/incidents/user/${authState.user._id}`,
maxHeight: "200px", {
}, headers: {
}} Authorization: `Bearer ${authState.authToken}`,
disableClearable },
renderInput={(params) => ( }
<TextField );
{...params}
size="small" // Reduce to a lookup object for 0(1) lookup
label={ if (res.data && res.data.data.length > 0) {
<React.Fragment> const monitorLookup = res.data.data.reduce((acc, monitor) => {
<TuneIcon acc[monitor._id] = monitor;
sx={{ marginRight: "0.5rem", position: "relative", top: "6px" }} 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> },
} { id: idx + 1, data: new Date(incident.createdAt).toLocaleString() },
InputProps={{ ...params.InputProps, endAdornment: null }} { id: idx + 2, data: incident.statusCode },
/> { id: idx + 3, data: monitors[incident.monitorId].name },
)} ],
/> };
); });
} data.rows = incidents;
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();
return ( return (
<Box <div>
sx={{ <div style={{ display: "flex", justifyContent: "space-between" }}>
marginTop: theme.spacing(4), <div style={{ display: "flex" }}>
marginX: "auto", <Typography>Incident history for: </Typography>
width: "80%", <Select value={selectedMonitor} onChange={handleSelect}>
paddingX: theme.spacing(6), <MenuItem value={"0"}>All servers</MenuItem>
[theme.breakpoints.down("md")]: { {Object.values(monitors).map((monitor) => {
width: "100%", return (
}, <MenuItem key={monitor._id} value={monitor._id}>
}} {monitor.name}
> </MenuItem>
<Box );
sx={{ })}
display: "flex", </Select>
justifyContent: "space-between", </div>
alignItems: "center", <ButtonGroup>
marginBottom: theme.spacing(2), <Button
}} level="secondary"
> label="All"
<Typography onClick={() => setFilter("all")}
variant="h6" />
component="div" <Button
sx={{ fontWeight: 600, fontSize: 16 }} level="secondary"
> label="Down"
Incident History onClick={() => setFilter("down")}
</Typography> />
<Filter /> <Button
</Box> level="secondary"
{/* TODO Replace with BasicTable */} label="Cannot Resolve"
{/* <StatusTable data={sampleData} columns={columns} /> */} onClick={() => setFilter("resolve")}
</Box> />
</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 * Creates a new monitor
* @async * @async
@@ -227,6 +281,8 @@ module.exports = {
getAllMonitors, getAllMonitors,
getMonitorById, getMonitorById,
getMonitorsByUserId, getMonitorsByUserId,
getMonitorByIdForIncidents,
getMonitorsByUserIdForIncidents,
createMonitor, createMonitor,
deleteMonitor, deleteMonitor,
deleteAllMonitors, deleteAllMonitors,
+55 -2
View File
@@ -131,7 +131,6 @@ const updateUser = async (req, res) => {
) )
.select("-password") .select("-password")
.select("-profileImage"); .select("-profileImage");
console.log(updatedUser);
return updatedUser; return updatedUser;
} catch (error) { } catch (error) {
throw 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 * Create a monitor
* @async * @async
@@ -459,7 +511,6 @@ const editMonitor = async (req, res) => {
const createCheck = async (checkData) => { const createCheck = async (checkData) => {
try { try {
console.log(checkData);
const check = await new Check({ ...checkData }).save(); const check = await new Check({ ...checkData }).save();
return check; return check;
} catch (error) { } catch (error) {
@@ -649,6 +700,8 @@ module.exports = {
getAllMonitors, getAllMonitors,
getMonitorById, getMonitorById,
getMonitorsByUserId, getMonitorsByUserId,
getMonitorByIdForIncidents,
getMonitorsByUserIdForIncidents,
createMonitor, createMonitor,
deleteMonitor, deleteMonitor,
deleteAllMonitors, deleteAllMonitors,
+9
View File
@@ -7,6 +7,15 @@ router.get("/", monitorController.getAllMonitors);
router.get("/:monitorId", monitorController.getMonitorById); router.get("/:monitorId", monitorController.getMonitorById);
router.get("/user/:userId", monitorController.getMonitorsByUserId); 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("/", monitorController.createMonitor);
router.post( router.post(
"/delete/:monitorId", "/delete/:monitorId",