Implemented pagination for incidents component

This commit is contained in:
Alex Holliday committed 2024-08-09 11:54:30 -07:00
1 parent 3924099e3e
commit 26e3f81a91
7 files changed
+131 -176

No files matched your search

@@ -6,10 +6,9 @@ import {
TableRow, TableRow,
TableCell, TableCell,
TableBody, TableBody,
TableFooter,
TablePagination,
Pagination, Pagination,
PaginationItem, PaginationItem,
Paper,
} from "@mui/material"; } from "@mui/material";
import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded"; import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
@@ -20,29 +19,29 @@ import { useSelector } from "react-redux";
import axiosInstance from "../../../Utils/axiosConfig"; import axiosInstance from "../../../Utils/axiosConfig";
import { StatusLabel } from "../../../Components/Label"; import { StatusLabel } from "../../../Components/Label";
const IncidentTable = ({ monitorId, filter }) => { const IncidentTable = ({ monitors, selectedMonitor, filter }) => {
const { authToken } = useSelector((state) => state.auth); const { authToken, user } = useSelector((state) => state.auth);
const [checks, setChecks] = useState([]); const [checks, setChecks] = useState([]);
const [checksCount, setChecksCount] = useState(0); const [checksCount, setChecksCount] = useState(0);
const [paginationController, setPaginationController] = useState({ const [paginationController, setPaginationController] = useState({
page: 0, page: 0,
rowsPerPage: 5, rowsPerPage: 12,
}); });
useEffect(() => { useEffect(() => {
const fetchPage = async () => { const fetchPage = async () => {
try { try {
if (monitorId === "0") { let url = `/checks/${selectedMonitor}?sortOrder=desc&filter=${filter}&page=${paginationController.page}&rowsPerPage=${paginationController.rowsPerPage}`;
return;
if (selectedMonitor === "0") {
url = `/checks/user/${user._id}?sortOrder=desc&filter=${filter}&page=${paginationController.page}&rowsPerPage=${paginationController.rowsPerPage}`;
} }
const res = await axiosInstance.get(
`/checks/${monitorId}?sortOrder=desc&filter=${filter}&page=${paginationController.page}&rowsPerPage=${paginationController.rowsPerPage}`, const res = await axiosInstance.get(url, {
{ headers: {
headers: { Authorization: `Bearer ${authToken}`,
Authorization: `Bearer ${authToken}`, },
}, });
}
);
setChecks(res.data.data.checks); setChecks(res.data.data.checks);
setChecksCount(res.data.data.checksCount); setChecksCount(res.data.data.checksCount);
} catch (error) { } catch (error) {
@@ -52,24 +51,18 @@ const IncidentTable = ({ monitorId, filter }) => {
fetchPage(); fetchPage();
}, [ }, [
authToken, authToken,
monitorId, user,
selectedMonitor,
filter, filter,
paginationController.page, paginationController.page,
paginationController.rowsPerPage, paginationController.rowsPerPage,
]); ]);
const handlePageChange = (_, newPage) => { const handlePageChange = (_, newPage) => {
console.log(newPage);
setPaginationController({ setPaginationController({
...paginationController, ...paginationController,
page: newPage, page: newPage - 1, // 0-indexed
});
};
const handleChangeRowsPerPage = (event) => {
setPaginationController({
...paginationController,
rowsPerPage: parseInt(event.target.value, 10),
page: 0,
}); });
}; };
@@ -78,7 +71,7 @@ const IncidentTable = ({ monitorId, filter }) => {
paginationComponent = ( paginationComponent = (
<Pagination <Pagination
count={Math.ceil(checksCount / paginationController.rowsPerPage)} count={Math.ceil(checksCount / paginationController.rowsPerPage)}
page={paginationController.page + 1} page={paginationController.page + 1} //0-indexed
onChange={handlePageChange} onChange={handlePageChange}
shape="rounded" shape="rounded"
renderItem={(item) => ( renderItem={(item) => (
@@ -105,7 +98,7 @@ const IncidentTable = ({ monitorId, filter }) => {
return ( return (
<> <>
<TableContainer> <TableContainer component={Paper}>
<Table> <Table>
<TableHead> <TableHead>
<TableRow> <TableRow>
@@ -121,6 +114,7 @@ const IncidentTable = ({ monitorId, filter }) => {
return ( return (
<TableRow key={check._id}> <TableRow key={check._id}>
<TableCell>{monitors[check.monitorId]?.name}</TableCell>
<TableCell> <TableCell>
<StatusLabel <StatusLabel
status={status} status={status}
@@ -144,7 +138,8 @@ const IncidentTable = ({ monitorId, filter }) => {
}; };
IncidentTable.propTypes = { IncidentTable.propTypes = {
monitorId: PropTypes.string.isRequired, monitors: PropTypes.object.isRequired,
selectedMonitor: PropTypes.string.isRequired,
filter: PropTypes.string.isRequired, filter: PropTypes.string.isRequired,
}; };
+6 -93
View File
@@ -1,11 +1,8 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { Typography, ButtonGroup, Stack, Box, Skeleton } from "@mui/material"; import { ButtonGroup, Stack, Skeleton } from "@mui/material";
import WestRoundedIcon from "@mui/icons-material/WestRounded";
import Button from "../../Components/Button"; import Button from "../../Components/Button";
import axiosInstance from "../../Utils/axiosConfig"; import axiosInstance from "../../Utils/axiosConfig";
import BasicTable from "../../Components/BasicTable";
import { StatusLabel } from "../../Components/Label";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
import Select from "../../Components/Inputs/Select"; import Select from "../../Components/Inputs/Select";
@@ -122,96 +119,12 @@ const Incidents = () => {
/> />
</ButtonGroup> </ButtonGroup>
</Stack> </Stack>
<IncidentTable monitorId={selectedMonitor} filter={filter} /> <IncidentTable
monitors={monitors}
selectedMonitor={selectedMonitor}
filter={filter}
/>
</Stack> </Stack>
// <>
// <Stack className="incidents" gap={theme.gap.large}>
// {loading ? (
// <SkeletonLayout />
// ) : false ? (
// <>
// <Stack direction="row" alignItems="center" gap={theme.gap.medium}>
// <Typography component="h1">Incident history for: </Typography>
// <Select
// id="incidents-select-monitor"
// placeholder="All servers"
// value={selectedMonitor}
// onChange={handleSelect}
// items={Object.values(monitors)}
// />
// {hasAnyIncidents && hasSpecificIncidents && (
// <ButtonGroup sx={{ ml: "auto" }}>
// <Button
// level="secondary"
// label="All"
// onClick={() => setFilter("all")}
// sx={{
// backgroundColor:
// filter === "all" && theme.palette.otherColors.fillGray,
// }}
// />
// <Button
// level="secondary"
// label="Down"
// onClick={() => setFilter("down")}
// sx={{
// backgroundColor:
// filter === "down" && theme.palette.otherColors.fillGray,
// }}
// />
// <Button
// level="secondary"
// label="Cannot Resolve"
// onClick={() => setFilter("resolve")}
// sx={{
// backgroundColor:
// filter === "resolve" &&
// theme.palette.otherColors.fillGray,
// }}
// />
// </ButtonGroup>
// )}
// </Stack>
// {hasAnyIncidents && hasSpecificIncidents ? (
// <div>thing</div>
// ) : (
// <Typography alignSelf="center" mt={theme.gap.xxl}>
// The monitor you have selected, has no recorded incidents yet.
// </Typography>
// )}
// </>
// ) : (
// <Box>
// <Button
// level="tertiary"
// label="Back"
// animate="slideLeft"
// img={<WestRoundedIcon />}
// onClick={() => navigate(-1)}
// sx={{
// backgroundColor: theme.palette.otherColors.fillGray,
// px: theme.gap.ml,
// mb: theme.gap.ml,
// "& svg.MuiSvgIcon-root": {
// mr: theme.gap.small,
// fill: theme.palette.otherColors.slateGray,
// },
// }}
// />
// <Box
// padding={theme.gap.xxl}
// gap={theme.gap.small}
// border={1}
// borderRadius={`${theme.shape.borderRadius}px`}
// borderColor={theme.palette.otherColors.graishWhite}
// backgroundColor={theme.palette.otherColors.white}
// >
// <Typography textAlign="center">No incidents, yet.</Typography>
// </Box>
// </Box>
// )}
// </Stack>
// </>
); );
}; };
@@ -6,8 +6,6 @@ import {
TableRow, TableRow,
TableCell, TableCell,
TableBody, TableBody,
TableFooter,
TablePagination,
PaginationItem, PaginationItem,
Pagination, Pagination,
Paper, Paper,
@@ -58,16 +56,16 @@ const PaginationTable = ({ monitorId, dateRange }) => {
const handlePageChange = (_, newPage) => { const handlePageChange = (_, newPage) => {
setPaginationController({ setPaginationController({
...paginationController, ...paginationController,
page: newPage - 1, page: newPage - 1, // 0-indexed
}); });
}; };
let paginationComponent = <></>; let paginationComponent = <></>;
if (checksCount > paginationController.rowsPerPage) { if (checksCount > paginationController.rowsPerPage) {
paginationComponent = ( paginationComponent = (
<Pagination <Pagination
count={Math.ceil(checksCount / paginationController.rowsPerPage)} count={Math.ceil(checksCount / paginationController.rowsPerPage)}
page={paginationController.page + 1} page={paginationController.page + 1} //0-indexed
onChange={handlePageChange} onChange={handlePageChange}
shape="rounded" shape="rounded"
renderItem={(item) => ( renderItem={(item) => (
+15 -2
View File
@@ -3,6 +3,8 @@ const {
createCheckBodyValidation, createCheckBodyValidation,
getChecksParamValidation, getChecksParamValidation,
getChecksQueryValidation, getChecksQueryValidation,
getUserChecksParamValidation,
getUserChecksQueryValidation,
deleteChecksParamValidation, deleteChecksParamValidation,
} = require("../validation/joi"); } = require("../validation/joi");
const { successMessages } = require("../utils/messages"); const { successMessages } = require("../utils/messages");
@@ -62,11 +64,22 @@ const getChecks = async (req, res, next) => {
const getUserChecks = async (req, res, next) => { const getUserChecks = async (req, res, next) => {
try { try {
const checks = req.db.getUserChecks(req); await getUserChecksParamValidation.validateAsync(req.params);
await getUserChecksQueryValidation.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 checkData = await req.db.getUserChecks(req);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.CHECK_GET, msg: successMessages.CHECK_GET,
data: { checksCount, checks }, data: checkData,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
+56 -36
View File
@@ -74,14 +74,10 @@ const getChecks = async (req) => {
const { monitorId } = req.params; const { monitorId } = req.params;
let { sortOrder, limit, dateRange, filter, page, rowsPerPage } = req.query; let { sortOrder, limit, dateRange, filter, page, rowsPerPage } = req.query;
// Default limit to 0 if not provided // Default limit to 0 if not provided
if (limit === undefined) limit = 0; limit = limit === "undefined" ? 0 : limit;
// Default sort order is newest -> oldest // Default sort order is newest -> oldest
if (sortOrder === "asc") { sortOrder = sortOrder === "asc" ? 1 : -1;
sortOrder = 1;
} else if (sortOrder === "desc") {
sortOrder = -1;
} else sortOrder = -1;
// Build query // Build query
const checksQuery = { monitorId: monitorId }; const checksQuery = { monitorId: monitorId };
@@ -121,43 +117,67 @@ const getChecks = async (req) => {
} }
}; };
const getUserChecks = async (req) => {
const { userId } = req.params;
let { sortOrder, limit, dateRange, filter, page, rowsPerPage } = req.query;
// Get monitorIDs
const userMonitors = await Monitor.find({ userId: userId });
const monitorIds = userMonitors.map((monitor) => monitor._id);
//Build check query
// Default limit to 0 if not provided
limit = limit === "undefined" ? 0 : limit;
// Default sort order is newest -> oldest
sortOrder = sortOrder === "asc" ? 1 : -1;
checksQuery = { monitorId: { $in: monitorIds } };
if (filter !== undefined) {
checksQuery.status = false;
switch (filter) {
case "all":
break;
case "down":
break;
case "resolve":
checksQuery.statusCode = 5000;
break;
default:
console.log("default");
break;
}
}
if (dateRange !== undefined) {
checksQuery.createdAt = { $gte: dateRangeLookup[dateRange] };
}
// Skip and limit for pagination
let skip = 0;
if (page && rowsPerPage) {
skip = page * rowsPerPage;
}
const checksCount = await Check.countDocuments(checksQuery);
const checks = await Check.find(checksQuery)
.skip(skip)
.limit(rowsPerPage)
.sort({ createdAt: sortOrder });
return { checksCount, checks };
};
/** /**
* Delete all checks for a monitor * Delete all checks for a user
* @async * @async
* @param {string} monitorId * @param {string} monitorId
* @returns {number} * @returns {number}
* @throws {Error} * @throws {Error}
*/ */
const getUserChecks = async (req) => {
const { userId } = req.params;
try {
const objectId = mongoose.Types.ObjectId.createFromHexString(userId);
const checks = await Check.aggregate([
{
$lookup: {
from: "monitors", // The name of the Monitor collection
localField: "monitorId",
foreignField: "_id",
as: "monitorDetails",
},
},
{
$unwind: "$monitorDetails",
},
{
$match: {
"monitorDetails.userId": objectId,
},
},
]);
return checks;
} catch (error) {
throw error;
}
};
const deleteChecks = async (monitorId) => { const deleteChecks = async (monitorId) => {
try { try {
const result = await Check.deleteMany({ monitorId }); const result = await Check.deleteMany({ monitorId });
+13 -12
View File
@@ -4,7 +4,7 @@ const Notification = require("../models/Notification");
/** /**
* Check Schema for MongoDB collection. * Check Schema for MongoDB collection.
* *
* Represents a check associated with a monitor, storing information * Represents a check associated with a monitor, storing information
* about the status and response of a particular check event. * about the status and response of a particular check event.
*/ */
@@ -12,7 +12,7 @@ const CheckSchema = mongoose.Schema(
{ {
/** /**
* Reference to the associated Monitor document. * Reference to the associated Monitor document.
* *
* @type {mongoose.Schema.Types.ObjectId} * @type {mongoose.Schema.Types.ObjectId}
*/ */
monitorId: { monitorId: {
@@ -22,7 +22,7 @@ const CheckSchema = mongoose.Schema(
}, },
/** /**
* Status of the check (true for up, false for down). * Status of the check (true for up, false for down).
* *
* @type {Boolean} * @type {Boolean}
*/ */
status: { status: {
@@ -30,23 +30,23 @@ const CheckSchema = mongoose.Schema(
}, },
/** /**
* Response time of the check in milliseconds. * Response time of the check in milliseconds.
* *
* @type {Number} * @type {Number}
*/ */
responseTime: { responseTime: {
type: Number, type: Number,
}, },
/** /**
* HTTP status code received during the check. * HTTP status code received during the check.
* *
* @type {Number} * @type {Number}
*/ */
statusCode: { statusCode: {
type: Number, type: Number,
}, },
/** /**
* Message or description of the check result. * Message or description of the check result.
* *
* @type {String} * @type {String}
*/ */
message: { message: {
@@ -54,7 +54,7 @@ const CheckSchema = mongoose.Schema(
}, },
/** /**
* Expiry date of the check, auto-calculated to expire after 30 days. * Expiry date of the check, auto-calculated to expire after 30 days.
* *
* @type {Date} * @type {Date}
*/ */
expiry: { expiry: {
@@ -70,7 +70,7 @@ const CheckSchema = mongoose.Schema(
/** /**
* Pre-save middleware to handle status change notifications. * Pre-save middleware to handle status change notifications.
* *
* This middleware checks if the status of the monitor associated * This middleware checks if the status of the monitor associated
* with the check has changed and sends notifications if necessary. * with the check has changed and sends notifications if necessary.
*/ */
@@ -79,7 +79,9 @@ CheckSchema.pre("save", async function (next) {
const monitor = await mongoose.model("Monitor").findById(this.monitorId); const monitor = await mongoose.model("Monitor").findById(this.monitorId);
if (monitor) { if (monitor) {
const notifications = await Notification.find({ monitorId: this.monitorId }); const notifications = await Notification.find({
monitorId: this.monitorId,
});
// Check if there are any notifications // Check if there are any notifications
if (notifications && notifications.length > 0) { if (notifications && notifications.length > 0) {
@@ -128,5 +130,4 @@ CheckSchema.pre("save", async function (next) {
} }
}); });
module.exports = mongoose.model("Check", CheckSchema); module.exports = mongoose.model("Check", CheckSchema);
+15
View File
@@ -241,6 +241,19 @@ const getChecksQueryValidation = joi.object({
rowsPerPage: joi.number(), rowsPerPage: joi.number(),
}); });
const getUserChecksParamValidation = joi.object({
userId: joi.string().required(),
});
const getUserChecksQueryValidation = joi.object({
sortOrder: joi.string().valid("asc", "desc"),
limit: joi.number(),
dateRange: joi.string().valid("day", "week", "month"),
filter: joi.string().valid("all", "down", "resolve"),
page: joi.number(),
rowsPerPage: joi.number(),
});
const deleteChecksParamValidation = joi.object({ const deleteChecksParamValidation = joi.object({
monitorId: joi.string().required(), monitorId: joi.string().required(),
}); });
@@ -321,6 +334,8 @@ module.exports = {
createCheckBodyValidation, createCheckBodyValidation,
getChecksParamValidation, getChecksParamValidation,
getChecksQueryValidation, getChecksQueryValidation,
getUserChecksParamValidation,
getUserChecksQueryValidation,
deleteChecksParamValidation, deleteChecksParamValidation,
deleteUserParamValidation, deleteUserParamValidation,
getPageSpeedCheckParamValidation, getPageSpeedCheckParamValidation,