FE refactor

This commit is contained in:
Alex Holliday committed 2024-12-30 16:07:28 -08:00
1 parent e5181727fe
commit 107540b2a8
5 files changed
+60 -37

No files matched your search

@@ -11,11 +11,11 @@ import {
} from "recharts"; } from "recharts";
import { memo, useMemo, useState } from "react"; import { memo, useMemo, useState } from "react";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { formatDateWithTz } from "../../../../Utils/timeUtils"; import { formatDateWithTz, toTimeStamp } from "../../../../Utils/timeUtils";
const CustomLabels = ({ x, width, height, firstDataPoint, lastDataPoint, type }) => { const CustomLabels = ({ x, width, height, firstDataPoint, lastDataPoint, type }) => {
const uiTimezone = useSelector((state) => state.ui.timezone); const uiTimezone = useSelector((state) => state.ui.timezone);
const dateFormat = type === "day" ? "MMM D, h:mm A" : "MMM D"; const dateFormat = type === "day" ? "MMM D, h A" : "MMM D";
return ( return (
<> <>
@@ -26,7 +26,11 @@ const CustomLabels = ({ x, width, height, firstDataPoint, lastDataPoint, type })
textAnchor="start" textAnchor="start"
fontSize={11} fontSize={11}
> >
{formatDateWithTz(new Date(firstDataPoint.time), dateFormat, uiTimezone)} {formatDateWithTz(
toTimeStamp(firstDataPoint._id, "YYYY-MM-DD-HH"),
dateFormat,
uiTimezone
)}
</text> </text>
<text <text
x={width} x={width}
@@ -35,7 +39,8 @@ const CustomLabels = ({ x, width, height, firstDataPoint, lastDataPoint, type })
textAnchor="end" textAnchor="end"
fontSize={11} fontSize={11}
> >
{formatDateWithTz(new Date(lastDataPoint.time), dateFormat, uiTimezone)} {lastDataPoint._id}
{/* {formatDateWithTz(new Date(lastDataPoint.time), dateFormat, uiTimezone)} */}
</text> </text>
</> </>
); );
@@ -57,9 +62,9 @@ const UpBarChart = memo(({ data, type, onBarHover }) => {
const [hoveredBarIndex, setHoveredBarIndex] = useState(null); const [hoveredBarIndex, setHoveredBarIndex] = useState(null);
const getColorRange = (uptime) => { const getColorRange = (uptime) => {
return uptime > 80 return uptime > 0.8
? { main: theme.palette.success.main, light: theme.palette.success.light } ? { main: theme.palette.success.main, light: theme.palette.success.light }
: uptime > 50 : uptime > 0.5
? { main: theme.palette.warning.main, light: theme.palette.warning.light } ? { main: theme.palette.warning.main, light: theme.palette.warning.light }
: { main: theme.palette.error.contrastText, light: theme.palette.error.light }; : { main: theme.palette.error.contrastText, light: theme.palette.error.light };
}; };
@@ -79,7 +84,7 @@ const UpBarChart = memo(({ data, type, onBarHover }) => {
data={reversedData} data={reversedData}
onMouseEnter={() => { onMouseEnter={() => {
setChartHovered(true); setChartHovered(true);
onBarHover({ time: null, totalChecks: 0, uptimePercentage: 0 }); onBarHover({ time: null, totalChecks: 0, groupUptimePercentage: 0 });
}} }}
onMouseLeave={() => { onMouseLeave={() => {
setChartHovered(false); setChartHovered(false);
@@ -104,12 +109,12 @@ const UpBarChart = memo(({ data, type, onBarHover }) => {
} }
/> />
<Bar <Bar
dataKey="totalChecks" dataKey="avgResponseTime"
maxBarSize={7} maxBarSize={7}
background={{ fill: "transparent" }} background={{ fill: "transparent" }}
> >
{reversedData.map((entry, index) => { {reversedData.map((entry, index) => {
let { main, light } = getColorRange(entry.uptimePercentage); let { main, light } = getColorRange(entry.groupUptimePercentage);
return ( return (
<Cell <Cell
key={`cell-${entry.time}`} key={`cell-${entry.time}`}
@@ -123,7 +128,7 @@ const UpBarChart = memo(({ data, type, onBarHover }) => {
onBarHover({ onBarHover({
time: null, time: null,
totalChecks: 0, totalChecks: 0,
uptimePercentage: 0, groupUptimePercentage: 0,
}); });
}} }}
/> />
+17 -19
View File
@@ -5,7 +5,6 @@ import { useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
import { networkService } from "../../../main"; import { networkService } from "../../../main";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
import { formatDurationRounded, formatDurationSplit } from "../../../Utils/timeUtils";
import MonitorDetailsAreaChart from "../../../Components/Charts/MonitorDetailsAreaChart"; import MonitorDetailsAreaChart from "../../../Components/Charts/MonitorDetailsAreaChart";
import ButtonGroup from "@mui/material/ButtonGroup"; import ButtonGroup from "@mui/material/ButtonGroup";
import SettingsIcon from "../../../assets/icons/settings-bold.svg?react"; import SettingsIcon from "../../../assets/icons/settings-bold.svg?react";
@@ -22,7 +21,7 @@ import { DownBarChart, ResponseGaugeChart, UpBarChart } from "./Charts";
import SkeletonLayout from "./skeleton"; import SkeletonLayout from "./skeleton";
import "./index.css"; import "./index.css";
import useUtils from "../utils"; import useUtils from "../utils";
import { formatDateWithTz } from "../../../Utils/timeUtils"; import { formatDateWithTz, formatDurationSplit } from "../../../Utils/timeUtils";
import { useIsAdmin } from "../../../Hooks/useIsAdmin"; import { useIsAdmin } from "../../../Hooks/useIsAdmin";
import IconBox from "../../../Components/IconBox"; import IconBox from "../../../Components/IconBox";
import StatBox from "../../../Components/StatBox"; import StatBox from "../../../Components/StatBox";
@@ -47,13 +46,10 @@ const DetailsPage = () => {
const fetchMonitor = useCallback(async () => { const fetchMonitor = useCallback(async () => {
try { try {
const res = await networkService.getStatsByMonitorId({ const res = await networkService.getUptimeDetailsById({
authToken: authToken, authToken: authToken,
monitorId: monitorId, monitorId: monitorId,
sortOrder: null,
limit: null,
dateRange: dateRange, dateRange: dateRange,
numToDisplay: 50,
normalize: true, normalize: true,
}); });
console.log(res?.data?.data); console.log(res?.data?.data);
@@ -185,7 +181,7 @@ const DetailsPage = () => {
}, },
}} }}
> >
Checking every {formatDurationRounded(monitor?.interval)}. {/* Checking every {formatDurationRounded(monitor?.interval)}. */}
</Typography> </Typography>
</Stack> </Stack>
</Box> </Box>
@@ -224,17 +220,17 @@ const DetailsPage = () => {
<StatBox <StatBox
sx={statusStyles[determineState(monitor)]} sx={statusStyles[determineState(monitor)]}
heading={"active for"} heading={"active for"}
subHeading={splitDuration(monitor?.uptimeDuration)} subHeading={splitDuration(monitor?.aggregateData?.uptimeDuration)}
/> />
<StatBox <StatBox
heading="last check" heading="last check"
subHeading={splitDuration(monitor?.lastChecked)} subHeading={splitDuration(monitor?.aggregateData?.timeSinceLastCheck)}
/> />
<StatBox <StatBox
heading="last response time" heading="last response time"
subHeading={ subHeading={
<> <>
{monitor?.latestResponseTime} {monitor?.aggregateData?.latestResponseTime}
<Typography component="span">{"ms"}</Typography> <Typography component="span">{"ms"}</Typography>
</> </>
} }
@@ -311,7 +307,7 @@ const DetailsPage = () => {
<Typography component="span"> <Typography component="span">
{hoveredUptimeData !== null {hoveredUptimeData !== null
? hoveredUptimeData.totalChecks ? hoveredUptimeData.totalChecks
: monitor?.periodTotalChecks} : monitor.dateRangeData[0].overallTotalChecks}
</Typography> </Typography>
{hoveredUptimeData !== null && hoveredUptimeData.time !== null && ( {hoveredUptimeData !== null && hoveredUptimeData.time !== null && (
<Typography <Typography
@@ -333,14 +329,16 @@ const DetailsPage = () => {
<Typography>Uptime Percentage</Typography> <Typography>Uptime Percentage</Typography>
<Typography component="span"> <Typography component="span">
{hoveredUptimeData !== null {hoveredUptimeData !== null
? Math.floor(hoveredUptimeData.uptimePercentage * 10) / 10 ? Math.floor(hoveredUptimeData.groupUptimePercentage * 100)
: Math.floor(monitor?.periodUptime * 10) / 10} : Math.floor(
monitor?.dateRangeData[0].overallUptimePercentage * 100
)}
<Typography component="span">%</Typography> <Typography component="span">%</Typography>
</Typography> </Typography>
</Box> </Box>
</Stack> </Stack>
<UpBarChart <UpBarChart
data={monitor?.aggregateData} data={monitor?.dateRangeData}
type={dateRange} type={dateRange}
onBarHover={setHoveredUptimeData} onBarHover={setHoveredUptimeData}
/> />
@@ -376,11 +374,11 @@ const DetailsPage = () => {
</Typography> </Typography>
)} )}
</Box> </Box>
<DownBarChart {/* <DownBarChart
data={monitor?.aggregateData} data={monitor?.aggregateData}
type={dateRange} type={dateRange}
onBarHover={setHoveredIncidentsData} onBarHover={setHoveredIncidentsData}
/> /> */}
</ChartBox> </ChartBox>
<ChartBox justifyContent="space-between"> <ChartBox justifyContent="space-between">
<Stack> <Stack>
@@ -389,9 +387,9 @@ const DetailsPage = () => {
</IconBox> </IconBox>
<Typography component="h2">Average Response Time</Typography> <Typography component="h2">Average Response Time</Typography>
</Stack> </Stack>
<ResponseGaugeChart {/* <ResponseGaugeChart
data={[{ response: monitor?.periodAvgResponseTime }]} data={[{ response: monitor?.periodAvgResponseTime }]}
/> /> */}
</ChartBox> </ChartBox>
<ChartBox sx={{ padding: 0 }}> <ChartBox sx={{ padding: 0 }}>
<Stack <Stack
@@ -403,7 +401,7 @@ const DetailsPage = () => {
</IconBox> </IconBox>
<Typography component="h2">Response Times</Typography> <Typography component="h2">Response Times</Typography>
</Stack> </Stack>
<MonitorDetailsAreaChart checks={[...monitor.checks].reverse()} /> {/* <MonitorDetailsAreaChart checks={[...monitor.checks].reverse()} /> */}
</ChartBox> </ChartBox>
<ChartBox <ChartBox
gap={theme.spacing(8)} gap={theme.spacing(8)}
+8 -5
View File
@@ -247,11 +247,14 @@ class NetworkService {
if (config.dateRange) params.append("dateRange", config.dateRange); if (config.dateRange) params.append("dateRange", config.dateRange);
if (config.normalize) params.append("normalize", config.normalize); if (config.normalize) params.append("normalize", config.normalize);
return this.axiosInstance.get(`/monitors/uptime/details/${config.monitorId}`, { return this.axiosInstance.get(
headers: { `/monitors/uptime/details/${config.monitorId}?${params.toString()}`,
Authorization: `Bearer ${config.authToken}`, {
}, headers: {
}); Authorization: `Bearer ${config.authToken}`,
},
}
);
} }
/** /**
+9 -1
View File
@@ -1,8 +1,11 @@
import dayjs from "dayjs"; import dayjs from "dayjs";
import utc from "dayjs/plugin/utc"; import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone"; import timezone from "dayjs/plugin/timezone";
import customParseFormat from "dayjs/plugin/customParseFormat";
dayjs.extend(utc); dayjs.extend(utc);
dayjs.extend(timezone); dayjs.extend(timezone);
dayjs.extend(customParseFormat);
export const MS_PER_SECOND = 1000; export const MS_PER_SECOND = 1000;
export const MS_PER_MINUTE = 60 * MS_PER_SECOND; export const MS_PER_MINUTE = 60 * MS_PER_SECOND;
@@ -72,6 +75,11 @@ export const formatDurationSplit = (ms) => {
: { time: 0, format: "seconds" }; : { time: 0, format: "seconds" };
}; };
export const toTimeStamp = (date, format) => {
const dayJsDate = dayjs(date, format);
return dayJsDate.valueOf();
};
export const formatDate = (date, customOptions) => { export const formatDate = (date, customOptions) => {
const options = { const options = {
year: "numeric", year: "numeric",
@@ -90,6 +98,6 @@ export const formatDate = (date, customOptions) => {
}; };
export const formatDateWithTz = (timestamp, format, timezone) => { export const formatDateWithTz = (timestamp, format, timezone) => {
const formattedDate = dayjs(timestamp, timezone).tz(timezone).format(format); const formattedDate = dayjs(timestamp).tz(timezone).format(format);
return formattedDate; return formattedDate;
}; };
+11 -2
View File
@@ -406,8 +406,9 @@ const getUptimeDetailsById = async (req) => {
{ {
$addFields: { $addFields: {
uptimePercentage: { uptimePercentage: {
$multiply: [{ $divide: ["$upChecks", "$totalChecks"] }, 100], $divide: ["$upChecks", "$totalChecks"],
}, },
overallTotalChecks: "$totalChecks",
}, },
}, },
{ {
@@ -448,6 +449,7 @@ const getUptimeDetailsById = async (req) => {
}, },
{ {
$project: { $project: {
totalChecks: 1,
avgResponseTime: 1, avgResponseTime: 1,
groupUptimePercentage: { $divide: ["$upChecks", "$totalChecks"] }, groupUptimePercentage: { $divide: ["$upChecks", "$totalChecks"] },
}, },
@@ -465,6 +467,7 @@ const getUptimeDetailsById = async (req) => {
$mergeObjects: [ $mergeObjects: [
"$groupedResults", "$groupedResults",
{ overallUptimePercentage: "$uptimePercentage" }, { overallUptimePercentage: "$uptimePercentage" },
{ overallTotalChecks: "$overallTotalChecks" },
], ],
}, },
}, },
@@ -474,7 +477,13 @@ const getUptimeDetailsById = async (req) => {
}, },
]); ]);
return { aggregateResults, dateRangeResults }; const monitorStats = {
...monitor.toObject(),
};
monitorStats.aggregateData = aggregateResults[0];
monitorStats.dateRangeData = dateRangeResults;
return monitorStats;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getUptimeDetailsById"; error.method = "getUptimeDetailsById";