Merge pull request #855 from bluewave-labs/develop

Develop -> Master
This commit is contained in:
Alexander Holliday authored and GitHub committed 2024-09-18 20:44:41 -07:00
commit aa24424168
96 files changed
+5932 -2809

No files matched your search

+1 -1
View File
@@ -71,7 +71,7 @@ function App() {
element={<ProtectedRoute Component={Configure} />} element={<ProtectedRoute Component={Configure} />}
/> />
<Route <Route
path="incidents" path="incidents/:monitorId?"
element={<ProtectedRoute Component={Incidents} />} element={<ProtectedRoute Component={Incidents} />}
/> />
@@ -1,12 +1,14 @@
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { Box, Stack, Tooltip, Typography } from "@mui/material"; import { Box, Stack, Tooltip, Typography } from "@mui/material";
import { formatDate } from "../../../Utils/timeUtils"; import { formatDateWithTz } from "../../../Utils/timeUtils";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import "./index.css"; import "./index.css";
import { useSelector } from "react-redux";
const BarChart = ({ checks = [] }) => { const BarChart = ({ checks = [] }) => {
const theme = useTheme(); const theme = useTheme();
const [animate, setAnimate] = useState(false); const [animate, setAnimate] = useState(false);
const uiTimezone = useSelector((state) => state.ui.timezone);
useEffect(() => { useEffect(() => {
setAnimate(true); setAnimate(true);
@@ -51,7 +53,11 @@ const BarChart = ({ checks = [] }) => {
title={ title={
<> <>
<Typography> <Typography>
{formatDate(new Date(check.createdAt), { year: undefined })} {formatDateWithTz(
check.createdAt,
"ddd, MMMM D, YYYY, HH:mm A",
uiTimezone
)}
</Typography> </Typography>
<Box mt={theme.spacing(2)}> <Box mt={theme.spacing(2)}>
<Box <Box
@@ -6,15 +6,19 @@ import {
Tooltip, Tooltip,
CartesianGrid, CartesianGrid,
ResponsiveContainer, ResponsiveContainer,
Text,
} from "recharts"; } from "recharts";
import { Box, Stack, Typography } from "@mui/material"; import { Box, Stack, Typography } from "@mui/material";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useMemo } from "react"; import { useMemo, useState } from "react";
import { useSelector } from "react-redux";
import { formatDateWithTz } from "../../../Utils/timeUtils";
import "./index.css"; import "./index.css";
const CustomToolTip = ({ active, payload, label }) => { const CustomToolTip = ({ active, payload, label }) => {
const theme = useTheme(); const uiTimezone = useSelector((state) => state.ui.timezone);
const theme = useTheme();
if (active && payload && payload.length) { if (active && payload && payload.length) {
return ( return (
<Box <Box
@@ -35,17 +39,7 @@ const CustomToolTip = ({ active, payload, label }) => {
fontWeight: 500, fontWeight: 500,
}} }}
> >
{new Date(label).toLocaleDateString("en-US", { {formatDateWithTz(label, "ddd, MMMM D, YYYY, h:mm A", uiTimezone)}
weekday: "short", // Mon
month: "long", // July
day: "numeric", // 17
}) +
", " +
new Date(label).toLocaleTimeString("en-US", {
hour: "numeric", // 12
minute: "2-digit", // 15
hour12: true, // AM/PM format
})}
</Typography> </Typography>
<Box mt={theme.spacing(1)}> <Box mt={theme.spacing(1)}>
<Box <Box
@@ -87,20 +81,39 @@ const CustomToolTip = ({ active, payload, label }) => {
return null; return null;
}; };
const MonitorDetailsAreaChart = ({ checks }) => { const CustomTick = ({ x, y, payload, index }) => {
const formatDate = (timestamp) => {
const date = new Date(timestamp);
return date.toLocaleTimeString("en-US", {
hour: "numeric",
minute: "2-digit",
hour12: true,
});
};
const memoizedChecks = useMemo(() => checks, [checks[0]]);
const theme = useTheme(); const theme = useTheme();
const uiTimezone = useSelector((state) => state.ui.timezone);
// Render nothing for the first tick
if (index === 0) return null;
return (
<Text
x={x}
y={y + 10}
textAnchor="middle"
fill={theme.palette.text.tertiary}
fontSize={11}
fontWeight={400}
>
{formatDateWithTz(payload?.value, "h:mm a", uiTimezone)}
</Text>
);
};
CustomTick.propTypes = {
x: PropTypes.number,
y: PropTypes.number,
payload: PropTypes.object,
index: PropTypes.number,
};
const MonitorDetailsAreaChart = ({ checks }) => {
const theme = useTheme();
const memoizedChecks = useMemo(() => checks, [checks[0]]);
const [isHovered, setIsHovered] = useState(false);
return ( return (
<ResponsiveContainer width="100%" minWidth={25} height={220}> <ResponsiveContainer width="100%" minWidth={25} height={220}>
<AreaChart <AreaChart
@@ -113,6 +126,8 @@ const MonitorDetailsAreaChart = ({ checks }) => {
left: 0, left: 0,
bottom: 0, bottom: 0,
}} }}
onMouseMove={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
> >
<CartesianGrid <CartesianGrid
stroke={theme.palette.border.light} stroke={theme.palette.border.light}
@@ -138,21 +153,24 @@ const MonitorDetailsAreaChart = ({ checks }) => {
<XAxis <XAxis
stroke={theme.palette.border.dark} stroke={theme.palette.border.dark}
dataKey="createdAt" dataKey="createdAt"
tickFormatter={formatDate} tick={<CustomTick />}
tick={{ fontSize: "13px" }} minTickGap={0}
axisLine={false}
tickLine={false} tickLine={false}
height={18} height={20}
interval="equidistantPreserveStart"
/> />
<Tooltip <Tooltip
cursor={{ stroke: theme.palette.border.light }} cursor={{ stroke: theme.palette.border.light }}
content={<CustomToolTip />} content={<CustomToolTip />}
wrapperStyle={{ pointerEvents: "none" }}
/> />
<Area <Area
type="monotone" type="monotone"
dataKey="responseTime" dataKey="responseTime"
stroke={theme.palette.primary.main} stroke={theme.palette.primary.main}
fill="url(#colorUv)" fill="url(#colorUv)"
strokeWidth={1.5} strokeWidth={isHovered ? 2.5 : 1.5}
activeDot={{ stroke: theme.palette.background.main, r: 5 }} activeDot={{ stroke: theme.palette.background.main, r: 5 }}
/> />
</AreaChart> </AreaChart>
Whitespace-only changes.
@@ -1,71 +0,0 @@
import { LineChart } from "@mui/x-charts/LineChart";
import PropTypes from "prop-types";
const PageSpeedLineChart = ({ pageSpeedChecks = [] }) => {
const keyToLabel = {
performance: "Performance",
seo: "SEO",
bestPractices: "Best practices",
accessibility: "Accessibility",
};
const colors = {
performance: "#2aa02b",
seo: "#9467bd",
bestPractices: "#ff7f0e",
accessibility: "#1f76b3",
};
const customize = {
legend: { position: { vertical: "bottom", horizontal: "middle" } },
margin: { bottom: 75 },
};
const xLabels = pageSpeedChecks.map((check) => {
return check.createdAt;
});
return (
<LineChart
series={Object.keys(keyToLabel).map((key) => ({
dataKey: key,
label: keyToLabel[key],
color: colors[key],
showMark: false,
}))}
yAxis={[{ min: 0, max: 100 }]}
xAxis={[
{
scaleType: "point",
data: xLabels,
valueFormatter: (val) => new Date(val).toLocaleDateString(),
},
]}
dataset={pageSpeedChecks}
{...customize}
grid={{ vertical: true, horizontal: true }}
tooltip={{ trigger: "none" }}
slotProps={{
legend: {
direction: "row",
position: { vertical: "bottom", horizontal: "middle" },
padding: 2,
itemMarkWidth: 8,
itemMarkHeight: 8,
markGap: 5,
itemGap: 15,
labelStyle: {
fontSize: 13,
color: "#344054"
}
},
}}
/>
);
};
PageSpeedLineChart.propTypes = {
pageSpeedChecks: PropTypes.array,
};
export default PageSpeedLineChart;
@@ -1,116 +0,0 @@
import { Autocomplete, TextField } from "@mui/material";
import React from "react";
import PropTypes from "prop-types";
import { useTheme } from "@emotion/react";
/**
* @example
*
* const options = [
* { _id: "66d6119ef959cbc681e034f0", name: "Googler" },
* { _id: "66d6119ef959cbc681e034f0", name: "CNN" },
* { _id: "66d61a1bf959cbc681e0353f", name: "X Corp." },
* ];
*
* <AutoCompleteField options={options} />
*
*/
/**
* AutoCompleteField component.
*
* @component
* @param {Object} props - The component props.
* @param {string} props.id - The ID of the autocomplete field.
* @param {string} props.type - The type of the input field (text or number).
* @param {Array} props.options - The options for the autocomplete field.
* @param {string} props.placeholder - The placeholder text for the input field.
* @param {boolean} props.disabled - Indicates if the field is disabled.
* @returns {JSX.Element} The AutoCompleteField component.
*/
const AutoCompleteField = ({
id,
type,
options,
placeholder = "Type to search",
disabled,
}) => {
const [value, setValue] = React.useState();
const [inputValue, setInputValue] = React.useState("");
const theme = useTheme();
return (
<Autocomplete
freeSolo
className="auto-complete-field"
id={id}
value={value}
onChange={(event, newValue) => {
setValue(newValue);
}}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
options={options}
getOptionLabel={(option) => option.name}
renderInput={(params) => (
<TextField
{...params}
type={type}
placeholder={placeholder}
disabled={disabled}
InputProps={{
...params.InputProps,
sx: {
width: 360,
height: 34,
fontSize: 13,
p: 0,
borderRadius: theme.shape.borderRadius,
"& input": {
p: 0,
},
},
}}
/>
)}
renderOption={(props, option) => {
const { key, ...optionProps } = props;
return (
<li key={option._id} {...optionProps}>
<div>{<span>{option.name}</span>}</div>
</li>
);
}}
slotProps={{
popper: {
sx: {
"& ul": { p: 0 },
"& li": { borderRadius: theme.shape.borderRadius },
},
},
paper: {
sx: {
p: 2,
fontSize: 13,
},
},
}}
/>
);
};
AutoCompleteField.displayName = "AutoCompleteField";
AutoCompleteField.propTypes = {
id: PropTypes.string,
type: PropTypes.oneOf(["text", "number"]),
options: PropTypes.array,
placeholder: PropTypes.string,
disabled: PropTypes.bool,
setWidth: PropTypes.string,
};
export default AutoCompleteField;
+2 -1
View File
@@ -121,8 +121,9 @@ const Field = forwardRef(
sx: { sx: {
color: theme.palette.text.secondary, color: theme.palette.text.secondary,
"&:-webkit-autofill": { "&:-webkit-autofill": {
WebkitBoxShadow: `0 0 0 100px ${theme.palette.background.fill} inset`, WebkitBoxShadow: `0 0 0 100px ${theme.palette.other.autofill} inset`,
WebkitTextFillColor: theme.palette.text.secondary, WebkitTextFillColor: theme.palette.text.secondary,
borderRadius: "0 5px 5px 0",
}, },
}, },
}} }}
@@ -0,0 +1,150 @@
import PropTypes from "prop-types";
import { Box, ListItem, Autocomplete, TextField } from "@mui/material";
import { useTheme } from "@emotion/react";
import SearchIcon from "../../../assets/icons/search.svg?react";
/**
* Search component using Material UI's Autocomplete.
*
* @param {Object} props
* @param {string} props.id - Unique identifier for the Autocomplete component
* @param {Array<Object>} props.options - Options to display in the Autocomplete dropdown
* @param {string} props.filteredBy - Key to access the option label from the options
* @param {string} props.value - Current input value for the Autocomplete
* @param {Function} props.handleChange - Function to call when the input changes
* @param {Object} props.sx - Additional styles to apply to the component
* @returns {JSX.Element} The rendered Search component
*/
const Search = ({
id,
options,
filteredBy,
value,
handleInputChange,
handleChange,
sx,
}) => {
const theme = useTheme();
return (
<Autocomplete
id={id}
inputValue={value}
onInputChange={(_, newValue) => {
handleInputChange(newValue);
}}
onChange={(_, newValue) => {
handleChange && handleChange(newValue);
}}
fullWidth
freeSolo
disableClearable
options={options}
getOptionLabel={(option) => option[filteredBy]}
renderInput={(params) => (
<TextField
{...params}
placeholder="Type to search"
InputProps={{
...params.InputProps,
startAdornment: (
<Box
mr={theme.spacing(4)}
height={16}
sx={{
"& svg": {
width: 16,
height: 16,
"& path": {
stroke: theme.palette.text.tertiary,
strokeWidth: 1.2,
},
},
}}
>
<SearchIcon />
</Box>
),
}}
sx={{
"& fieldset": {
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
},
"& .MuiOutlinedInput-root:hover:not(:has(input:focus)):not(:has(textarea:focus)) fieldset":
{
borderColor: theme.palette.border.light,
},
}}
/>
)}
filterOptions={(options, { inputValue }) => {
const filtered = options.filter((option) =>
option[filteredBy].toLowerCase().includes(inputValue.toLowerCase())
);
if (filtered.length === 0) {
return [{ [filteredBy]: "No monitors found", noOptions: true }];
}
return filtered;
}}
renderOption={(props, option) => {
const { key, ...optionProps } = props;
return (
<ListItem
key={key}
{...optionProps}
sx={
option.noOptions
? {
pointerEvents: "none",
backgroundColor: theme.palette.background.main,
}
: {}
}
>
{option[filteredBy]}
</ListItem>
);
}}
slotProps={{
popper: {
keepMounted: true,
sx: {
"& ul": { p: 2 },
"& li.MuiAutocomplete-option": {
color: theme.palette.text.secondary,
px: 4,
borderRadius: theme.shape.borderRadius,
},
"& .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true'], & .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true'].Mui-focused, & .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true']:hover":
{
backgroundColor: theme.palette.background.fill,
},
"& .MuiAutocomplete-noOptions": {
px: theme.spacing(6),
py: theme.spacing(5),
},
},
},
}}
sx={{
height: 34,
"&.MuiAutocomplete-root .MuiAutocomplete-input": { p: 0 },
...sx,
}}
/>
);
};
Search.propTypes = {
id: PropTypes.string,
options: PropTypes.array.isRequired,
filteredBy: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
handleInputChange: PropTypes.func.isRequired,
handleChange: PropTypes.func,
sx: PropTypes.object,
};
export default Search;
Whitespace-only changes.
-49
View File
@@ -1,49 +0,0 @@
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import Chip from '@mui/material/Chip';
import Box from '@mui/material/Box';
import { useTheme } from "@mui/material";
const teamMembers = [
{ title: 'John Doe'},
{ title: 'Jane Smith'},
{ title: 'Alex Johnson'},
];
/**
* @component
* @returns {JSX.Element}
*/
export default function Search()
{
const theme = useTheme();
return (
<Box padding={theme.spacing(2)}> {/* Add padding to the container */}
<Autocomplete
multiple
id="tags-outlined"
options={teamMembers}
getOptionLabel={(option) => option.title}
filterSelectedOptions
renderInput={(params) => (
<TextField
{...params}
label="Team Members"
placeholder="Favorites"
/>
)}
renderTags={(value, getTagProps) =>
value.map((option) => (
<Chip
key={option.title}
variant="outlined"
label={option.title}
{...getTagProps({ option })}
/>
))
}
/>
</Box>
);
}
+1 -1
View File
@@ -67,7 +67,7 @@ export const update = createAsyncThunk(
fd.append("deleteProfileImage", form.deleteProfileImage); fd.append("deleteProfileImage", form.deleteProfileImage);
const res = await networkService.updateUser(token, user._id, fd); const res = await networkService.updateUser(token, user._id, fd);
console.log(res);
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
+11 -2
View File
@@ -14,6 +14,7 @@ const initialState = {
}, },
mode: "light", mode: "light",
greeting: { index: 0, lastUpdate: null }, greeting: { index: 0, lastUpdate: null },
timezone: "America/Toronto",
}; };
const uiSlice = createSlice({ const uiSlice = createSlice({
@@ -36,9 +37,17 @@ const uiSlice = createSlice({
state.greeting.index = action.payload.index; state.greeting.index = action.payload.index;
state.greeting.lastUpdate = action.payload.lastUpdate; state.greeting.lastUpdate = action.payload.lastUpdate;
}, },
setTimezone(state, action) {
state.timezone = action.payload.timezone;
},
}, },
}); });
export default uiSlice.reducer; export default uiSlice.reducer;
export const { setRowsPerPage, toggleSidebar, setMode, setGreeting } = export const {
uiSlice.actions; setRowsPerPage,
toggleSidebar,
setMode,
setGreeting,
setTimezone,
} = uiSlice.actions;
@@ -164,6 +164,44 @@ export const deleteMonitorChecksByTeamId = createAsyncThunk(
} }
} }
); );
export const addDemoMonitors = createAsyncThunk(
"monitors/addDemoMonitors",
async (data, thunkApi) => {
try {
const { authToken } = data;
const res = await networkService.addDemoMonitors(authToken);
return res.data;
} catch (error) {
if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data);
}
const payload = {
status: false,
msg: error.message ? error.message : "Unknown error",
};
return thunkApi.rejectWithValue(payload);
}
}
);
export const deleteAllMonitors = createAsyncThunk(
"monitors/deleteAllMonitors",
async (data, thunkApi) => {
try {
const { authToken } = data;
const res = await networkService.deleteAllMonitors(authToken);
return res.data;
} catch (error) {
if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data);
}
const payload = {
status: false,
msg: error.message ? error.message : "Unknown error",
};
return thunkApi.rejectWithValue(payload);
}
}
);
const uptimeMonitorsSlice = createSlice({ const uptimeMonitorsSlice = createSlice({
name: "uptimeMonitors", name: "uptimeMonitors",
@@ -306,6 +344,42 @@ const uptimeMonitorsSlice = createSlice({
state.msg = action.payload state.msg = action.payload
? action.payload.msg ? action.payload.msg
: "Failed to pause uptime monitor"; : "Failed to pause uptime monitor";
})
// *****************************************************
// Add Demo Monitors
// *****************************************************
.addCase(addDemoMonitors.pending, (state) => {
state.isLoading = true;
})
.addCase(addDemoMonitors.fulfilled, (state, action) => {
state.isLoading = false;
state.success = action.payload.success;
state.msg = action.payload.msg;
})
.addCase(addDemoMonitors.rejected, (state, action) => {
state.isLoading = false;
state.success = false;
state.msg = action.payload
? action.payload.msg
: "Failed to add demo uptime monitors";
})
// *****************************************************
// Delete all Monitors
// *****************************************************
.addCase(deleteAllMonitors.pending, (state) => {
state.isLoading = true;
})
.addCase(deleteAllMonitors.fulfilled, (state, action) => {
state.isLoading = false;
state.success = action.payload.success;
state.msg = action.payload.msg;
})
.addCase(deleteAllMonitors.rejected, (state, action) => {
state.isLoading = false;
state.success = false;
state.msg = action.payload
? action.payload.msg
: "Failed to delete all monitors";
}); });
}, },
}); });
@@ -21,9 +21,16 @@ import { networkService } from "../../../main";
import { StatusLabel } from "../../../Components/Label"; import { StatusLabel } from "../../../Components/Label";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { formatDateWithTz } from "../../../Utils/timeUtils";
import PlaceholderLight from "../../../assets/Images/data_placeholder.svg?react";
import PlaceholderDark from "../../../assets/Images/data_placeholder_dark.svg?react";
const IncidentTable = ({ monitors, selectedMonitor, filter }) => { const IncidentTable = ({ monitors, selectedMonitor, filter }) => {
const uiTimezone = useSelector((state) => state.ui.timezone);
const theme = useTheme(); const theme = useTheme();
const { authToken, user } = useSelector((state) => state.auth); const { authToken, user } = useSelector((state) => state.auth);
const mode = useSelector((state) => state.ui.mode);
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({
@@ -109,6 +116,7 @@ const IncidentTable = ({ monitors, selectedMonitor, filter }) => {
{...item} {...item}
/> />
)} )}
sx={{ mt: "auto" }}
/> />
); );
} }
@@ -125,12 +133,18 @@ const IncidentTable = ({ monitors, selectedMonitor, filter }) => {
<> <>
{checks?.length === 0 && selectedMonitor === "0" ? ( {checks?.length === 0 && selectedMonitor === "0" ? (
<Box sx={{ ...sharedStyles }}> <Box sx={{ ...sharedStyles }}>
<Box textAlign="center" pb={theme.spacing(20)}>
{mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />}
</Box>
<Typography textAlign="center" color={theme.palette.text.secondary}> <Typography textAlign="center" color={theme.palette.text.secondary}>
No incidents recorded yet. No incidents recorded yet.
</Typography> </Typography>
</Box> </Box>
) : checks?.length === 0 ? ( ) : checks?.length === 0 ? (
<Box sx={{ ...sharedStyles }}> <Box sx={{ ...sharedStyles }}>
<Box textAlign="center" pb={theme.spacing(20)}>
{mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />}
</Box>
<Typography textAlign="center" color={theme.palette.text.secondary}> <Typography textAlign="center" color={theme.palette.text.secondary}>
The monitor you have selected has no recorded incidents yet. The monitor you have selected has no recorded incidents yet.
</Typography> </Typography>
@@ -151,6 +165,11 @@ const IncidentTable = ({ monitors, selectedMonitor, filter }) => {
<TableBody> <TableBody>
{checks.map((check) => { {checks.map((check) => {
const status = check.status === true ? "up" : "down"; const status = check.status === true ? "up" : "down";
const formattedDate = formatDateWithTz(
check.createdAt,
"YYYY-MM-DD HH:mm:ss A",
uiTimezone
);
return ( return (
<TableRow key={check._id}> <TableRow key={check._id}>
@@ -162,9 +181,7 @@ const IncidentTable = ({ monitors, selectedMonitor, filter }) => {
customStyles={{ textTransform: "capitalize" }} customStyles={{ textTransform: "capitalize" }}
/> />
</TableCell> </TableCell>
<TableCell> <TableCell>{formattedDate}</TableCell>
{new Date(check.createdAt).toLocaleString()}
</TableCell>
<TableCell> <TableCell>
{check.statusCode ? check.statusCode : "N/A"} {check.statusCode ? check.statusCode : "N/A"}
</TableCell> </TableCell>
+20 -13
View File
@@ -1,16 +1,19 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { ButtonGroup, Stack, Typography, Button } from "@mui/material"; import { ButtonGroup, Stack, Typography, Button } from "@mui/material";
import { useParams } from "react-router-dom";
import { networkService } from "../../main"; import { networkService } from "../../main";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import Select from "../../Components/Inputs/Select"; import Select from "../../Components/Inputs/Select";
import IncidentTable from "./IncidentTable"; import IncidentTable from "./IncidentTable";
import "./index.css";
import SkeletonLayout from "./skeleton"; import SkeletonLayout from "./skeleton";
import "./index.css";
const Incidents = () => { const Incidents = () => {
const theme = useTheme(); const theme = useTheme();
const authState = useSelector((state) => state.auth); const authState = useSelector((state) => state.auth);
const { monitorId } = useParams();
const [monitors, setMonitors] = useState({}); const [monitors, setMonitors] = useState({});
const [selectedMonitor, setSelectedMonitor] = useState("0"); const [selectedMonitor, setSelectedMonitor] = useState("0");
@@ -22,17 +25,20 @@ const Incidents = () => {
useEffect(() => { useEffect(() => {
const fetchMonitors = async () => { const fetchMonitors = async () => {
setLoading(true); setLoading(true);
const res = await networkService.getMonitorsByTeamId( const res = await networkService.getMonitorsByTeamId({
authState.authToken, authToken: authState.authToken,
authState.user.teamId, teamId: authState.user.teamId,
1, limit: -1,
null, types: null,
null, status: null,
null, checkOrder: null,
null, normalize: null,
null, page: null,
null rowsPerPage: null,
); filter: null,
field: null,
order: null,
});
// Reduce to a lookup object for 0(1) lookup // Reduce to a lookup object for 0(1) lookup
if (res?.data?.data?.monitors?.length > 0) { if (res?.data?.data?.monitors?.length > 0) {
const monitorLookup = res.data.data.monitors.reduce((acc, monitor) => { const monitorLookup = res.data.data.monitors.reduce((acc, monitor) => {
@@ -40,6 +46,7 @@ const Incidents = () => {
return acc; return acc;
}, {}); }, {});
setMonitors(monitorLookup); setMonitors(monitorLookup);
monitorId !== undefined && setSelectedMonitor(monitorId);
} }
setLoading(false); setLoading(false);
}; };
@@ -54,7 +61,7 @@ const Incidents = () => {
}; };
return ( return (
<Stack className="incidents" pt={theme.spacing(20)} gap={theme.spacing(12)}> <Stack className="incidents" pt={theme.spacing(6)} gap={theme.spacing(12)}>
{loading ? ( {loading ? (
<SkeletonLayout /> <SkeletonLayout />
) : ( ) : (
@@ -1,6 +1,3 @@
.configure-monitor h1.MuiTypography-root + span.MuiTypography-root {
font-size: var(--env-var-font-size-small-plus);
}
.configure-monitor button.MuiButtonBase-root { .configure-monitor button.MuiButtonBase-root {
height: var(--env-var-height-2); height: var(--env-var-height-2);
} }
+3 -13
View File
@@ -223,12 +223,7 @@ const Configure = () => {
> >
<Stack direction="row" gap={theme.spacing(2)}> <Stack direction="row" gap={theme.spacing(2)}>
<Box> <Box>
<Typography <Typography component="h1" variant="h1">
component="h1"
fontSize={22}
fontWeight={500}
color={theme.palette.text.primary}
>
{monitor.name} {monitor.name}
</Typography> </Typography>
<Stack <Stack
@@ -259,17 +254,12 @@ const Configure = () => {
/> />
</Box> </Box>
</Tooltip> </Tooltip>
<Typography <Typography component="h2" variant="h2">
component="h2"
fontSize={14.5}
color={theme.palette.text.secondary}
>
{monitor.url?.replace(/^https?:\/\//, "") || "..."} {monitor.url?.replace(/^https?:\/\//, "") || "..."}
</Typography> </Typography>
<Typography <Typography
position="relative" position="relative"
fontSize={12} variant="body2"
color={theme.palette.text.tertiary}
ml={theme.spacing(6)} ml={theme.spacing(6)}
mt={theme.spacing(1)} mt={theme.spacing(1)}
sx={{ sx={{
@@ -1,7 +1,3 @@
.create-monitor h1.MuiTypography-root {
font-size: var(--env-var-font-size-large-plus);
font-weight: 500;
}
.create-monitor p.MuiTypography-root, .create-monitor p.MuiTypography-root,
.create-monitor button.MuiButtonBase-root { .create-monitor button.MuiButtonBase-root {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
@@ -177,14 +177,7 @@ const CreateMonitor = () => {
]; ];
return ( return (
<Box <Box className="create-monitor">
className="create-monitor"
sx={{
"& h1": {
color: theme.palette.text.primary,
},
}}
>
<Breadcrumbs <Breadcrumbs
list={[ list={[
{ name: "monitors", path: "/monitors" }, { name: "monitors", path: "/monitors" },
@@ -200,15 +193,16 @@ const CreateMonitor = () => {
gap={theme.spacing(12)} gap={theme.spacing(12)}
mt={theme.spacing(6)} mt={theme.spacing(6)}
> >
<Typography component="h1"> <Typography component="h1" variant="h1">
<Typography <Typography component="span" fontSize="inherit">
component="span"
fontSize="inherit"
color={theme.palette.text.secondary}
>
Create your{" "} Create your{" "}
</Typography> </Typography>
<Typography component="span" fontSize="inherit" fontWeight="inherit"> <Typography
component="span"
variant="h2"
fontSize="inherit"
fontWeight="inherit"
>
monitor monitor
</Typography> </Typography>
</Typography> </Typography>
@@ -262,7 +256,7 @@ const CreateMonitor = () => {
onChange={(event) => handleChange(event)} onChange={(event) => handleChange(event)}
/> />
{monitor.type === "http" ? ( {monitor.type === "http" ? (
<ButtonGroup sx={{ ml: "32px" }}> <ButtonGroup sx={{ ml: theme.spacing(16) }}>
<Button <Button
variant="group" variant="group"
filled={https.toString()} filled={https.toString()}
@@ -1,4 +1,5 @@
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import PropTypes from "prop-types";
import { import {
BarChart, BarChart,
Bar, Bar,
@@ -8,8 +9,9 @@ import {
RadialBarChart, RadialBarChart,
RadialBar, RadialBar,
} from "recharts"; } from "recharts";
import { formatDate } from "../../../../Utils/timeUtils";
import { memo, useMemo, useState } from "react"; import { memo, useMemo, useState } from "react";
import { useSelector } from "react-redux";
import { formatDateWithTz } from "../../../../Utils/timeUtils";
const CustomLabels = ({ const CustomLabels = ({
x, x,
@@ -19,27 +21,35 @@ const CustomLabels = ({
lastDataPoint, lastDataPoint,
type, type,
}) => { }) => {
let options = { const uiTimezone = useSelector((state) => state.ui.timezone);
month: "short", const dateFormat = type === "day" ? "MMM D, h:mm A" : "MMM D";
year: undefined,
hour: undefined,
minute: undefined,
};
if (type === "day") delete options.hour;
return ( return (
<> <>
<text x={x} y={height} dy={-3} textAnchor="start" fontSize={11}> <text x={x} y={height} dy={-3} textAnchor="start" fontSize={11}>
{formatDate(new Date(firstDataPoint.time), options)} {formatDateWithTz(
new Date(firstDataPoint.time),
dateFormat,
uiTimezone
)}
</text> </text>
<text x={width} y={height} dy={-3} textAnchor="end" fontSize={11}> <text x={width} y={height} dy={-3} textAnchor="end" fontSize={11}>
{formatDate(new Date(lastDataPoint.time), options)} {formatDateWithTz(new Date(lastDataPoint.time), dateFormat, uiTimezone)}
</text> </text>
</> </>
); );
}; };
export const UpBarChart = memo(({ data, type, onBarHover }) => { CustomLabels.propTypes = {
x: PropTypes.number.isRequired,
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
firstDataPoint: PropTypes.object.isRequired,
lastDataPoint: PropTypes.object.isRequired,
type: PropTypes.string.isRequired,
};
const UpBarChart = memo(({ data, type, onBarHover }) => {
const theme = useTheme(); const theme = useTheme();
const [chartHovered, setChartHovered] = useState(false); const [chartHovered, setChartHovered] = useState(false);
@@ -122,7 +132,18 @@ export const UpBarChart = memo(({ data, type, onBarHover }) => {
); );
}); });
export const DownBarChart = memo(({ data, type, onBarHover }) => { // Add display name for the component
UpBarChart.displayName = "UpBarChart";
// Validate props using PropTypes
UpBarChart.propTypes = {
data: PropTypes.arrayOf(PropTypes.object),
type: PropTypes.string,
onBarHover: PropTypes.func,
};
export { UpBarChart };
const DownBarChart = memo(({ data, type, onBarHover }) => {
const theme = useTheme(); const theme = useTheme();
const [chartHovered, setChartHovered] = useState(false); const [chartHovered, setChartHovered] = useState(false);
@@ -194,7 +215,15 @@ export const DownBarChart = memo(({ data, type, onBarHover }) => {
); );
}); });
export const ResponseGaugeChart = ({ data }) => { DownBarChart.displayName = "DownBarChart";
DownBarChart.propTypes = {
data: PropTypes.arrayOf(PropTypes.object),
type: PropTypes.string,
onBarHover: PropTypes.func,
};
export { DownBarChart };
const ResponseGaugeChart = ({ data }) => {
const theme = useTheme(); const theme = useTheme();
let max = 1000; // max ms let max = 1000; // max ms
@@ -281,3 +310,9 @@ export const ResponseGaugeChart = ({ data }) => {
</ResponsiveContainer> </ResponsiveContainer>
); );
}; };
ResponseGaugeChart.propTypes = {
data: PropTypes.arrayOf(PropTypes.object).isRequired,
};
export { ResponseGaugeChart };
@@ -18,10 +18,9 @@ import { StatusLabel } from "../../../../Components/Label";
import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded"; import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
import ArrowForwardRoundedIcon from "@mui/icons-material/ArrowForwardRounded"; import ArrowForwardRoundedIcon from "@mui/icons-material/ArrowForwardRounded";
import { logger } from "../../../../Utils/Logger"; import { logger } from "../../../../Utils/Logger";
import { useTheme } from "@emotion/react"; import { formatDateWithTz } from "../../../../Utils/timeUtils";
const PaginationTable = ({ monitorId, dateRange }) => { const PaginationTable = ({ monitorId, dateRange }) => {
const theme = useTheme();
const { authToken } = useSelector((state) => state.auth); const { authToken } = useSelector((state) => state.auth);
const [checks, setChecks] = useState([]); const [checks, setChecks] = useState([]);
const [checksCount, setChecksCount] = useState(0); const [checksCount, setChecksCount] = useState(0);
@@ -29,6 +28,7 @@ const PaginationTable = ({ monitorId, dateRange }) => {
page: 0, page: 0,
rowsPerPage: 5, rowsPerPage: 5,
}); });
const uiTimezone = useSelector((state) => state.ui.timezone);
useEffect(() => { useEffect(() => {
setPaginationController((prevPaginationController) => ({ setPaginationController((prevPaginationController) => ({
@@ -119,7 +119,11 @@ const PaginationTable = ({ monitorId, dateRange }) => {
/> />
</TableCell> </TableCell>
<TableCell> <TableCell>
{new Date(check.createdAt).toLocaleString()} {formatDateWithTz(
check.createdAt,
"ddd, MMMM D, YYYY, HH:mm A",
uiTimezone
)}
</TableCell> </TableCell>
<TableCell> <TableCell>
{check.statusCode ? check.statusCode : "N/A"} {check.statusCode ? check.statusCode : "N/A"}
+29 -43
View File
@@ -14,7 +14,6 @@ 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 { import {
formatDate,
formatDurationRounded, formatDurationRounded,
formatDurationSplit, formatDurationSplit,
} from "../../../Utils/timeUtils"; } from "../../../Utils/timeUtils";
@@ -35,6 +34,8 @@ 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";
/** /**
* Details page component displaying monitor details and related information. * Details page component displaying monitor details and related information.
* @component * @component
@@ -57,6 +58,9 @@ const DetailsPage = ({ isAdmin }) => {
setAnchorEl(null); setAnchorEl(null);
}; };
const dateFormat = dateRange === "day" ? "MMM D, h A" : "MMM D";
const uiTimezone = useSelector((state) => state.ui.timezone);
const fetchMonitor = useCallback(async () => { const fetchMonitor = useCallback(async () => {
try { try {
const res = await networkService.getStatsByMonitorId( const res = await networkService.getStatsByMonitorId(
@@ -95,10 +99,7 @@ const DetailsPage = ({ isAdmin }) => {
const date = new Date(year, month - 1, day); const date = new Date(year, month - 1, day);
setCertificateExpiry( setCertificateExpiry(
formatDate(date, { formatDateWithTz(date, dateFormat, uiTimezone) ?? "N/A"
hour: undefined,
minute: undefined,
}) ?? "N/A"
); );
} }
} catch (error) { } catch (error) {
@@ -138,12 +139,7 @@ const DetailsPage = ({ isAdmin }) => {
<Stack gap={theme.spacing(10)} mt={theme.spacing(10)}> <Stack gap={theme.spacing(10)} mt={theme.spacing(10)}>
<Stack direction="row" gap={theme.spacing(2)}> <Stack direction="row" gap={theme.spacing(2)}>
<Box> <Box>
<Typography <Typography component="h1" variant="h1">
component="h1"
fontSize={22}
fontWeight={500}
color={theme.palette.text.primary}
>
{monitor.name} {monitor.name}
</Typography> </Typography>
<Stack <Stack
@@ -172,19 +168,14 @@ const DetailsPage = ({ isAdmin }) => {
<PulseDot color={statusColor[determineState(monitor)]} /> <PulseDot color={statusColor[determineState(monitor)]} />
</Box> </Box>
</Tooltip> </Tooltip>
<Typography <Typography component="h2" variant="h2">
component="h2"
fontSize={14.5}
color={theme.palette.text.secondary}
>
{monitor.url?.replace(/^https?:\/\//, "") || "..."} {monitor.url?.replace(/^https?:\/\//, "") || "..."}
</Typography> </Typography>
<Typography <Typography
position="relative"
variant="body2"
mt={theme.spacing(1)} mt={theme.spacing(1)}
ml={theme.spacing(6)} ml={theme.spacing(6)}
fontSize={12}
position="relative"
color={theme.palette.text.tertiary}
sx={{ sx={{
"&:before": { "&:before": {
position: "absolute", position: "absolute",
@@ -217,6 +208,11 @@ const DetailsPage = ({ isAdmin }) => {
onClick={openCertificate} onClick={openCertificate}
sx={{ sx={{
cursor: "pointer", cursor: "pointer",
"& svg": {
width: 23,
height: 23,
top: "52%",
},
}} }}
> >
<CertificateIcon /> <CertificateIcon />
@@ -248,9 +244,7 @@ const DetailsPage = ({ isAdmin }) => {
}, },
}} }}
> >
<Typography fontSize={12} color={theme.palette.text.tertiary}> <Typography variant="body2">Certificate Expiry</Typography>
Certificate Expiry
</Typography>
<Typography <Typography
component="span" component="span"
fontSize={13} fontSize={13}
@@ -309,7 +303,7 @@ const DetailsPage = ({ isAdmin }) => {
gap={theme.spacing(4)} gap={theme.spacing(4)}
mb={theme.spacing(8)} mb={theme.spacing(8)}
> >
<Typography fontSize={12} color={theme.palette.text.tertiary}> <Typography variant="body2">
Showing statistics for past{" "} Showing statistics for past{" "}
{dateRange === "day" {dateRange === "day"
? "24 hours" ? "24 hours"
@@ -367,12 +361,11 @@ const DetailsPage = ({ isAdmin }) => {
fontSize={11} fontSize={11}
color={theme.palette.text.tertiary} color={theme.palette.text.tertiary}
> >
{formatDate(new Date(hoveredUptimeData.time), { {formatDateWithTz(
month: "short", hoveredUptimeData.time,
year: undefined, dateFormat,
minute: undefined, uiTimezone
hour: dateRange === "day" ? "numeric" : undefined, )}
})}
</Typography> </Typography>
)} )}
</Box> </Box>
@@ -417,12 +410,11 @@ const DetailsPage = ({ isAdmin }) => {
fontSize={11} fontSize={11}
color={theme.palette.text.tertiary} color={theme.palette.text.tertiary}
> >
{formatDate(new Date(hoveredIncidentsData.time), { {formatDateWithTz(
month: "short", hoveredIncidentsData.time,
year: undefined, dateFormat,
minute: undefined, uiTimezone
hour: dateRange === "day" ? "numeric" : undefined, )}
})}
</Typography> </Typography>
)} )}
</Box> </Box>
@@ -445,14 +437,8 @@ const DetailsPage = ({ isAdmin }) => {
data={[{ response: monitor?.periodAvgResponseTime }]} data={[{ response: monitor?.periodAvgResponseTime }]}
/> />
</ChartBox> </ChartBox>
<ChartBox <ChartBox sx={{ padding: 0 }}>
sx={{ <Stack pt={theme.spacing(8)} pl={theme.spacing(8)}>
"& tspan": {
fontSize: 11,
},
}}
>
<Stack>
<IconBox> <IconBox>
<ResponseTimeIcon /> <ResponseTimeIcon />
</IconBox> </IconBox>
+2 -1
View File
@@ -40,7 +40,7 @@ export const ChartBox = styled(Stack)(({ theme }) => ({
fill: theme.palette.text.tertiary, fill: theme.palette.text.tertiary,
}, },
"& path": { "& path": {
transition: "fill 300ms ease", transition: "fill 300ms ease, stroke-width 400ms ease",
}, },
})); }));
@@ -76,6 +76,7 @@ export const StatBox = styled(Box)(({ theme }) => ({
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
borderRadius: 4, borderRadius: 4,
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
background: `linear-gradient(340deg, ${theme.palette.background.accent} 20%, ${theme.palette.background.main} 45%)`,
"& h2": { "& h2": {
fontSize: 13, fontSize: 13,
fontWeight: 500, fontWeight: 500,
@@ -14,9 +14,10 @@ import {
Button, Button,
} from "@mui/material"; } from "@mui/material";
import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded"; import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded";
import ArrowUpwardRoundedIcon from "@mui/icons-material/ArrowUpwardRounded";
import { setRowsPerPage } from "../../../../Features/UI/uiSlice"; import { setRowsPerPage } from "../../../../Features/UI/uiSlice";
import { useState, useEffect } from "react"; import { useState, useEffect, memo } from "react";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
import { logger } from "../../../../Utils/Logger"; import { logger } from "../../../../Utils/Logger";
import Host from "../host"; import Host from "../host";
@@ -48,6 +49,7 @@ import useUtils from "../../utils";
*/ */
const TablePaginationActions = (props) => { const TablePaginationActions = (props) => {
const { count, page, rowsPerPage, onPageChange } = props; const { count, page, rowsPerPage, onPageChange } = props;
const handleFirstPageButtonClick = (event) => { const handleFirstPageButtonClick = (event) => {
onPageChange(event, 0); onPageChange(event, 0);
}; };
@@ -106,7 +108,7 @@ TablePaginationActions.propTypes = {
onPageChange: PropTypes.func.isRequired, onPageChange: PropTypes.func.isRequired,
}; };
const MonitorTable = ({ isAdmin }) => { const MonitorTable = ({ isAdmin, filter }) => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const dispatch = useDispatch(); const dispatch = useDispatch();
@@ -118,6 +120,7 @@ const MonitorTable = ({ isAdmin }) => {
const [monitorCount, setMonitorCount] = useState(0); const [monitorCount, setMonitorCount] = useState(0);
const authState = useSelector((state) => state.auth); const authState = useSelector((state) => state.auth);
const [updateTrigger, setUpdateTrigger] = useState(false); const [updateTrigger, setUpdateTrigger] = useState(false);
const [sort, setSort] = useState({});
const handleActionMenuDelete = () => { const handleActionMenuDelete = () => {
setUpdateTrigger((prev) => !prev); setUpdateTrigger((prev) => !prev);
@@ -142,17 +145,20 @@ const MonitorTable = ({ isAdmin }) => {
try { try {
const { authToken } = authState; const { authToken } = authState;
const user = jwtDecode(authToken); const user = jwtDecode(authToken);
const res = await networkService.getMonitorsByTeamId( const res = await networkService.getMonitorsByTeamId({
authToken, authToken,
user.teamId, teamId: user.teamId,
25, limit: 25,
["http", "ping"], types: ["http", "ping"],
null, status: null,
"desc", checkOrder: "desc",
true, normalize: true,
page, page: page,
rowsPerPage rowsPerPage: rowsPerPage,
); filter: filter,
field: sort.field,
order: sort.order,
});
setMonitors(res?.data?.data?.monitors ?? []); setMonitors(res?.data?.data?.monitors ?? []);
setMonitorCount(res?.data?.data?.monitorCount ?? 0); setMonitorCount(res?.data?.data?.monitorCount ?? 0);
} catch (error) { } catch (error) {
@@ -160,7 +166,7 @@ const MonitorTable = ({ isAdmin }) => {
} }
}; };
fetchPage(); fetchPage();
}, [updateTrigger, authState, page, rowsPerPage]); }, [updateTrigger, authState, page, rowsPerPage, filter, sort]);
/** /**
* Helper function to calculate the range of displayed rows. * Helper function to calculate the range of displayed rows.
@@ -172,19 +178,80 @@ const MonitorTable = ({ isAdmin }) => {
return `${start} - ${end}`; return `${start} - ${end}`;
}; };
const handleSort = async (field) => {
let order = "";
if (sort.field !== field) {
order = "desc";
} else {
order = sort.order === "asc" ? "desc" : "asc";
}
setSort({ field, order });
const { authToken } = authState;
const user = jwtDecode(authToken);
const res = await networkService.getMonitorsByTeamId({
authToken,
teamId: user.teamId,
limit: 25,
types: ["http", "ping"],
status: null,
checkOrder: "desc",
normalize: true,
page: page,
rowsPerPage: rowsPerPage,
filter: null,
field: field,
order: order,
});
setMonitors(res?.data?.data?.monitors ?? []);
setMonitorCount(res?.data?.data?.monitorCount ?? 0);
};
return ( return (
<> <>
<TableContainer component={Paper}> <TableContainer component={Paper}>
<Table> <Table>
<TableHead> <TableHead>
<TableRow> <TableRow>
<TableCell>Host</TableCell> <TableCell
<TableCell> sx={{ cursor: "pointer" }}
onClick={() => handleSort("name")}
>
<Box>
Host
<span
style={{
visibility: sort.field === "name" ? "visible" : "hidden",
}}
>
{sort.order === "asc" ? (
<ArrowUpwardRoundedIcon />
) : (
<ArrowDownwardRoundedIcon />
)}
</span>
</Box>
</TableCell>
<TableCell
sx={{ cursor: "pointer" }}
onClick={() => handleSort("status")}
>
{" "} {" "}
<Box width="max-content"> <Box width="max-content">
{" "}
Status Status
<span> <span
<ArrowDownwardRoundedIcon /> style={{
visibility:
sort.field === "status" ? "visible" : "hidden",
}}
>
{sort.order === "asc" ? (
<ArrowUpwardRoundedIcon />
) : (
<ArrowDownwardRoundedIcon />
)}
</span> </span>
</Box> </Box>
</TableCell> </TableCell>
@@ -272,13 +339,8 @@ const MonitorTable = ({ isAdmin }) => {
alignItems="center" alignItems="center"
justifyContent="space-between" justifyContent="space-between"
px={theme.spacing(4)} px={theme.spacing(4)}
sx={{
"& p": {
color: theme.palette.text.tertiary,
},
}}
> >
<Typography px={theme.spacing(2)} fontSize={12} sx={{ opacity: 0.7 }}> <Typography px={theme.spacing(2)} variant="body2" sx={{ opacity: 0.7 }}>
Showing {getRange()} of {monitorCount} monitor(s) Showing {getRange()} of {monitorCount} monitor(s)
</Typography> </Typography>
<TablePagination <TablePagination
@@ -344,6 +406,8 @@ const MonitorTable = ({ isAdmin }) => {
MonitorTable.propTypes = { MonitorTable.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
filter: PropTypes.string,
}; };
export default MonitorTable; const MemoizedMonitorTable = memo(MonitorTable);
export default MemoizedMonitorTable;
+11 -4
View File
@@ -91,6 +91,7 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
anchorEl={anchorEl} anchorEl={anchorEl}
open={Boolean(anchorEl)} open={Boolean(anchorEl)}
onClose={(e) => closeMenu(e)} onClose={(e) => closeMenu(e)}
disableScrollLock
slotProps={{ slotProps={{
paper: { paper: {
sx: { sx: {
@@ -125,7 +126,14 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
Details Details
</MenuItem> </MenuItem>
{/* TODO - pass monitor id to Incidents page */} {/* TODO - pass monitor id to Incidents page */}
<MenuItem disabled>Incidents</MenuItem> <MenuItem
onClick={(e) => {
e.stopPropagation();
navigate(`/incidents/${actions.id}`);
}}
>
Incidents
</MenuItem>
{isAdmin && ( {isAdmin && (
<MenuItem <MenuItem
onClick={(e) => { onClick={(e) => {
@@ -169,7 +177,6 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
> >
<Stack <Stack
gap={theme.spacing(2)} gap={theme.spacing(2)}
color={theme.palette.text.secondary}
sx={{ sx={{
position: "absolute", position: "absolute",
top: "50%", top: "50%",
@@ -187,10 +194,10 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
}, },
}} }}
> >
<Typography id="modal-delete-monitor" component="h2" fontWeight={600}> <Typography id="modal-delete-monitor" component="h2" variant="h2">
Do you really want to delete this monitor? Do you really want to delete this monitor?
</Typography> </Typography>
<Typography id="delete-monitor-confirmation" fontSize={13}> <Typography id="delete-monitor-confirmation" variant="body1">
Once deleted, this monitor cannot be retrieved. Once deleted, this monitor cannot be retrieved.
</Typography> </Typography>
<Stack <Stack
+13 -3
View File
@@ -1,25 +1,35 @@
import { Button, Stack, Typography } from "@mui/material"; import { Box, Button, Stack, Typography } from "@mui/material";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
import PlaceholderLight from "../../../assets/Images/data_placeholder.svg?react";
import PlaceholderDark from "../../../assets/Images/data_placeholder_dark.svg?react";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
const Fallback = ({ isAdmin }) => { const Fallback = ({ isAdmin }) => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const mode = useSelector((state) => state.ui.mode);
return ( return (
<Stack <Stack
alignItems="center" alignItems="center"
backgroundColor={theme.palette.background.main} backgroundColor={theme.palette.background.main}
p={theme.spacing(30)} p={theme.spacing(30)}
pt={theme.spacing(25)}
gap={theme.spacing(2)} gap={theme.spacing(2)}
border={1} border={1}
borderRadius={theme.shape.borderRadius} borderRadius={theme.shape.borderRadius}
borderColor={theme.palette.border.light} borderColor={theme.palette.border.light}
color={theme.palette.text.secondary} color={theme.palette.text.secondary}
> >
<Typography component="h2">No monitors found</Typography> <Box pb={theme.spacing(20)}>
<Typography> {mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />}
</Box>
<Typography component="h2" variant="h2" fontWeight={500}>
No monitors found to display
</Typography>
<Typography variant="body1">
It looks like you don’t have any monitors set up yet. It looks like you don’t have any monitors set up yet.
</Typography> </Typography>
{isAdmin && ( {isAdmin && (
-11
View File
@@ -1,14 +1,3 @@
.monitors h1.MuiTypography-root {
font-size: var(--env-var-font-size-large-plus);
font-weight: 500;
}
.monitors h2.MuiTypography-root {
font-size: var(--env-var-font-size-large);
font-weight: 500;
}
.monitors h1.MuiTypography-root + p.MuiTypography-root {
font-size: var(--env-var-font-size-medium-plus);
}
.monitors .MuiStack-root > button:not(.MuiIconButton-root) { .monitors .MuiStack-root > button:not(.MuiIconButton-root) {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
height: var(--env-var-height-2); height: var(--env-var-height-2);
+20 -6
View File
@@ -1,5 +1,5 @@
import "./index.css"; import "./index.css";
import { useEffect } from "react"; import { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux"; import { useSelector, useDispatch } from "react-redux";
import { getUptimeMonitorsByTeamId } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; import { getUptimeMonitorsByTeamId } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
@@ -12,13 +12,17 @@ import StatusBox from "./StatusBox";
import Breadcrumbs from "../../../Components/Breadcrumbs"; import Breadcrumbs from "../../../Components/Breadcrumbs";
import Greeting from "../../../Utils/greeting"; import Greeting from "../../../Utils/greeting";
import MonitorTable from "./MonitorTable"; import MonitorTable from "./MonitorTable";
import Search from "../../../Components/Inputs/Search";
import useDebounce from "../../../Utils/debounce";
const Monitors = ({ isAdmin }) => { const Monitors = ({ isAdmin }) => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const monitorState = useSelector((state) => state.uptimeMonitors); const monitorState = useSelector((state) => state.uptimeMonitors);
const authState = useSelector((state) => state.auth); const authState = useSelector((state) => state.auth);
const [search, setSearch] = useState("");
const dispatch = useDispatch({}); const dispatch = useDispatch({});
const debouncedFilter = useDebounce(search, 500);
useEffect(() => { useEffect(() => {
dispatch(getUptimeMonitorsByTeamId(authState.authToken)); dispatch(getUptimeMonitorsByTeamId(authState.authToken));
@@ -26,6 +30,7 @@ const Monitors = ({ isAdmin }) => {
let loading = let loading =
monitorState?.isLoading && monitorState?.isLoading &&
monitorState?.monitorsSummary?.monitors?.length === 0; monitorState?.monitorsSummary?.monitors?.length === 0;
return ( return (
<Stack className="monitors" gap={theme.spacing(8)}> <Stack className="monitors" gap={theme.spacing(8)}>
{loading ? ( {loading ? (
@@ -85,7 +90,8 @@ const Monitors = ({ isAdmin }) => {
</Stack> </Stack>
<Box <Box
flex={1} flex={1}
p={theme.spacing(10)} px={theme.spacing(10)}
py={theme.spacing(8)}
border={1} border={1}
borderColor={theme.palette.border.light} borderColor={theme.palette.border.light}
borderRadius={theme.shape.borderRadius} borderRadius={theme.shape.borderRadius}
@@ -98,8 +104,9 @@ const Monitors = ({ isAdmin }) => {
> >
<Typography <Typography
component="h2" component="h2"
color={theme.palette.text.secondary} variant="h2"
letterSpacing={-0.5} fontWeight={500}
letterSpacing={-0.2}
> >
Actively monitoring Actively monitoring
</Typography> </Typography>
@@ -112,9 +119,16 @@ const Monitors = ({ isAdmin }) => {
> >
{monitorState?.monitorsSummary?.monitorCounts?.total || 0} {monitorState?.monitorsSummary?.monitorCounts?.total || 0}
</Box> </Box>
{/* TODO - add search bar */} <Box width="25%" minWidth={150} ml="auto">
<Search
options={monitorState?.monitorsSummary.monitors}
filteredBy="name"
value={search}
handleInputChange={setSearch}
/>
</Box>
</Stack> </Stack>
<MonitorTable isAdmin={isAdmin} /> <MonitorTable isAdmin={isAdmin} filter={debouncedFilter} />
</Box> </Box>
</> </>
)} )}
+1 -9
View File
@@ -24,15 +24,7 @@ const SkeletonLayout = () => {
<Skeleton variant="rounded" width="100%" height={100} /> <Skeleton variant="rounded" width="100%" height={100} />
<Skeleton variant="rounded" width="100%" height={100} /> <Skeleton variant="rounded" width="100%" height={100} />
</Stack> </Stack>
<Stack <Skeleton variant="rounded" width="100%" height="100%" flex={1} />
gap={theme.spacing(12)}
p={theme.spacing(20)}
backgroundColor="#f9fafb"
>
<Skeleton variant="rounded" width="50%" height={25} />
<Skeleton variant="rounded" width="100%" height={300} />
<Skeleton variant="rounded" width="100%" height={100} />
</Stack>
</> </>
); );
}; };
+30 -3
View File
@@ -29,31 +29,58 @@ const useUtils = () => {
const statusStyles = { const statusStyles = {
up: { up: {
backgroundColor: theme.palette.success.bg, backgroundColor: theme.palette.success.bg,
background: `linear-gradient(340deg, ${theme.palette.success.light} -60%, ${theme.palette.success.bg} 35%)`,
borderColor: theme.palette.success.light, borderColor: theme.palette.success.light,
"& h2": { color: theme.palette.success.main }, "& h2": { color: theme.palette.success.main },
}, },
down: { down: {
backgroundColor: theme.palette.error.bg, backgroundColor: theme.palette.error.bg,
background: `linear-gradient(340deg, ${theme.palette.error.light} -60%, ${theme.palette.error.bg} 35%)`,
borderColor: theme.palette.error.light, borderColor: theme.palette.error.light,
"& h2": { color: theme.palette.error.main }, "& h2": { color: theme.palette.error.main },
}, },
paused: { paused: {
backgroundColor: theme.palette.warning.light, backgroundColor: theme.palette.warning.bg,
borderColor: theme.palette.warning.border, background: `linear-gradient(340deg, ${theme.palette.warning.light} -60%, ${theme.palette.warning.bg} 35%)`,
borderColor: theme.palette.warning.light,
"& h2": { color: theme.palette.warning.main }, "& h2": { color: theme.palette.warning.main },
}, },
pending: { pending: {
backgroundColor: theme.palette.warning.light, backgroundColor: theme.palette.warning.light,
borderColor: theme.palette.warning.border, background: `linear-gradient(340deg, ${theme.palette.warning.dark} -60%, ${theme.palette.warning.light} 35%)`,
borderColor: theme.palette.warning.dark,
"& h2": { color: theme.palette.warning.main }, "& h2": { color: theme.palette.warning.main },
}, },
}; };
const pagespeedStyles = {
up: {
bg: theme.palette.success.bg,
light: theme.palette.success.light,
stroke: theme.palette.success.main,
},
down: {
bg: theme.palette.error.bg,
light: theme.palette.error.light,
stroke: theme.palette.error.main,
},
paused: {
bg: theme.palette.warning.bg,
light: theme.palette.warning.light,
stroke: theme.palette.warning.main,
},
pending: {
bg: theme.palette.warning.bg,
light: theme.palette.warning.light,
stroke: theme.palette.warning.main,
},
};
return { return {
determineState, determineState,
statusColor, statusColor,
statusMsg, statusMsg,
pagespeedStatusMsg, pagespeedStatusMsg,
pagespeedStyles,
statusStyles, statusStyles,
}; };
}; };
+3 -7
View File
@@ -36,16 +36,12 @@ const NotFound = ({ title = DefaultValue.title, desc = DefaultValue.desc }) => {
return ( return (
<Stack height="100vh" justifyContent="center"> <Stack height="100vh" justifyContent="center">
<Stack <Stack gap={theme.spacing(2)} alignItems="center">
gap={theme.spacing(2)}
alignItems="center"
color={theme.palette.text.secondary}
>
<img src={NotFoundSvg} alt="404" style={{ maxHeight: "25rem" }} /> <img src={NotFoundSvg} alt="404" style={{ maxHeight: "25rem" }} />
<Typography component="h1" fontSize={16} fontWeight={600}> <Typography component="h1" variant="h1" fontSize={16}>
{title} {title}
</Typography> </Typography>
<Typography fontSize={13}>{desc}</Typography> <Typography variant="body1">{desc}</Typography>
<Button <Button
variant="contained" variant="contained"
color="primary" color="primary"
@@ -1,47 +1,7 @@
.configure-pagespeed h1.MuiTypography-root {
font-size: var(--env-var-font-size-large-plus);
}
.configure-pagespeed span.MuiTypography-root {
font-size: var(--env-var-font-size-small-plus);
}
.configure-pagespeed h1.MuiTypography-root,
.configure-pagespeed h3.MuiTypography-root,
.configure-pagespeed h2.MuiTypography-root {
font-weight: 600;
}
.configure-pagespeed p.MuiTypography-root,
.configure-pagespeed h3.MuiTypography-root,
.configure-pagespeed h3.MuiTypography-root > span.MuiTypography-root {
font-size: var(--env-var-font-size-medium);
}
.configure-pagespeed .MuiBox-root > .field + p.MuiTypography-root {
font-size: var(--env-var-font-size-small-plus);
}
.configure-pagespeed .MuiBox-root > .field + p.MuiTypography-root,
.configure-pagespeed h3.MuiTypography-root > span.MuiTypography-root {
opacity: 0.6;
}
.configure-pagespeed .checkbox-wrapper {
margin-bottom: 1px;
}
/* to be removed */
.configure-pagespeed .section-disabled {
opacity: 0.4;
padding: 10px;
border-radius: 8px;
user-select: none;
pointer-events: none;
}
.configure-pagespeed button { .configure-pagespeed button {
height: var(--env-var-height-2); height: var(--env-var-height-2);
} }
.configure-pagespeed h3.MuiTypography-root {
flex: 0.7;
}
.configure-pagespeed .field, .configure-pagespeed .field,
.configure-pagespeed .section-disabled, .configure-pagespeed .section-disabled,
.configure-pagespeed .select-wrapper { .configure-pagespeed .select-wrapper {
+203 -108
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { Box, Button, Modal, Stack, Typography } from "@mui/material"; import { Box, Button, Modal, Stack, Tooltip, Typography } from "@mui/material";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router"; import { useNavigate, useParams } from "react-router";
import { import {
@@ -13,6 +13,7 @@ import {
import { monitorValidation } from "../../../Validation/validation"; import { monitorValidation } from "../../../Validation/validation";
import { createToast } from "../../../Utils/toastUtils"; import { createToast } from "../../../Utils/toastUtils";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
import { ConfigBox } from "../../Monitors/styled";
import Field from "../../../Components/Inputs/Field"; import Field from "../../../Components/Inputs/Field";
import Select from "../../../Components/Inputs/Select"; import Select from "../../../Components/Inputs/Select";
import Checkbox from "../../../Components/Inputs/Checkbox"; import Checkbox from "../../../Components/Inputs/Checkbox";
@@ -22,20 +23,27 @@ import PulseDot from "../../../Components/Animated/PulseDot";
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import PlayCircleOutlineRoundedIcon from "@mui/icons-material/PlayCircleOutlineRounded"; import PlayCircleOutlineRoundedIcon from "@mui/icons-material/PlayCircleOutlineRounded";
import SkeletonLayout from "./skeleton"; import SkeletonLayout from "./skeleton";
import "./index.css";
import useUtils from "../../Monitors/utils"; import useUtils from "../../Monitors/utils";
import "./index.css";
const PageSpeedConfigure = () => { const PageSpeedConfigure = () => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const dispatch = useDispatch(); const dispatch = useDispatch();
const MS_PER_MINUTE = 60000; const MS_PER_MINUTE = 60000;
const { authToken } = useSelector((state) => state.auth); const { user, authToken } = useSelector((state) => state.auth);
const { isLoading } = useSelector((state) => state.pageSpeedMonitors); const { isLoading } = useSelector((state) => state.pageSpeedMonitors);
const { monitorId } = useParams(); const { monitorId } = useParams();
const [monitor, setMonitor] = useState({}); const [monitor, setMonitor] = useState({});
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const { determineState, statusColor } = useUtils(); const { statusColor, pagespeedStatusMsg, determineState } = useUtils();
const idMap = {
"monitor-url": "url",
"monitor-name": "name",
"monitor-checks-http": "type",
"monitor-checks-ping": "type",
"notify-email-default": "notification-email",
};
const frequencies = [ const frequencies = [
{ _id: 3, name: "3 minutes" }, { _id: 3, name: "3 minutes" },
@@ -68,24 +76,58 @@ const PageSpeedConfigure = () => {
fetchMonitor(); fetchMonitor();
}, [dispatch, authToken, monitorId, navigate]); }, [dispatch, authToken, monitorId, navigate]);
const handleChange = (event, id) => { const handleChange = (event, name) => {
let { value } = event.target; let { value, id } = event.target;
if (id === "interval") { if (!name) name = idMap[id];
value = value * MS_PER_MINUTE;
if (name.includes("notification-")) {
name = name.replace("notification-", "");
let hasNotif = monitor.notifications.some(
(notification) => notification.type === name
);
setMonitor((prev) => {
const notifs = [...prev.notifications];
if (hasNotif) {
return {
...prev,
notifications: notifs.filter((notif) => notif.type !== name),
};
} else {
return {
...prev,
notifications: [
...notifs,
name === "email"
? { type: name, address: value }
: // TODO - phone number
{ type: name, phone: value },
],
};
}
});
} else {
if (name === "interval") {
value = value * MS_PER_MINUTE;
}
setMonitor((prev) => ({
...prev,
[name]: value,
}));
const validation = monitorValidation.validate(
{ [name]: value },
{ abortEarly: false }
);
setErrors((prev) => {
const updatedErrors = { ...prev };
if (validation.error)
updatedErrors[name] = validation.error.details[0].message;
else delete updatedErrors[name];
return updatedErrors;
});
} }
setMonitor((prev) => ({ ...prev, [id]: value }));
const { error } = monitorValidation.validate(
{ [id]: value },
{ abortEarly: false }
);
setErrors((prev) => {
const newErrors = { ...prev };
if (error) newErrors[id] = error.details[0].message;
else delete newErrors[id];
return newErrors;
});
}; };
const handlePause = async () => { const handlePause = async () => {
@@ -128,7 +170,7 @@ const PageSpeedConfigure = () => {
}; };
return ( return (
<Stack className="configure-pagespeed" gap={theme.spacing(12)}> <Stack className="configure-pagespeed" gap={theme.spacing(10)}>
{Object.keys(monitor).length === 0 ? ( {Object.keys(monitor).length === 0 ? (
<SkeletonLayout /> <SkeletonLayout />
) : ( ) : (
@@ -146,27 +188,65 @@ const PageSpeedConfigure = () => {
spellCheck="false" spellCheck="false"
onSubmit={handleSave} onSubmit={handleSave}
flex={1} flex={1}
gap={theme.spacing(12)} gap={theme.spacing(10)}
> >
<Stack direction="row" gap={theme.spacing(2)}> <Stack direction="row" gap={theme.spacing(2)}>
<PulseDot color={statusColor[determineState(monitor)]} />
<Box> <Box>
<Typography <Typography component="h1" variant="h1">
component="h1" {monitor.name}
mb={theme.spacing(2)}
sx={{ lineHeight: 1 }}
color={theme.palette.text.primary}
>
{monitor?.url}
</Typography> </Typography>
<Typography <Stack
component="span" direction="row"
sx={{ alignItems="center"
color: statusColor[determineState(monitor)], height="fit-content"
}} gap={theme.spacing(2)}
> >
Your pagespeed monitor is {determineState(monitor)}. <Tooltip
</Typography> title={pagespeedStatusMsg[determineState(monitor)]}
disableInteractive
slotProps={{
popper: {
modifiers: [
{
name: "offset",
options: {
offset: [0, -8],
},
},
],
},
}}
>
<Box>
<PulseDot color={statusColor[determineState(monitor)]} />
</Box>
</Tooltip>
<Typography component="h2" variant="h2">
{monitor.url?.replace(/^https?:\/\//, "") || "..."}
</Typography>
<Typography
position="relative"
variant="body2"
ml={theme.spacing(6)}
mt={theme.spacing(1)}
sx={{
"&:before": {
position: "absolute",
content: `""`,
width: 4,
height: 4,
borderRadius: "50%",
backgroundColor: theme.palette.text.tertiary,
opacity: 0.8,
left: -10,
top: "50%",
transform: "translateY(-50%)",
},
}}
>
Editting...
</Typography>
</Stack>
</Box> </Box>
<Box alignSelf="flex-end" ml="auto"> <Box alignSelf="flex-end" ml="auto">
<LoadingButton <LoadingButton
@@ -211,102 +291,116 @@ const PageSpeedConfigure = () => {
</LoadingButton> </LoadingButton>
</Box> </Box>
</Stack> </Stack>
<Stack <ConfigBox>
border={1} <Box>
borderColor={theme.palette.border.light} <Typography component="h2">General settings</Typography>
borderRadius={theme.shape.borderRadius} <Typography component="p">
backgroundColor={theme.palette.background.main} Here you can select the URL of the host, together with the
p={theme.spacing(20)} type of monitor.
pl={theme.spacing(15)} </Typography>
gap={theme.spacing(20)} </Box>
sx={{
"& h3, & p": {
color: theme.palette.text.secondary,
},
}}
>
<Stack direction="row">
<Typography component="h3">Monitor display name</Typography>
<Field
type="text"
id="monitor-name"
placeholder="Example monitor"
value={monitor?.name || ""}
onChange={(event) => handleChange(event, "name")}
error={errors.name}
/>
</Stack>
<Stack <Stack
direction="row" gap={theme.spacing(20)}
sx={{ sx={{
".MuiInputBase-root:has(> .Mui-disabled)": { ".MuiInputBase-root:has(> .Mui-disabled)": {
backgroundColor: theme.palette.background.accent, backgroundColor: theme.palette.background.accent,
}, },
}} }}
> >
<Typography component="h3">URL</Typography>
<Field <Field
type="url" type="url"
id="monitor-url" id="monitor-url"
label="URL"
placeholder="random.website.com" placeholder="random.website.com"
value={monitor?.url?.replace("http://", "") || ""} value={monitor?.url?.replace("http://", "") || ""}
onChange={(event) => handleChange(event, "url")} onChange={handleChange}
error={errors.url} error={errors.url}
disabled={true} disabled={true}
/> />
</Stack> <Field
<Stack direction="row"> type="text"
<Typography component="h3">Check frequency</Typography> id="monitor-name"
<Select label="Monitor display name"
id="monitor-frequency" placeholder="Example monitor"
items={frequencies} isOptional={true}
value={monitor?.interval / MS_PER_MINUTE || 3} value={monitor?.name || ""}
onChange={(event) => handleChange(event, "interval")} onChange={handleChange}
error={errors.name}
/> />
</Stack> </Stack>
<Stack direction="row"> </ConfigBox>
<Typography component="h3"> <ConfigBox>
Incidents notifications{" "} <Box>
<Typography component="span">(coming soon)</Typography> <Typography component="h2">Incident notifications</Typography>
<Typography component="p">
When there is an incident, notify users.
</Typography> </Typography>
<Stack </Box>
className="section-disabled" <Stack gap={theme.spacing(6)}>
backgroundColor={theme.palette.background.fill} <Typography component="p">
> When there is a new incident,
<Typography mb={theme.spacing(4)}> </Typography>
When there is a new incident, <Checkbox
</Typography> id="notify-sms"
<Checkbox label="Notify via SMS (coming soon)"
id="notify-sms" isChecked={false}
label="Notify via SMS (coming soon)" value=""
isChecked={false} onChange={() => logger.warn("disabled")}
isDisabled={true} isDisabled={true}
/> />
<Checkbox <Checkbox
id="notify-email" id="notify-email-default"
label="Notify via email (to gorkem.cetin@bluewavelabs.ca)" label={`Notify via email (to ${user.email})`}
isChecked={false} isChecked={
/> monitor?.notifications?.some(
<Checkbox (notification) => notification.type === "email"
id="notify-emails" ) || false
label="Notify via email to following emails" }
isChecked={false} value={user?.email}
/> onChange={(event) => handleChange(event)}
/>
<Checkbox
id="notify-email"
label="Also notify via email to multiple addresses (coming soon)"
isChecked={false}
value=""
onChange={() => logger.warn("disabled")}
isDisabled={true}
/>
{monitor?.notifications?.some(
(notification) => notification.type === "emails"
) ? (
<Box mx={theme.spacing(16)}> <Box mx={theme.spacing(16)}>
<Field <Field
id="notify-emails-list" id="notify-email-list"
placeholder="notifications@gmail.com" type="text"
placeholder="name@gmail.com"
value="" value=""
onChange={() => logger.warn("disabled")} onChange={() => logger.warn("disabled")}
error=""
/> />
<Typography mt={theme.spacing(4)}> <Typography mt={theme.spacing(4)}>
You can separate multiple emails with a comma You can separate multiple emails with a comma
</Typography> </Typography>
</Box> </Box>
</Stack> ) : (
""
)}
</Stack> </Stack>
</Stack> </ConfigBox>
<ConfigBox>
<Box>
<Typography component="h2">Advanced settings</Typography>
</Box>
<Stack gap={theme.spacing(20)}>
<Select
id="monitor-frequency"
label="Check frequency"
items={frequencies}
value={monitor?.interval / MS_PER_MINUTE || 3}
onChange={(event) => handleChange(event, "interval")}
/>
</Stack>
</ConfigBox>
<Stack direction="row" justifyContent="flex-end" mt="auto"> <Stack direction="row" justifyContent="flex-end" mt="auto">
<LoadingButton <LoadingButton
loading={isLoading} loading={isLoading}
@@ -351,13 +445,14 @@ const PageSpeedConfigure = () => {
<Typography <Typography
id="modal-delete-pagespeed-monitor" id="modal-delete-pagespeed-monitor"
component="h2" component="h2"
color={theme.palette.text.secondary} variant="h2"
fontWeight={500}
> >
Do you really want to delete this monitor? Do you really want to delete this monitor?
</Typography> </Typography>
<Typography <Typography
id="delete-pagespeed-monitor-confirmation" id="delete-pagespeed-monitor-confirmation"
color={theme.palette.text.tertiary} variant="body1"
> >
Once deleted, this monitor cannot be retrieved. Once deleted, this monitor cannot be retrieved.
</Typography> </Typography>
@@ -1,43 +0,0 @@
.create-page-speed h1.MuiTypography-root,
.create-page-speed h3.MuiTypography-root {
font-weight: 600;
}
.create-page-speed p.MuiTypography-root,
.create-page-speed h3.MuiTypography-root,
.create-page-speed h3.MuiTypography-root > span.MuiTypography-root {
font-size: var(--env-var-font-size-medium);
}
.create-page-speed .MuiBox-root > .field + p.MuiTypography-root {
font-size: var(--env-var-font-size-small-plus);
}
.create-page-speed .MuiBox-root > .field + p.MuiTypography-root,
.create-page-speed h3.MuiTypography-root > span.MuiTypography-root {
opacity: 0.6;
}
.create-page-speed .checkbox-wrapper {
margin-bottom: 1px;
}
/* to be removed */
.create-page-speed .section-disabled {
opacity: 0.4;
padding: 10px;
margin-right: -5px;
border-radius: 8px;
user-select: none;
pointer-events: none;
}
.create-page-speed button {
height: var(--env-var-height-2);
}
.create-page-speed h3.MuiTypography-root {
flex: 0.7;
}
.create-page-speed .field,
.create-page-speed .section-disabled,
.create-page-speed .select-wrapper {
flex: 1;
}
@@ -164,16 +164,17 @@ const CreatePageSpeed = () => {
gap={theme.spacing(12)} gap={theme.spacing(12)}
mt={theme.spacing(6)} mt={theme.spacing(6)}
> >
<Typography component="h1"> <Typography component="h1" variant="h1">
<Typography component="span" fontSize="inherit">
Create your{" "}
</Typography>
<Typography <Typography
component="span" component="span"
fontSize="inherit" fontSize="inherit"
fontWeight="inherit"
color={theme.palette.text.secondary} color={theme.palette.text.secondary}
> >
Create your{" "} pagespeed monitor
</Typography>
<Typography component="span" fontSize="inherit" fontWeight="inherit">
Pagespeed monitor
</Typography> </Typography>
</Typography> </Typography>
<ConfigBox> <ConfigBox>
@@ -0,0 +1,315 @@
import PropTypes from "prop-types";
import {
AreaChart,
Area,
XAxis,
Tooltip,
CartesianGrid,
ResponsiveContainer,
Text,
} from "recharts";
import { useTheme } from "@emotion/react";
import { useMemo, useState } from "react";
import { Box, Stack, Typography } from "@mui/material";
import { formatDateWithTz } from "../../../../Utils/timeUtils";
import { useSelector } from "react-redux";
const config = {
seo: {
id: "seo",
text: "SEO",
color: "unresolved",
},
performance: {
id: "performance",
text: "performance",
color: "success",
},
bestPractices: {
id: "bestPractices",
text: "best practices",
color: "warning",
},
accessibility: {
id: "accessibility",
text: "accessibility",
color: "primary",
},
};
/**
* Custom tooltip for the area chart.
* @param {Object} props
* @param {boolean} props.active - Whether the tooltip is active.
* @param {Array} props.payload - The payload data for the tooltip.
* @param {string} props.label - The label for the tooltip.
* @returns {JSX.Element|null} The tooltip element or null if not active.
*/
const CustomToolTip = ({ active, payload, label, config }) => {
const theme = useTheme();
const uiTimezone = useSelector((state) => state.ui.timezone);
if (active && payload && payload.length) {
return (
<Box
sx={{
backgroundColor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.dark,
borderRadius: theme.shape.borderRadius,
py: theme.spacing(2),
px: theme.spacing(4),
}}
>
<Typography
sx={{
color: theme.palette.text.tertiary,
fontSize: 12,
fontWeight: 500,
}}
>
{formatDateWithTz(label, "ddd, MMMM D, YYYY, h:mm A", uiTimezone)}
</Typography>
{Object.keys(config)
.reverse()
.map((key) => {
const { color } = config[key];
const dotColor = theme.palette[color].main;
return (
<Stack
key={`${key}-tooltip`}
direction="row"
alignItems="center"
gap={theme.spacing(3)}
mt={theme.spacing(1)}
sx={{
"& span": {
color: theme.palette.text.tertiary,
fontSize: 11,
fontWeight: 500,
},
}}
>
<Box
width={theme.spacing(4)}
height={theme.spacing(4)}
backgroundColor={dotColor}
sx={{ borderRadius: "50%" }}
/>
<Typography
component="span"
textTransform="capitalize"
sx={{ opacity: 0.8 }}
>
{config[key].text}
</Typography>{" "}
<Typography component="span">
{payload[0].payload[key]}
</Typography>
</Stack>
);
})}
</Box>
);
}
return null;
};
CustomToolTip.propTypes = {
active: PropTypes.bool,
payload: PropTypes.array,
label: PropTypes.string,
config: PropTypes.object,
};
/**
* Processes data to insert gaps with null values based on the interval.
* @param {Array} data
* @param {number} interval - The interval in milliseconds for gaps.
* @returns {Array} The formatted data with gaps.
*/
const processDataWithGaps = (data, interval) => {
if (data.length === 0) return [];
let formattedData = [];
let last = new Date(data[0].createdAt).getTime();
// Helper function to add a null entry
const addNullEntry = (timestamp) => {
formattedData.push({
accessibility: "N/A",
bestPractices: "N/A",
performance: "N/A",
seo: "N/A",
createdAt: timestamp,
});
};
data.forEach((entry) => {
const current = new Date(entry.createdAt).getTime();
if (current - last > interval * 2) {
// Insert null entries for each interval
let temp = last + interval;
while (temp < current) {
addNullEntry(new Date(temp).toISOString());
temp += interval;
}
}
formattedData.push(entry);
last = current;
});
return formattedData;
};
/**
* Custom tick component to render ticks on the XAxis.
*
* @param {Object} props
* @param {number} props.x - The x coordinate for the tick.
* @param {number} props.y - The y coordinate for the tick.
* @param {Object} props.payload - The data object containing the tick value.
* @param {number} props.index - The index of the tick in the array of ticks.
*
* @returns {JSX.Element|null} The tick element or null if the tick should be hidden.
*/
const CustomTick = ({ x, y, payload, index }) => {
const theme = useTheme();
const uiTimezone = useSelector((state) => state.ui.timezone);
// Render nothing for the first tick
if (index === 0) return null;
return (
<Text
x={x}
y={y + 8}
textAnchor="middle"
fill={theme.palette.text.tertiary}
fontSize={11}
fontWeight={400}
>
{formatDateWithTz(payload?.value, "h:mm a", uiTimezone)}
</Text>
);
};
CustomTick.propTypes = {
x: PropTypes.number,
y: PropTypes.number,
payload: PropTypes.shape({
value: PropTypes.string.isRequired,
}),
index: PropTypes.number,
};
/**
* A chart displaying pagespeed details over time.
* @param {Object} props
* @param {Array} props.data - The data to display in the chart.
* @param {number} props.interval - The interval in milliseconds for processing gaps.
* @returns {JSX.Element} The area chart component.
*/
const PagespeedDetailsAreaChart = ({ data, interval, metrics }) => {
const theme = useTheme();
const [isHovered, setIsHovered] = useState(false);
const memoizedData = useMemo(
() => processDataWithGaps(data, interval),
[data[0]]
);
const filteredConfig = Object.keys(config).reduce((result, key) => {
if (metrics[key]) {
result[key] = config[key];
}
return result;
}, {});
return (
<ResponsiveContainer width="100%" minWidth={25} height={215}>
<AreaChart
width="100%"
height="100%"
data={memoizedData}
margin={{ top: 10 }}
onMouseMove={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
<CartesianGrid
stroke={theme.palette.border.light}
strokeWidth={1}
strokeOpacity={1}
fill="transparent"
vertical={false}
/>
<XAxis
stroke={theme.palette.border.dark}
dataKey="createdAt"
tick={<CustomTick />}
axisLine={false}
tickLine={false}
height={18}
minTickGap={0}
interval="equidistantPreserveStart"
/>
<Tooltip
cursor={{ stroke: theme.palette.border.light }}
content={<CustomToolTip config={filteredConfig} />}
/>
<defs>
{Object.values(filteredConfig).map(({ id, color }) => {
const startColor = theme.palette[color].main;
const endColor = theme.palette[color].light;
return (
<linearGradient id={id} x1="0" y1="0" x2="0" y2="1" key={id}>
<stop offset="0%" stopColor={startColor} stopOpacity={0.8} />
<stop offset="100%" stopColor={endColor} stopOpacity={0} />
</linearGradient>
);
})}
</defs>
{Object.keys(filteredConfig).map((key) => {
const { color } = filteredConfig[key];
const strokeColor = theme.palette[color].main;
const bgColor = theme.palette.background.main;
return (
<Area
connectNulls
key={key}
dataKey={key}
stackId={1}
stroke={strokeColor}
strokeWidth={isHovered ? 2.5 : 1.5}
fill={`url(#${filteredConfig[key].id})`}
activeDot={{ stroke: bgColor, fill: strokeColor, r: 4.5 }}
/>
);
})}
</AreaChart>
</ResponsiveContainer>
);
};
PagespeedDetailsAreaChart.propTypes = {
data: PropTypes.arrayOf(
PropTypes.shape({
createdAt: PropTypes.string.isRequired,
accessibility: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
.isRequired,
bestPractices: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
.isRequired,
performance: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
.isRequired,
seo: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
})
).isRequired,
interval: PropTypes.number.isRequired,
metrics: PropTypes.object,
};
export default PagespeedDetailsAreaChart;
@@ -0,0 +1,312 @@
import PropTypes from "prop-types";
import { PieChart as MuiPieChart } from "@mui/x-charts/PieChart";
import { useDrawingArea } from "@mui/x-charts";
import { useState } from "react";
import { useTheme } from "@emotion/react";
import { Box } from "@mui/material";
/**
* Renders a centered label within a pie chart.
*
* @param {Object} props
* @param {string | number} props.value - The value to display in the label.
* @param {string} props.color - The color of the text.
* @returns {JSX.Element}
*/
const PieCenterLabel = ({ value, color, setExpand }) => {
const { width, height } = useDrawingArea();
return (
<g
transform={`translate(${width / 2}, ${height / 2})`}
onMouseEnter={() => setExpand(true)}
>
<circle cx={0} cy={0} r={width / 4} fill="transparent" />
<text
className="pie-label"
style={{
fill: color,
fontSize: 48,
textAnchor: "middle",
dominantBaseline: "central",
userSelect: "none",
}}
>
{value}
</text>
</g>
);
};
PieCenterLabel.propTypes = {
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
color: PropTypes.string,
setExpand: PropTypes.func,
};
/**
* A component that renders a label on a pie chart slice.
* The label is positioned relative to the center of the pie chart and is optionally highlighted.
*
* @param {Object} props
* @param {number} props.value - The value to display inside the pie slice.
* @param {number} props.startAngle - The starting angle of the pie slice in degrees.
* @param {number} props.endAngle - The ending angle of the pie slice in degrees.
* @param {string} props.color - The color of the label text when highlighted.
* @param {boolean} props.highlighted - Determines if the label should be highlighted or not.
* @returns {JSX.Element}
*/
const PieValueLabel = ({ value, startAngle, endAngle, color, highlighted }) => {
const { width, height } = useDrawingArea();
// Compute the midpoint angle in radians
const angle = (((startAngle + endAngle) / 2) * Math.PI) / 180;
const radius = height / 4; // length from center of the circle to where the text is positioned
// Calculate x and y positions
const x = Math.sin(angle) * radius;
const y = -Math.cos(angle) * radius;
return (
<g transform={`translate(${width / 2}, ${height / 2})`}>
<text
className="pie-value-label"
x={x}
y={y}
style={{
fill: highlighted ? color : "rgba(0,0,0,0)",
fontSize: 12,
textAnchor: "middle",
dominantBaseline: "central",
userSelect: "none",
pointerEvents: "none",
}}
>
+{value}
</text>
</g>
);
};
// Validate props using PropTypes
PieValueLabel.propTypes = {
value: PropTypes.number.isRequired,
startAngle: PropTypes.number.isRequired,
endAngle: PropTypes.number.isRequired,
color: PropTypes.string.isRequired,
highlighted: PropTypes.bool.isRequired,
};
const PieChart = ({ audits }) => {
const theme = useTheme();
/**
* Weight constants for different performance metrics.
* @type {Object}
*/
const weights = {
fcp: 10,
si: 10,
lcp: 25,
tbt: 30,
cls: 25,
};
/**
* Retrieves color properties based on the performance value.
*
* @param {number} value - The performance score used to determine the color properties.
* @returns {{stroke: string, strokeBg: string, text: string, bg: string}} The color properties for the given performance value.
*/
const getColors = (value) => {
if (value >= 90 && value <= 100)
return {
stroke: theme.palette.success.main,
strokeBg: theme.palette.success.light,
text: theme.palette.success.text,
bg: theme.palette.success.bg,
};
else if (value >= 50 && value < 90)
return {
stroke: theme.palette.warning.main,
strokeBg: theme.palette.warning.light,
text: theme.palette.warning.text,
bg: theme.palette.warning.bg,
};
else if (value >= 0 && value < 50)
return {
stroke: theme.palette.error.text,
strokeBg: theme.palette.error.light,
text: theme.palette.error.text,
bg: theme.palette.error.bg,
};
return {
stroke: theme.palette.unresolved.main,
strokeBg: theme.palette.unresolved.light,
text: theme.palette.unresolved.main,
bg: theme.palette.unresolved.bg,
};
};
/**
* Calculates and formats the data needed for rendering a pie chart based on audit scores and weights.
* This function generates properties for each pie slice, including angles, radii, and colors.
* It also calculates performance based on the weighted values.
*
* @returns {Array<Object>} An array of objects, each representing the properties for a slice of the pie chart.
* @returns {number} performance - A variable updated with the rounded sum of weighted values.
*/
let performance = 0;
const getPieData = (audits) => {
let data = [];
let startAngle = 0;
const padding = 3; // padding between arcs
const max = 360 - padding * (Object.keys(audits).length - 1); // _id is a child of audits
Object.keys(audits).forEach((key) => {
if (audits[key].score) {
let value = audits[key].score * weights[key];
let endAngle = startAngle + (weights[key] * max) / 100;
let theme = getColors(audits[key].score * 100);
data.push({
id: key,
data: [
{
value: value,
color: theme.stroke,
label: key.toUpperCase(),
},
{
value: weights[key] - value,
color: theme.strokeBg,
label: "",
},
],
arcLabel: (item) => `${item.label}`,
arcLabelRadius: 95,
startAngle: startAngle,
endAngle: endAngle,
innerRadius: 73,
outerRadius: 80,
cornerRadius: 2,
highlightScope: { faded: "global", highlighted: "series" },
faded: {
innerRadius: 73,
outerRadius: 80,
additionalRadius: -20,
arcLabelRadius: 5,
},
cx: pieSize.width / 2,
});
performance += Math.floor(value);
startAngle = endAngle + padding;
}
});
return data;
};
const pieSize = { width: 230, height: 230 };
const pieData = getPieData(audits);
const colorMap = getColors(performance);
const [highlightedItem, setHighLightedItem] = useState(null);
const [expand, setExpand] = useState(false);
return (
<Box onMouseLeave={() => setExpand(false)}>
{expand ? (
<MuiPieChart
series={[
{
data: [
{
value: 100,
color: colorMap.bg,
},
],
outerRadius: 77,
cx: pieSize.width / 2,
},
...pieData,
]}
width={pieSize.width}
height={pieSize.height}
margin={{ left: 0, top: 0, right: 0, bottom: 0 }}
onHighlightChange={setHighLightedItem}
slotProps={{
legend: { hidden: true },
}}
tooltip={{ trigger: "none" }}
sx={{
"&:has(.MuiPieArcLabel-faded) .pie-label": {
fill: "rgba(0,0,0,0) !important",
},
}}
>
<PieCenterLabel
value={performance}
color={colorMap.text}
setExpand={setExpand}
/>
{pieData?.map((pie) => (
<PieValueLabel
key={pie.id}
value={Math.round(pie.data[0].value * 10) / 10}
startAngle={pie.startAngle}
endAngle={pie.endAngle}
color={pie.data[0].color}
highlighted={highlightedItem?.seriesId === pie.id}
/>
))}
</MuiPieChart>
) : (
<MuiPieChart
series={[
{
data: [
{
value: 100,
color: colorMap.bg,
},
],
outerRadius: 77,
cx: pieSize.width / 2,
},
{
data: [
{
value: performance,
color: colorMap.stroke,
},
],
innerRadius: 73,
outerRadius: 80,
paddingAngle: 5,
cornerRadius: 2,
startAngle: 0,
endAngle: (performance / 100) * 360,
cx: pieSize.width / 2,
},
]}
width={pieSize.width}
height={pieSize.height}
margin={{ left: 0, top: 0, right: 0, bottom: 0 }}
tooltip={{ trigger: "none" }}
>
<PieCenterLabel
value={performance}
color={colorMap.text}
setExpand={setExpand}
/>
</MuiPieChart>
)}
</Box>
);
};
PieChart.propTypes = {
audits: PropTypes.object,
};
export default PieChart;
@@ -1,41 +1,7 @@
.page-speed-details h1 {
font-size: var(--env-var-font-size-large-plus);
}
.page-speed-details h2,
.page-speed-details h6 {
font-size: var(--env-var-font-size-large);
}
.page-speed-details h4,
.page-speed-details p,
.page-speed-details p > span {
font-size: var(--env-var-font-size-medium);
}
.page-speed-details h1 + span,
.page-speed-details h4 > span {
font-size: var(--env-var-font-size-small-plus);
}
.page-speed-details h6 {
line-height: 22px;
}
.page-speed-details h1,
.page-speed-details h2,
.page-speed-details h6 {
font-weight: 600;
}
.page-speed-details button.MuiButtonBase-root { .page-speed-details button.MuiButtonBase-root {
height: 34px; height: 34px;
} }
.page-speed-details .stat-box {
flex: 1;
}
.page-speed-details .stat-box:last-of-type {
flex-shrink: 1;
}
.page-speed-details .stat-box svg {
width: 22px;
height: 22px;
}
.page-speed-details .MuiPieArcLabel-root { .page-speed-details .MuiPieArcLabel-root {
font-size: var(--env-var-font-size-small-plus); font-size: var(--env-var-font-size-small-plus);
transition: fill 300ms ease; transition: fill 300ms ease;
@@ -50,8 +16,3 @@
.page-speed-details .MuiPieArc-root { .page-speed-details .MuiPieArc-root {
stroke: inherit; stroke: inherit;
} }
.page-speed-details .metric {
min-width: 200px;
flex: 1;
}
+236 -533
View File
@@ -1,165 +1,45 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { Box, Button, Skeleton, Stack, Typography } from "@mui/material"; import {
import { PieChart } from "@mui/x-charts/PieChart"; Box,
import { useDrawingArea } from "@mui/x-charts"; Button,
Divider,
Stack,
Tooltip,
Typography,
} from "@mui/material";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { import {
formatDuration,
formatDurationRounded, formatDurationRounded,
formatDurationSplit,
} from "../../../Utils/timeUtils"; } from "../../../Utils/timeUtils";
import { ChartBox, IconBox, StatBox } from "./styled";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
import { networkService } from "../../../main"; import { networkService } from "../../../main";
import SkeletonLayout from "./skeleton";
import SettingsIcon from "../../../assets/icons/settings-bold.svg?react"; import SettingsIcon from "../../../assets/icons/settings-bold.svg?react";
import LastCheckedIcon from "../../../assets/icons/calendar-check.svg?react"; import SpedometerIcon from "../../../assets/icons/spedometer-icon.svg?react";
import ClockIcon from "../../../assets/icons/maintenance.svg?react"; import MetricsIcon from "../../../assets/icons/ruler-icon.svg?react";
import IntervalCheckIcon from "../../../assets/icons/interval-check.svg?react"; import ScoreIcon from "../../../assets/icons/monitor-graph-line.svg?react";
import PageSpeedLineChart from "../../../Components/Charts/PagespeedLineChart"; import PerformanceIcon from "../../../assets/icons/performance-report.svg?react";
import Breadcrumbs from "../../../Components/Breadcrumbs"; import Breadcrumbs from "../../../Components/Breadcrumbs";
import PulseDot from "../../../Components/Animated/PulseDot"; import PulseDot from "../../../Components/Animated/PulseDot";
import "./index.css"; import PagespeedDetailsAreaChart from "./Charts/AreaChart";
import Checkbox from "../../../Components/Inputs/Checkbox";
import PieChart from "./Charts/PieChart";
import useUtils from "../../Monitors/utils"; import useUtils from "../../Monitors/utils";
import SkeletonLayout from "./skeleton"; import "./index.css";
const StatBox = ({ icon, title, value }) => {
const theme = useTheme();
return (
<Stack
className="stat-box"
direction="row"
gap={theme.spacing(4)}
pt={theme.spacing(8)}
px={theme.spacing(8)}
pb={theme.spacing(10)}
border={1}
borderColor={theme.palette.border.light}
borderRadius={theme.shape.borderRadius}
backgroundColor={theme.palette.background.main}
minWidth="200px"
>
{icon}
<Box>
<Typography
variant="h6"
color={theme.palette.primary.main}
mb={theme.spacing(6)}
>
{title}
</Typography>
<Typography variant="h4" color={theme.palette.text.secondary}>
{value}
</Typography>
</Box>
</Stack>
);
};
StatBox.propTypes = {
icon: PropTypes.element,
title: PropTypes.string,
value: PropTypes.node,
};
/**
* Renders a centered label within a pie chart.
*
* @param {Object} props
* @param {string | number} props.value - The value to display in the label.
* @param {string} props.color - The color of the text.
* @returns {JSX.Element}
*/
const PieCenterLabel = ({ value, color, setExpand }) => {
const { width, height } = useDrawingArea();
return (
<g
transform={`translate(${width / 2}, ${height / 2})`}
onMouseEnter={() => setExpand(true)}
>
<circle cx={0} cy={0} r={width / 3} fill="transparent" />
<text
className="pie-label"
style={{
fill: color,
fontSize: "45px",
textAnchor: "middle",
dominantBaseline: "central",
userSelect: "none",
}}
>
{value}
</text>
</g>
);
};
PieCenterLabel.propTypes = {
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
color: PropTypes.string,
setExpand: PropTypes.func,
};
/**
* A component that renders a label on a pie chart slice.
* The label is positioned relative to the center of the pie chart and is optionally highlighted.
*
* @param {Object} props
* @param {number} props.value - The value to display inside the pie slice.
* @param {number} props.startAngle - The starting angle of the pie slice in degrees.
* @param {number} props.endAngle - The ending angle of the pie slice in degrees.
* @param {string} props.color - The color of the label text when highlighted.
* @param {boolean} props.highlighted - Determines if the label should be highlighted or not.
* @returns {JSX.Element}
*/
const PieValueLabel = ({ value, startAngle, endAngle, color, highlighted }) => {
const { width, height } = useDrawingArea();
// Compute the midpoint angle in radians
const angle = (((startAngle + endAngle) / 2) * Math.PI) / 180;
const radius = height / 3.5; // length from center of the circle to where the text is positioned
// Calculate x and y positions
const x = Math.sin(angle) * radius;
const y = -Math.cos(angle) * radius;
return (
<g transform={`translate(${width / 2}, ${height / 2})`}>
<text
className="pie-value-label"
x={x}
y={y}
style={{
fill: highlighted ? color : "rgba(0,0,0,0)",
fontSize: "12px",
textAnchor: "middle",
dominantBaseline: "central",
userSelect: "none",
}}
>
+{value}
</text>
</g>
);
};
PieValueLabel.propTypes = {
value: PropTypes.number,
startAngle: PropTypes.number,
endAngle: PropTypes.number,
color: PropTypes.string,
highlighted: PropTypes.bool,
};
const PageSpeedDetails = () => { const PageSpeedDetails = () => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const { statusColor, pagespeedStatusMsg, determineState } = useUtils();
const [monitor, setMonitor] = useState({}); const [monitor, setMonitor] = useState({});
const [audits, setAudits] = useState({}); const [audits, setAudits] = useState({});
const { monitorId } = useParams(); const { monitorId } = useParams();
const { authToken } = useSelector((state) => state.auth); const { authToken } = useSelector((state) => state.auth);
const { determineState, statusColor, pagespeedStatusMsg } = useUtils();
useEffect(() => { useEffect(() => {
const fetchMonitor = async () => { const fetchMonitor = async () => {
@@ -184,138 +64,31 @@ const PageSpeedDetails = () => {
fetchMonitor(); fetchMonitor();
}, [monitorId, authToken, navigate]); }, [monitorId, authToken, navigate]);
/**
* Weight constants for different performance metrics.
* @type {Object}
*/
const weights = {
fcp: 10,
si: 10,
lcp: 25,
tbt: 30,
cls: 25,
};
/**
* Retrieves color properties based on the performance value.
*
* @param {number} value - The performance score used to determine the color properties.
* @returns {{stroke: string, text: string, bg: string}} The color properties for the given performance value.
*/
const getColors = (value) => {
if (value >= 90 && value <= 100)
return {
stroke: theme.palette.success.main,
strokeBg: theme.palette.success.light,
text: theme.palette.success.text,
bg: theme.palette.success.bg,
shape: "circle",
};
else if (value >= 50 && value < 90)
return {
stroke: theme.palette.warning.main,
strokeBg: theme.palette.warning.bg,
text: theme.palette.warning.text,
bg: theme.palette.warning.light,
shape: "square",
};
else if (value >= 0 && value < 50)
return {
stroke: theme.palette.error.text,
strokeBg: theme.palette.error.light,
text: theme.palette.error.text,
bg: theme.palette.error.bg,
shape: "circle",
};
return {
stroke: theme.palette.unresolved.main,
strokeBg: theme.palette.unresolved.light,
text: theme.palette.unresolved.main,
bg: theme.palette.unresolved.bg,
shape: "",
};
};
/**
* Calculates and formats the data needed for rendering a pie chart based on audit scores and weights.
* This function generates properties for each pie slice, including angles, radii, and colors.
* It also calculates performance based on the weighted values.
*
* @returns {Array<Object>} An array of objects, each representing the properties for a slice of the pie chart.
* @returns {number} performance - A variable updated with the rounded sum of weighted values.
*/
let performance = 0;
const getPieData = (audits) => {
let props = [];
let startAngle = 0;
const padding = 3; // padding between arcs
const max = 360 - padding * (Object.keys(audits).length - 1); // _id is a child of audits
Object.keys(audits).forEach((key) => {
if (audits[key].score) {
let value = audits[key].score * weights[key];
let endAngle = startAngle + (weights[key] * max) / 100;
let theme = getColors(audits[key].score * 100);
props.push({
id: key,
data: [
{
value: value,
color: theme.stroke,
label: key.toUpperCase(),
},
{
value: weights[key] - value,
color: theme.strokeBg,
label: "",
},
],
arcLabel: (item) => `${item.label}`,
arcLabelRadius: 95,
startAngle: startAngle,
endAngle: endAngle,
innerRadius: 73,
outerRadius: 80,
cornerRadius: 2,
highlightScope: { faded: "global", highlighted: "series" },
faded: {
innerRadius: 63,
outerRadius: 70,
additionalRadius: -20,
arcLabelRadius: 5,
},
cx: pieSize.width / 2,
});
performance += Math.round(value);
startAngle = endAngle + padding;
}
});
return props;
};
const pieSize = { width: 210, height: 200 };
const pieData = getPieData(audits);
const colorMap = getColors(performance);
const [highlightedItem, setHighLightedItem] = useState(null);
const [expand, setExpand] = useState(false);
let loading = Object.keys(monitor).length === 0; let loading = Object.keys(monitor).length === 0;
const data = monitor?.checks ? [...monitor.checks].reverse() : []; const data = monitor?.checks ? [...monitor.checks].reverse() : [];
let sharedStyles = { const splitDuration = (duration) => {
border: 1, const { time, format } = formatDurationSplit(duration);
borderColor: theme.palette.border.light, return (
borderRadius: theme.shape.borderRadius, <>
backgroundColor: theme.palette.background.main, {time}
<Typography component="span">{format}</Typography>
</>
);
};
const [metrics, setMetrics] = useState({
accessibility: true,
bestPractices: true,
performance: true,
seo: true,
});
const handleMetrics = (id) => {
setMetrics((prev) => ({ ...prev, [id]: !prev[id] }));
}; };
const monitorState = determineState(monitor);
return ( return (
<Stack className="page-speed-details" gap={theme.spacing(12)}> <Stack className="page-speed-details" gap={theme.spacing(10)}>
{loading ? ( {loading ? (
<SkeletonLayout /> <SkeletonLayout />
) : ( ) : (
@@ -327,19 +100,62 @@ const PageSpeedDetails = () => {
]} ]}
/> />
<Stack direction="row" gap={theme.spacing(2)}> <Stack direction="row" gap={theme.spacing(2)}>
<PulseDot color={statusColor[monitorState]} />
<Box> <Box>
<Typography <Typography component="h1" variant="h1">
component="h1" {monitor.name}
mb={theme.spacing(2)} </Typography>
color={theme.palette.text.primary} <Stack
sx={{ lineHeight: 1 }} direction="row"
alignItems="center"
height="fit-content"
gap={theme.spacing(2)}
> >
{monitor?.url} <Tooltip
</Typography> title={pagespeedStatusMsg[determineState(monitor)]}
<Typography component="span" color={statusColor[monitorState]}> disableInteractive
{pagespeedStatusMsg[monitorState] || "Pending..."} slotProps={{
</Typography> popper: {
modifiers: [
{
name: "offset",
options: {
offset: [0, -8],
},
},
],
},
}}
>
<Box>
<PulseDot color={statusColor[determineState(monitor)]} />
</Box>
</Tooltip>
<Typography component="h2" variant="h2">
{monitor?.url}
</Typography>
<Typography
position="relative"
variant="body2"
mt={theme.spacing(1)}
ml={theme.spacing(6)}
sx={{
"&:before": {
position: "absolute",
content: `""`,
width: 4,
height: 4,
borderRadius: "50%",
backgroundColor: theme.palette.text.tertiary,
opacity: 0.8,
left: -9,
top: "50%",
transform: "translateY(-50%)",
},
}}
>
Checking every {formatDurationRounded(monitor?.interval)}.
</Typography>
</Stack>
</Box> </Box>
<Button <Button
variant="contained" variant="contained"
@@ -361,275 +177,161 @@ const PageSpeedDetails = () => {
Configure Configure
</Button> </Button>
</Stack> </Stack>
<Stack <Stack direction="row" gap={theme.spacing(8)}>
direction="row" <StatBox>
justifyContent="space-between" <Typography component="h2">checks since</Typography>
gap={theme.spacing(12)} <Typography>
flexWrap="wrap" {splitDuration(monitor?.uptimeDuration)}
> <Typography component="span">ago</Typography>
<StatBox </Typography>
icon={<LastCheckedIcon />} </StatBox>
title="Last checked" <StatBox>
value={ <Typography component="h2">last check</Typography>
<> <Typography>
{formatDuration(monitor?.lastChecked)}{" "} {splitDuration(monitor?.lastChecked)}
<Typography <Typography component="span">ago</Typography>
component="span" </Typography>
fontStyle="italic" </StatBox>
sx={{ opacity: 0.8 }}
>
ago
</Typography>
</>
}
/>
<StatBox
icon={<ClockIcon />}
title="Checks since"
value={
<>
{formatDuration(monitor?.uptimeDuration)}{" "}
<Typography
component="span"
fontStyle="italic"
sx={{ opacity: 0.8 }}
>
ago
</Typography>
</>
}
></StatBox>
<StatBox
icon={<IntervalCheckIcon />}
title="Checks every"
value={formatDurationRounded(monitor?.interval)}
></StatBox>
</Stack> </Stack>
<Typography component="h2" color={theme.palette.text.secondary}> <Box>
Score history <Typography variant="body2" my={theme.spacing(8)}>
</Typography> Showing statistics for past 24 hours.
<Box </Typography>
height="300px" <ChartBox sx={{ gridTemplateColumns: "75% 25%" }}>
sx={{ <Stack direction="row" alignItems="center" gap={theme.spacing(6)}>
...sharedStyles, <IconBox>
}} <ScoreIcon />
> </IconBox>
<PageSpeedLineChart pageSpeedChecks={data} /> <Typography component="h2">Score history</Typography>
</Stack>
<Box>
<PagespeedDetailsAreaChart
data={data}
interval={monitor?.interval}
metrics={metrics}
/>
</Box>
<Box>
<Stack
direction="row"
alignItems="center"
gap={theme.spacing(6)}
>
<IconBox>
<MetricsIcon />
</IconBox>
<Typography component="h2">Metrics</Typography>
</Stack>
<Stack
gap={theme.spacing(4)}
mt={theme.spacing(16)}
sx={{
"& label": { pl: theme.spacing(6) },
}}
>
<Box>
<Typography fontSize={11} fontWeight={500}>
Shown
</Typography>
<Divider sx={{ mt: theme.spacing(2) }} />
</Box>
<Checkbox
id="accessibility-toggle"
label="Accessibility"
isChecked={metrics.accessibility}
onChange={() => handleMetrics("accessibility")}
/>
<Divider />
<Checkbox
id="best-practices-toggle"
label="Best Practices"
isChecked={metrics.bestPractices}
onChange={() => handleMetrics("bestPractices")}
/>
<Divider />
<Checkbox
id="performance-toggle"
label="Performance"
isChecked={metrics.performance}
onChange={() => handleMetrics("performance")}
/>
<Divider />
<Checkbox
id="seo-toggle"
label="Search Engine Optimization"
isChecked={metrics.seo}
onChange={() => handleMetrics("seo")}
/>
<Divider />
</Stack>
</Box>
</ChartBox>
</Box> </Box>
<Typography component="h2" color={theme.palette.text.secondary}> <ChartBox
Performance report
</Typography>
<Stack
direction="row"
alignItems="center"
overflow="hidden"
flex={1} flex={1}
sx={{ sx={{ gridTemplateColumns: "50% 50%", gridTemplateRows: "15% 85%" }}
"& p": {
color: theme.palette.text.secondary,
},
...sharedStyles,
}}
> >
<Stack direction="row" alignItems="center" gap={theme.spacing(6)}>
<IconBox>
<PerformanceIcon />
</IconBox>
<Typography component="h2">Performance report</Typography>
</Stack>
<Stack <Stack
alignItems="center" alignItems="center"
textAlign="center" textAlign="center"
minWidth="300px" minWidth="300px"
flex={1} flex={1}
px={theme.spacing(20)} pt={theme.spacing(6)}
py={theme.spacing(8)} pb={theme.spacing(12)}
> >
<Box onMouseLeave={() => setExpand(false)}> <PieChart audits={audits} />
{expand ? ( <Typography variant="body1" mt="auto">
<PieChart
series={[
{
data: [
{
value: 100,
color: colorMap.bg,
},
],
outerRadius: 67,
cx: pieSize.width / 2,
},
...pieData,
]}
width={pieSize.width}
height={pieSize.height}
margin={{ left: 0, top: 0, right: 0, bottom: 0 }}
onHighlightChange={setHighLightedItem}
slotProps={{
legend: { hidden: true },
}}
tooltip={{ trigger: "none" }}
sx={{
"&:has(.MuiPieArcLabel-faded) .pie-label": {
fill: "rgba(0,0,0,0) !important",
},
}}
>
<PieCenterLabel
value={performance}
color={colorMap.text}
setExpand={setExpand}
/>
{pieData?.map((pie) => (
<PieValueLabel
key={pie.id}
value={Math.round(pie.data[0].value * 10) / 10}
startAngle={pie.startAngle}
endAngle={pie.endAngle}
color={pie.data[0].color}
highlighted={highlightedItem?.seriesId === pie.id}
/>
))}
</PieChart>
) : (
<PieChart
series={[
{
data: [
{
value: 100,
color: colorMap.bg,
},
],
outerRadius: 67,
cx: pieSize.width / 2,
},
{
data: [
{
value: performance,
color: colorMap.stroke,
},
],
innerRadius: 63,
outerRadius: 70,
paddingAngle: 5,
cornerRadius: 2,
startAngle: 0,
endAngle: (performance / 100) * 360,
cx: pieSize.width / 2,
},
]}
width={pieSize.width}
height={pieSize.height}
margin={{ left: 0, top: 0, right: 0, bottom: 0 }}
tooltip={{ trigger: "none" }}
>
<PieCenterLabel
value={performance}
color={colorMap.text}
setExpand={setExpand}
/>
</PieChart>
)}
</Box>
<Typography mt={theme.spacing(6)}>
Values are estimated and may vary.{" "} Values are estimated and may vary.{" "}
<Typography <Typography
component="span" component="span"
fontSize="inherit"
sx={{ sx={{
color: theme.palette.primary.main, color: theme.palette.primary.main,
fontWeight: 500, fontWeight: 500,
textDecoration: "underline", textDecoration: "underline",
textUnderlineOffset: 2,
transition: "all 200ms",
cursor: "pointer", cursor: "pointer",
"&:hover": {
textUnderlineOffset: 4,
},
}} }}
> >
See calculator See calculator
</Typography> </Typography>
</Typography> </Typography>
</Stack> </Stack>
<Box <Box px={theme.spacing(20)} py={theme.spacing(8)} height="100%">
px={theme.spacing(20)} <Stack direction="row" alignItems="center" gap={theme.spacing(6)}>
py={theme.spacing(8)} <IconBox>
height="100%" <SpedometerIcon />
flex={1} </IconBox>
sx={{ <Typography component="h2">Performance Metrics</Typography>
borderLeft: 1, </Stack>
borderLeftColor: theme.palette.border.light,
}}
>
<Typography
mb={theme.spacing(6)}
pb={theme.spacing(8)}
color={theme.palette.text.secondary}
textAlign="center"
sx={{
borderBottom: 1,
borderBottomColor: theme.palette.border.light,
borderBottomStyle: "dashed",
}}
>
The{" "}
<Typography
component="span"
sx={{
color: theme.palette.primary.main,
fontWeight: 500,
textDecoration: "underline",
cursor: "pointer",
}}
>
performance score is calculated
</Typography>{" "}
directly from these{" "}
<Typography component="span" fontWeight={600}>
metrics
</Typography>
.
</Typography>
<Stack <Stack
direction="row"
flexWrap="wrap" flexWrap="wrap"
pt={theme.spacing(8)} mt={theme.spacing(4)}
gap={theme.spacing(8)} gap={theme.spacing(4)}
> >
{Object.keys(audits).map((key) => { {Object.keys(audits).map((key) => {
if (key === "_id") return; if (key === "_id") return;
let audit = audits[key]; let audit = audits[key];
let metricParams = getColors(audit.score * 100); let score = audit.score * 100;
let bg =
let shape = ( score >= 90
<Box ? theme.palette.success.main
sx={{ : score >= 50
width: theme.spacing(6), ? theme.palette.warning.main
height: theme.spacing(6), : score >= 0
borderRadius: "50%", ? theme.palette.error.text
backgroundColor: metricParams.stroke, : theme.palette.unresolved.main;
}}
></Box>
);
if (metricParams.shape === "square")
shape = (
<Box
sx={{
width: theme.spacing(6),
height: theme.spacing(6),
backgroundColor: metricParams.stroke,
}}
></Box>
);
else if (metricParams.shape === "triangle")
shape = (
<Box
sx={{
width: 0,
height: 0,
ml: `calc((${theme.spacing(6)} - ${theme.spacing(
4
)}) / -2)`,
borderLeft: `${theme.spacing(4)} solid transparent`,
borderRight: `${theme.spacing(4)} solid transparent`,
borderBottom: `${theme.spacing(6)} solid ${
metricParams.stroke
}`,
}}
></Box>
);
// Find the position where the number ends and the unit begins // Find the position where the number ends and the unit begins
const match = audit.displayValue.match( const match = audit.displayValue.match(
@@ -639,50 +341,51 @@ const PageSpeedDetails = () => {
let unit; let unit;
if (match) { if (match) {
value = match[1]; value = match[1];
unit = match[2]; match[2] === "s" ? (unit = "seconds") : (unit = match[2]);
} else { } else {
value = audit.displayValue; value = audit.displayValue;
} }
return ( return (
<Stack <Stack
className="metric"
key={`${key}-box`} key={`${key}-box`}
justifyContent="space-between"
direction="row" direction="row"
gap={theme.spacing(4)} gap={theme.spacing(4)}
p={theme.spacing(3)}
border={1}
borderColor={theme.palette.border.light}
borderRadius={4}
> >
{shape}
<Box> <Box>
<Typography sx={{ lineHeight: 1 }}> <Typography
fontSize={12}
fontWeight={500}
lineHeight={1}
mb={1}
textTransform="uppercase"
>
{audit.title} {audit.title}
</Typography> </Typography>
<Typography <Typography
component="span" component="span"
sx={{ fontSize={14}
color: metricParams.text, fontWeight={500}
fontSize: "16px", color={theme.palette.text.primary}
fontWeight: 600,
}}
> >
{value} {value}
<Typography <Typography component="span" variant="body2" ml={2}>
component="span"
ml="2px"
sx={{
color: theme.palette.text.secondary,
fontSize: 13,
}}
>
{unit} {unit}
</Typography> </Typography>
</Typography> </Typography>
</Box> </Box>
<Box width={4} backgroundColor={bg} borderRadius={4} />
</Stack> </Stack>
); );
})} })}
</Stack> </Stack>
</Box> </Box>
</Stack> </ChartBox>
</> </>
)} )}
</Stack> </Stack>
@@ -1,5 +1,4 @@
import { Box, Skeleton, Stack } from "@mui/material"; import { Box, Skeleton, Stack } from "@mui/material";
import { useTheme } from "@emotion/react";
/** /**
* Renders a skeleton layout. * Renders a skeleton layout.
@@ -7,21 +6,14 @@ import { useTheme } from "@emotion/react";
* @returns {JSX.Element} * @returns {JSX.Element}
*/ */
const SkeletonLayout = () => { const SkeletonLayout = () => {
const theme = useTheme();
return ( return (
<> <>
<Skeleton variant="rounded" width="15%" height={34} /> <Skeleton variant="rounded" width="15%" height={34} />
<Stack direction="row" gap={theme.spacing(4)}> <Stack direction="row" gap={4}>
<Skeleton variant="circular" style={{ minWidth: 24, minHeight: 24 }} /> <Skeleton variant="circular" style={{ minWidth: 24, minHeight: 24 }} />
<Box width="85%"> <Box width="85%">
<Skeleton variant="rounded" width="50%" height={24} /> <Skeleton variant="rounded" width="50%" height={24} />
<Skeleton <Skeleton variant="rounded" width="50%" height={18} sx={{ mt: 4 }} />
variant="rounded"
width="50%"
height={18}
sx={{ mt: theme.spacing(4) }}
/>
</Box> </Box>
<Skeleton <Skeleton
variant="rounded" variant="rounded"
@@ -33,7 +25,7 @@ const SkeletonLayout = () => {
<Stack <Stack
direction="row" direction="row"
justifyContent="space-between" justifyContent="space-between"
gap={theme.spacing(20)} gap={20}
flexWrap="wrap" flexWrap="wrap"
> >
<Skeleton variant="rounded" width="30%" height={90} sx={{ flex: 1 }} /> <Skeleton variant="rounded" width="30%" height={90} sx={{ flex: 1 }} />
@@ -0,0 +1,93 @@
import { Box, Stack, styled } from "@mui/material";
export const ChartBox = styled(Stack)(({ theme }) => ({
display: "grid",
height: 300,
minWidth: 250,
border: 1,
borderStyle: "solid",
borderColor: theme.palette.border.light,
borderRadius: 4,
borderTopRightRadius: 16,
borderBottomRightRadius: 16,
backgroundColor: theme.palette.background.main,
"& h2": {
color: theme.palette.text.secondary,
fontSize: 15,
fontWeight: 500,
},
"& p": { color: theme.palette.text.tertiary },
"& > :nth-of-type(1)": {
gridColumn: 1,
gridRow: 1,
height: "fit-content",
paddingTop: theme.spacing(8),
paddingLeft: theme.spacing(8),
},
"& > :nth-of-type(2)": { gridColumn: 1, gridRow: 2 },
"& > :nth-of-type(3)": {
gridColumn: 2,
gridRow: "span 2",
padding: theme.spacing(8),
borderLeft: 1,
borderLeftStyle: "solid",
borderLeftColor: theme.palette.border.light,
borderRadius: 16,
backgroundColor: theme.palette.background.main,
background: `linear-gradient(325deg, ${theme.palette.background.accent} 20%, ${theme.palette.background.main} 45%)`,
},
"& path": {
transition: "stroke-width 400ms ease",
},
}));
export const IconBox = styled(Box)(({ theme }) => ({
height: 34,
minWidth: 34,
width: 34,
position: "relative",
border: 1,
borderStyle: "solid",
borderColor: theme.palette.border.dark,
borderRadius: 4,
backgroundColor: theme.palette.background.accent,
"& svg": {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 20,
height: 20,
"& path": {
stroke: theme.palette.text.tertiary,
},
},
}));
export const StatBox = styled(Box)(({ theme }) => ({
padding: `${theme.spacing(4)} ${theme.spacing(8)}`,
minWidth: 200,
width: 225,
border: 1,
borderStyle: "solid",
borderColor: theme.palette.border.light,
borderRadius: 4,
backgroundColor: theme.palette.background.main,
background: `linear-gradient(340deg, ${theme.palette.background.accent} 20%, ${theme.palette.background.main} 45%)`,
"& h2": {
fontSize: 13,
fontWeight: 500,
color: theme.palette.text.secondary,
textTransform: "uppercase",
},
"& p": {
fontSize: 18,
color: theme.palette.text.primary,
marginTop: theme.spacing(2),
"& span": {
color: theme.palette.text.tertiary,
marginLeft: theme.spacing(2),
fontSize: 15,
},
},
}));
+283 -46
View File
@@ -1,32 +1,220 @@
import { getLastChecked } from "../../Utils/monitorUtils"; import PropTypes from "prop-types";
import { formatDate, formatDurationRounded } from "../../Utils/timeUtils";
import PageSpeedIcon from "../../assets/icons/page-speed.svg?react"; import PageSpeedIcon from "../../assets/icons/page-speed.svg?react";
import { StatusLabel } from "../../Components/Label"; import { StatusLabel } from "../../Components/Label";
import { Box, Grid, Stack, Typography } from "@mui/material"; import { Box, Grid, Stack, Typography } from "@mui/material";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { IconBox } from "./Details/styled";
import {
Area,
AreaChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
} from "recharts";
import { useSelector } from "react-redux";
import { formatDateWithTz, formatDurationSplit } from "../../Utils/timeUtils";
import useUtils from "../Monitors/utils"; import useUtils from "../Monitors/utils";
import PropTypes from "prop-types"; import { useState } from "react";
/**
* CustomToolTip displays a tooltip with formatted date and score information.
* @param {Object} props
* @param {Array} props.payload - Data to display in the tooltip
* @returns {JSX.Element} The rendered tooltip component
*/
const CustomToolTip = ({ payload }) => {
const theme = useTheme();
const uiTimezone = useSelector((state) => state.ui.timezone);
return (
<Box
sx={{
backgroundColor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.dark,
borderRadius: theme.shape.borderRadius,
py: theme.spacing(2),
px: theme.spacing(4),
}}
>
<Typography
sx={{
color: theme.palette.text.tertiary,
fontSize: 12,
fontWeight: 500,
}}
>
{formatDateWithTz(
payload[0]?.payload.createdAt,
"ddd, MMMM D, YYYY, h:mm A",
uiTimezone
)}
</Typography>
<Stack
direction="row"
alignItems="center"
gap={theme.spacing(3)}
mt={theme.spacing(1)}
sx={{
"& span": {
color: theme.palette.text.tertiary,
fontSize: 11,
fontWeight: 500,
},
}}
>
<Box
width={theme.spacing(4)}
height={theme.spacing(4)}
backgroundColor={payload[0]?.color}
sx={{ borderRadius: "50%" }}
/>
<Typography
component="span"
textTransform="capitalize"
sx={{ opacity: 0.8 }}
>
{payload[0]?.name}
</Typography>{" "}
<Typography component="span">{payload[0]?.payload.score}</Typography>
</Stack>
</Box>
);
};
CustomToolTip.propTypes = {
payload: PropTypes.array,
};
/**
* Processes the raw data to include a score for each entry.
* @param {Array<Object>} data - The raw data array.
* @returns {Array<Object>} - The formatted data array with scores.
*/
const processData = (data) => {
if (data.length === 0) return [];
let formattedData = [];
const calculateScore = (entry) => {
return (
(entry.accessibility +
entry.bestPractices +
entry.performance +
entry.seo) /
4
);
};
data.forEach((entry) => {
entry = { ...entry, score: calculateScore(entry) };
formattedData.push(entry);
});
return formattedData;
};
/**
* Renders an area chart displaying page speed scores.
* @param {Object} props
* @param {Array<Object>} props.data - The raw data to be displayed in the chart.
* @param {string} props.status - The status of the page speed which determines the chart's color scheme.
* @returns {JSX.Element} - The rendered area chart.
*/
const PagespeedAreaChart = ({ data, status }) => {
const theme = useTheme();
const [isHovered, setIsHovered] = useState(false);
const { pagespeedStyles } = useUtils();
const formattedData = processData(data);
return (
<ResponsiveContainer width="100%" minWidth={25} height={85}>
<AreaChart
width="100%"
height="100%"
data={formattedData}
margin={{ top: 10, bottom: -5 }}
style={{ cursor: "pointer" }}
onMouseMove={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
<CartesianGrid
stroke={theme.palette.border.light}
strokeWidth={1}
strokeOpacity={1}
fill="transparent"
vertical={false}
/>
<Tooltip
cursor={{ stroke: theme.palette.border.light }}
content={<CustomToolTip />}
/>
<defs>
<linearGradient
id={`pagespeed-chart-${status}`}
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop
offset="0%"
stopColor={pagespeedStyles[status].stroke}
stopOpacity={0.8}
/>
<stop
offset="100%"
stopColor={pagespeedStyles[status].light}
stopOpacity={0}
/>
</linearGradient>
</defs>
<Area
dataKey="score"
stroke={pagespeedStyles[status].stroke}
strokeWidth={isHovered ? 2.5 : 1.5}
fill={`url(#pagespeed-chart-${status})`}
activeDot={{
stroke: pagespeedStyles[status].light,
fill: pagespeedStyles[status].stroke,
r: 4.5,
}}
/>
</AreaChart>
</ResponsiveContainer>
);
};
PagespeedAreaChart.propTypes = {
data: PropTypes.arrayOf(
PropTypes.shape({
accessibility: PropTypes.number.isRequired,
bestPractices: PropTypes.number.isRequired,
performance: PropTypes.number.isRequired,
seo: PropTypes.number.isRequired,
})
).isRequired,
status: PropTypes.string.isRequired,
};
/**
* Renders a card displaying monitor details and an area chart.
* @param {Object} props
* @param {Object} props.monitor - The monitor data to be displayed in the card.
* @returns {JSX.Element} - The rendered card.
*/
const Card = ({ monitor }) => { const Card = ({ monitor }) => {
const { determineState, pagespeedStatusMsg } = useUtils(); const { determineState, pagespeedStatusMsg } = useUtils();
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const monitorState = determineState(monitor); const monitorState = determineState(monitor);
return ( return (
<Grid <Grid item lg={6} flexGrow={1}>
item <Box
lg={6} position="relative"
flexGrow={1}
sx={{
"&:hover > .MuiStack-root": {
backgroundColor: theme.palette.background.accent,
},
}}
>
<Stack
direction="row"
gap={theme.spacing(6)}
p={theme.spacing(8)} p={theme.spacing(8)}
onClick={() => navigate(`/pagespeed/${monitor._id}`)} onClick={() => navigate(`/pagespeed/${monitor._id}`)}
border={1} border={1}
@@ -34,42 +222,91 @@ const Card = ({ monitor }) => {
borderRadius={theme.shape.borderRadius} borderRadius={theme.shape.borderRadius}
backgroundColor={theme.palette.background.main} backgroundColor={theme.palette.background.main}
sx={{ sx={{
display: "grid",
gridTemplateColumns: "34px 2fr 1fr",
columnGap: theme.spacing(5),
gridTemplateRows: "34px 1fr 3fr",
cursor: "pointer", cursor: "pointer",
"& svg path": { stroke: theme.palette.other.icon, strokeWidth: 0.8 }, "&:hover": {
backgroundColor: theme.palette.background.accent,
},
"& path": {
transition: "stroke-width 400ms ease",
},
}} }}
> >
<PageSpeedIcon <IconBox>
style={{ width: theme.spacing(8), height: theme.spacing(8) }} <PageSpeedIcon />
</IconBox>
<Typography
component="h2"
variant="h2"
fontWeight={500}
alignSelf="center"
>
{monitor.name}
</Typography>
<StatusLabel
status={monitorState}
text={pagespeedStatusMsg[monitorState] || "Pending..."}
customStyles={{
width: "max-content",
textTransform: "capitalize",
alignSelf: "flex-start",
justifySelf: "flex-end",
}}
/> />
<Box flex={1}> <Typography
<Stack direction="row" justifyContent="space-between"> variant="body2"
<Typography mt={theme.spacing(-2)}
component="h2" sx={{ gridColumnStart: 2 }}
mb={theme.spacing(2)} >
color={theme.palette.primary.main} {monitor.url}
> </Typography>
{monitor.name} <Box
</Typography> mx={theme.spacing(-8)}
<StatusLabel mt={theme.spacing(4)}
status={monitorState} mb={theme.spacing(-8)}
text={pagespeedStatusMsg[monitorState] || "Pending..."} sx={{ gridColumnStart: 1, gridColumnEnd: 4 }}
customStyles={{ textTransform: "capitalize" }} >
/> <PagespeedAreaChart data={monitor.checks} status={monitorState} />
</Stack> </Box>
<Typography fontSize={13}> <Box
{monitor.url.replace(/^https?:\/\//, "")} position="absolute"
</Typography> bottom={0}
<Typography mt={theme.spacing(12)}> py={theme.spacing(1)}
<Typography component="span" fontWeight={600}> px={theme.spacing(4)}
Last checked:{" "} borderTop={1}
</Typography> borderRight={1}
{formatDate(getLastChecked(monitor.checks, false))}{" "} borderColor={theme.palette.border.light}
<Typography component="span" fontStyle="italic"> backgroundColor={theme.palette.background.accent}
({formatDurationRounded(getLastChecked(monitor.checks))} ago) sx={{
</Typography> pointerEvents: "none",
userSelect: "none",
borderTopRightRadius: 8,
borderBottomLeftRadius: 4,
}}
>
<Typography fontSize={11} color={theme.palette.text.accent}>
Checking every{" "}
{(() => {
const { time, format } = formatDurationSplit(monitor?.interval);
return (
<>
<Typography
component="span"
fontSize={12}
color={theme.palette.text.primary}
>
{time}{" "}
</Typography>
{format}
</>
);
})()}
</Typography> </Typography>
</Box> </Box>
</Stack> </Box>
</Grid> </Grid>
); );
}; };
+1 -15
View File
@@ -1,20 +1,6 @@
.page-speed h2.MuiTypography-root {
line-height: 1.1;
}
.page-speed:not(:has([class*="fallback__"])) h1.MuiTypography-root {
font-size: var(--env-var-font-size-large-plus);
}
.page-speed h2.MuiTypography-root {
font-size: var(--env-var-font-size-large);
font-weight: 600;
}
.page-speed p:has(> span.MuiTypography-root),
.page-speed p.MuiTypography-root > span.MuiTypography-root {
font-size: var(--env-var-font-size-small-plus);
}
.page-speed .label { .page-speed .label {
padding: 7px; padding: 7px;
height: 22px; height: 24px;
font-size: var(--env-var-font-size-small); font-size: var(--env-var-font-size-small);
} }
.page-speed:not(:has([class*="fallback__"])) button { .page-speed:not(:has([class*="fallback__"])) button {
+41 -16
View File
@@ -1,5 +1,5 @@
import { Box, Button, Grid, Stack } from "@mui/material"; import { Box, Button, Grid, Stack } from "@mui/material";
import { useEffect } from "react"; import { useEffect, useState } from "react";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { getPageSpeedByTeamId } from "../../Features/PageSpeedMonitor/pageSpeedMonitorSlice"; import { getPageSpeedByTeamId } from "../../Features/PageSpeedMonitor/pageSpeedMonitorSlice";
@@ -11,24 +11,54 @@ import Breadcrumbs from "../../Components/Breadcrumbs";
import Greeting from "../../Utils/greeting"; import Greeting from "../../Utils/greeting";
import SkeletonLayout from "./skeleton"; import SkeletonLayout from "./skeleton";
import Card from "./card"; import Card from "./card";
import { networkService } from "../../main";
const PageSpeed = ({ isAdmin }) => { const PageSpeed = ({ isAdmin }) => {
const theme = useTheme(); const theme = useTheme();
const dispatch = useDispatch(); const dispatch = useDispatch();
const navigate = useNavigate(); const navigate = useNavigate();
const { authToken } = useSelector((state) => state.auth); const { user, authToken } = useSelector((state) => state.auth);
const { monitorsSummary, isLoading } = useSelector( const [isLoading, setIsLoading] = useState(false);
(state) => state.pageSpeedMonitors const [monitors, setMonitors] = useState([]);
);
useEffect(() => { useEffect(() => {
dispatch(getPageSpeedByTeamId(authToken)); dispatch(getPageSpeedByTeamId(authToken));
}, [authToken, dispatch]); }, [authToken, dispatch]);
useEffect(() => {
const fetchMonitors = async () => {
try {
setIsLoading(true);
const res = await networkService.getMonitorsByTeamId({
authToken: authToken,
teamId: user.teamId,
limit: 10,
types: ["pagespeed"],
status: null,
checkOrder: "desc",
normalize: true,
page: null,
rowsPerPage: null,
filter: null,
field: null,
order: null,
});
if (res?.data?.data?.monitors) {
setMonitors(res.data.data.monitors);
}
} catch (error) {
console.log(error);
} finally {
setIsLoading(false);
}
};
fetchMonitors();
}, []);
// will show skeletons only on initial load // will show skeletons only on initial load
// since monitor state is being added to redux persist, there's no reason to display skeletons on every render // since monitor state is being added to redux persist, there's no reason to display skeletons on every render
let isActuallyLoading = isLoading && monitorsSummary?.monitors?.length === 0; let isActuallyLoading = isLoading && monitors?.length === 0;
return ( return (
<Box <Box
className="page-speed" className="page-speed"
@@ -46,14 +76,8 @@ const PageSpeed = ({ isAdmin }) => {
> >
{isActuallyLoading ? ( {isActuallyLoading ? (
<SkeletonLayout /> <SkeletonLayout />
) : monitorsSummary?.monitors?.length !== 0 ? ( ) : monitors?.length !== 0 ? (
<Box <Box>
sx={{
"& p": {
color: theme.palette.text.secondary,
},
}}
>
<Box mb={theme.spacing(12)}> <Box mb={theme.spacing(12)}>
<Breadcrumbs list={[{ name: `pagespeed`, path: "/pagespeed" }]} /> <Breadcrumbs list={[{ name: `pagespeed`, path: "/pagespeed" }]} />
<Stack <Stack
@@ -67,13 +91,14 @@ const PageSpeed = ({ isAdmin }) => {
variant="contained" variant="contained"
color="primary" color="primary"
onClick={() => navigate("/pagespeed/create")} onClick={() => navigate("/pagespeed/create")}
sx={{ whiteSpace: "nowrap" }}
> >
Create new Create new
</Button> </Button>
</Stack> </Stack>
</Box> </Box>
<Grid container spacing={theme.spacing(12)}> <Grid container spacing={theme.spacing(12)}>
{monitorsSummary?.monitors?.map((monitor) => ( {monitors?.map((monitor) => (
<Card monitor={monitor} key={monitor._id} /> <Card monitor={monitor} key={monitor._id} />
))} ))}
</Grid> </Grid>
+159 -51
View File
@@ -1,5 +1,5 @@
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { Box, Button, Stack, styled, Typography } from "@mui/material"; import { Box, Stack, Typography } from "@mui/material";
import Field from "../../Components/Inputs/Field"; import Field from "../../Components/Inputs/Field";
import Link from "../../Components/Link"; import Link from "../../Components/Link";
import Select from "../../Components/Inputs/Select"; import Select from "../../Components/Inputs/Select";
@@ -7,17 +7,97 @@ import { logger } from "../../Utils/Logger";
import "./index.css"; import "./index.css";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { createToast } from "../../Utils/toastUtils"; import { createToast } from "../../Utils/toastUtils";
import { deleteMonitorChecksByTeamId } from "../../Features/UptimeMonitors/uptimeMonitorsSlice"; import {
deleteMonitorChecksByTeamId,
addDemoMonitors,
deleteAllMonitors,
} from "../../Features/UptimeMonitors/uptimeMonitorsSlice";
import { update } from "../../Features/Auth/authSlice";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import { setTimezone } from "../../Features/UI/uiSlice";
import timezones from "../../Utils/timezones.json";
import { useState } from "react";
import { ConfigBox } from "./styled";
import { networkService } from "../../main";
import { settingsValidation } from "../../Validation/validation";
const SECONDS_PER_DAY = 86400;
const Settings = ({ isAdmin }) => { const Settings = ({ isAdmin }) => {
const theme = useTheme(); const theme = useTheme();
const { user, authToken } = useSelector((state) => state.auth); const { user, authToken } = useSelector((state) => state.auth);
const { checkTTL } = user;
const { isLoading } = useSelector((state) => state.uptimeMonitors); const { isLoading } = useSelector((state) => state.uptimeMonitors);
const { isLoading: authIsLoading } = useSelector((state) => state.auth);
const { timezone } = useSelector((state) => state.ui);
const [checksIsLoading, setChecksIsLoading] = useState(false);
const [form, setForm] = useState({
ttl: (checkTTL / SECONDS_PER_DAY).toString(),
});
const [errors, setErrors] = useState({});
const dispatch = useDispatch(); const dispatch = useDispatch();
const handleChange = (event) => {
const { value, id } = event.target;
const { error } = settingsValidation.validate(
{ [id]: value },
{
abortEarly: false,
}
);
if (!error || error.details.length === 0) {
setErrors({});
} else {
const newErrors = {};
error.details.forEach((err) => {
newErrors[err.path[0]] = err.message;
});
setErrors(newErrors);
console.log(newErrors);
logger.error("Validation errors:", error.details);
}
let inputValue = value;
id === "ttl" && (inputValue = value.replace(/[^0-9]/g, ""));
setForm((prev) => ({
...prev,
[id]: inputValue,
}));
};
// TODO Handle saving // TODO Handle saving
const handleSave = async () => {
try {
setChecksIsLoading(true);
await networkService.updateChecksTTL(authToken, form.ttl);
const updatedUser = { ...user, checkTTL: form.ttl };
const action = await dispatch(
update({ authToken, localData: updatedUser })
);
if (action.payload.success) {
createToast({
body: "Settings saved successfully",
});
} else {
if (action.payload) {
// dispatch errors
createToast({
body: action.payload.msg,
});
} else {
// unknown errors
createToast({
body: "Unknown error.",
});
}
}
} catch (error) {
console.log(error);
createToast({ body: "Failed to save settings" });
} finally {
setChecksIsLoading(false);
}
};
const handleClearStats = async () => { const handleClearStats = async () => {
try { try {
@@ -36,32 +116,33 @@ const Settings = ({ isAdmin }) => {
} }
}; };
const ConfigBox = styled("div")({ const handleInsertDemoMonitors = async () => {
display: "flex", try {
flexDirection: "row", const action = await dispatch(addDemoMonitors({ authToken }));
justifyContent: "space-between", if (addDemoMonitors.fulfilled.match(action)) {
gap: theme.spacing(20), createToast({ body: "Successfully added demo monitors" });
paddingTop: theme.spacing(12), } else {
paddingInline: theme.spacing(15), createToast({ body: "Failed to add demo monitors" });
paddingBottom: theme.spacing(25), }
backgroundColor: theme.palette.background.main, } catch (error) {
border: 1, logger.error(error);
borderStyle: "solid", createToast({ Body: "Failed to add demo monitors" });
borderColor: theme.palette.border.light, }
borderRadius: theme.spacing(2), };
"& > div:first-of-type": {
flex: 0.7, const handleDeleteAllMonitors = async () => {
}, try {
"& > div:last-of-type": { const action = await dispatch(deleteAllMonitors({ authToken }));
flex: 1, if (deleteAllMonitors.fulfilled.match(action)) {
}, createToast({ body: "Successfully deleted all monitors" });
"& h1, & h2": { } else {
color: theme.palette.text.secondary, createToast({ body: "Failed to add demo monitors" });
}, }
"& p": { } catch (error) {
color: theme.palette.text.tertiary, logger.error(error);
}, createToast({ Body: "Failed to delete all monitors" });
}); }
};
return ( return (
<Box <Box
@@ -83,25 +164,16 @@ const Settings = ({ isAdmin }) => {
<Typography component="span">Display timezone</Typography>- The <Typography component="span">Display timezone</Typography>- The
timezone of the dashboard you publicly display. timezone of the dashboard you publicly display.
</Typography> </Typography>
<Typography>
<Typography component="span">Server timezone</Typography>- The
timezone of your server.
</Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
<Select <Select
id="display-timezone" id="display-timezone"
label="Display timezone" label="Display timezone"
value="est" value={timezone}
onChange={() => logger.warn("disabled")} onChange={(e) => {
items={[{ _id: "est", name: "America / Toronto" }]} dispatch(setTimezone({ timezone: e.target.value }));
/> }}
<Select items={timezones}
id="server-timezone"
label="Server timezone"
value="est"
onChange={() => logger.warn("disabled")}
items={[{ _id: "est", name: "America / Toronto" }]}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
@@ -116,21 +188,19 @@ const Settings = ({ isAdmin }) => {
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
<Field <Field
type="text" id="ttl"
id="history-monitoring"
label="The days you want to keep monitoring history." label="The days you want to keep monitoring history."
isOptional={true}
optionalLabel="0 for infinite" optionalLabel="0 for infinite"
placeholder="90" value={form.ttl}
value="" onChange={handleChange}
onChange={() => logger.warn("Disabled")} error={errors.ttl}
/> />
<Box> <Box>
<Typography>Clear all stats. This is irreversible.</Typography> <Typography>Clear all stats. This is irreversible.</Typography>
<LoadingButton <LoadingButton
variant="contained" variant="contained"
color="error" color="error"
loading={isLoading} loading={isLoading || authIsLoading || checksIsLoading}
onClick={handleClearStats} onClick={handleClearStats}
sx={{ mt: theme.spacing(4) }} sx={{ mt: theme.spacing(4) }}
> >
@@ -140,6 +210,42 @@ const Settings = ({ isAdmin }) => {
</Stack> </Stack>
</ConfigBox> </ConfigBox>
)} )}
{isAdmin && (
<ConfigBox>
<Box>
<Typography component="h1">Demo Monitors</Typography>
<Typography sx={{ mt: theme.spacing(2) }}>
Here you can add and remove demo monitors
</Typography>
</Box>
<Stack gap={theme.spacing(20)}>
<Box>
<Typography>Add demo monitors</Typography>
<LoadingButton
variant="contained"
color="primary"
loading={isLoading || authIsLoading || checksIsLoading}
onClick={handleInsertDemoMonitors}
sx={{ mt: theme.spacing(4) }}
>
Add demo monitors
</LoadingButton>
</Box>
<Box>
<Typography>Remove all monitors</Typography>
<LoadingButton
variant="contained"
color="error"
loading={isLoading || authIsLoading || checksIsLoading}
onClick={handleDeleteAllMonitors}
sx={{ mt: theme.spacing(4) }}
>
Remove all monitors
</LoadingButton>
</Box>
</Stack>
</ConfigBox>
)}
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography component="h1">About</Typography> <Typography component="h1">About</Typography>
@@ -160,10 +266,12 @@ const Settings = ({ isAdmin }) => {
</ConfigBox> </ConfigBox>
<Stack direction="row" justifyContent="flex-end"> <Stack direction="row" justifyContent="flex-end">
<LoadingButton <LoadingButton
loading={false} loading={isLoading || authIsLoading || checksIsLoading}
disabled={Object.keys(errors).length > 0}
variant="contained" variant="contained"
color="primary" color="primary"
sx={{ px: theme.spacing(12), mt: theme.spacing(20) }} sx={{ px: theme.spacing(12), mt: theme.spacing(20) }}
onClick={handleSave}
> >
Save Save
</LoadingButton> </LoadingButton>
+28
View File
@@ -0,0 +1,28 @@
import { Stack, styled } from "@mui/material";
export const ConfigBox = styled(Stack)(({ theme }) => ({
display: "flex",
flexDirection: "row",
justifyContent: "space-between",
gap: theme.spacing(20),
paddingTop: theme.spacing(12),
paddingInline: theme.spacing(15),
paddingBottom: theme.spacing(25),
backgroundColor: theme.palette.background.main,
border: 1,
borderStyle: "solid",
borderColor: theme.palette.border.light,
borderRadius: theme.spacing(2),
"& > div:first-of-type": {
flex: 0.7,
},
"& > div:last-of-type": {
flex: 1,
},
"& h1, & h2": {
color: theme.palette.text.secondary,
},
"& p": {
color: theme.palette.text.tertiary,
},
}));
+86 -19
View File
@@ -83,26 +83,37 @@ class NetworkService {
* ************************************ * ************************************
* *
* @async * @async
* @param {string} authToken - The authorization token to be used in the request header. * @param {Object} config - The configuration object.
* @param {string} userId - The ID of the user whose monitors are to be retrieved. * @param {string} config.authToken - The authorization token to be used in the request header.
* @param {number} [limit] - The maximum number of monitors to retrieve. * @param {string} config.teamId - The ID of the team whose monitors are to be retrieved.
* @param {Array<string>} [types] - The types of monitors to retrieve. * @param {number} [config.limit] - The maximum number of monitors to retrieve.
* @param {string} [status] - The status of the monitors to retrieve. * @param {Array<string>} [config.types] - The types of monitors to retrieve.
* @param {string} [sortOrder] - The order in which to sort the retrieved monitors. * @param {string} [config.status] - The status of the monitors to retrieve.
* @param {boolean} [normalize] - Whether to normalize the retrieved monitors. * @param {string} [config.checkOrder] - The order in which to sort the retrieved monitors.
* @param {boolean} [config.normalize] - Whether to normalize the retrieved monitors.
* @param {number} [config.page] - The page number for pagination.
* @param {number} [config.rowsPerPage] - The number of rows per page for pagination.
* @param {string} [config.filter] - The filter to apply to the monitors.
* @param {string} [config.field] - The field to sort by.
* @param {string} [config.order] - The order in which to sort the field.
* @returns {Promise<AxiosResponse>} The response from the axios GET request. * @returns {Promise<AxiosResponse>} The response from the axios GET request.
*/ */
async getMonitorsByTeamId( async getMonitorsByTeamId(config) {
authToken, const {
teamId, authToken,
limit, teamId,
types, limit,
status, types,
sortOrder, status,
normalize, checkOrder,
page, normalize,
rowsPerPage page,
) { rowsPerPage,
filter,
field,
order,
} = config;
const params = new URLSearchParams(); const params = new URLSearchParams();
if (limit) params.append("limit", limit); if (limit) params.append("limit", limit);
@@ -112,10 +123,13 @@ class NetworkService {
}); });
} }
if (status) params.append("status", status); if (status) params.append("status", status);
if (sortOrder) params.append("sortOrder", sortOrder); if (checkOrder) params.append("checkOrder", checkOrder);
if (normalize) params.append("normalize", normalize); if (normalize) params.append("normalize", normalize);
if (page) params.append("page", page); if (page) params.append("page", page);
if (rowsPerPage) params.append("rowsPerPage", rowsPerPage); if (rowsPerPage) params.append("rowsPerPage", rowsPerPage);
if (filter) params.append("filter", filter);
if (field) params.append("field", field);
if (order) params.append("order", order);
return this.axiosInstance.get( return this.axiosInstance.get(
`/monitors/team/${teamId}?${params.toString()}`, `/monitors/team/${teamId}?${params.toString()}`,
@@ -274,6 +288,46 @@ class NetworkService {
); );
} }
/**
* ************************************
* Adds demo monitors
* ************************************
*
* @async
* @param {string} authToken - The authorization token to be used in the request header.
* @returns {Promise<AxiosResponse>} The response from the axios POST request.
*/
async addDemoMonitors(authToken) {
return this.axiosInstance.post(
`/monitors/demo`,
{},
{
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
}
);
}
/**
* ************************************
* Deletes all monitors for a team by team ID
* ************************************
*
* @async
* @param {string} authToken - The authorization token to be used in the request header.
* @returns {Promise<AxiosResponse>} The response from the axios DELETE request.
*/
async deleteAllMonitors(authToken) {
return this.axiosInstance.delete(`/monitors/`, {
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
});
}
/** /**
* ************************************ * ************************************
* Gets the certificate expiry for a monitor * Gets the certificate expiry for a monitor
@@ -542,6 +596,19 @@ class NetworkService {
} }
); );
} }
async updateChecksTTL(authToken, ttl) {
return this.axiosInstance.put(
`/checks/ttl`,
{ ttl },
{
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
}
);
}
} }
export default NetworkService; export default NetworkService;
+10 -2
View File
@@ -21,7 +21,14 @@ const shadow =
"0px 4px 24px -4px rgba(255, 255, 255, 0.03), 0px 3px 3px -3px rgba(255, 255, 255, 0.01)"; "0px 4px 24px -4px rgba(255, 255, 255, 0.03), 0px 3px 3px -3px rgba(255, 255, 255, 0.01)";
const darkTheme = createTheme({ const darkTheme = createTheme({
typography: { fontFamily: fontFamilyDefault, fontSize: 13 }, typography: {
fontFamily: fontFamilyDefault,
fontSize: 13,
h1: { fontSize: 22, color: text.primary, fontWeight: 500 },
h2: { fontSize: 14.5, color: text.secondary, fontWeight: 400 },
body1: { fontSize: 13, color: text.tertiary, fontWeight: 400 },
body2: { fontSize: 12, color: text.tertiary, fontWeight: 400 },
},
palette: { palette: {
mode: "dark", mode: "dark",
primary: { main: "#1570ef" }, primary: { main: "#1570ef" },
@@ -63,13 +70,14 @@ const darkTheme = createTheme({
uptimeGood: "#ffd600", uptimeGood: "#ffd600",
uptimeExcellent: "#079455", uptimeExcellent: "#079455",
}, },
unresolved: { main: "#4e5ba6", light: "#e2eaf7", bg: "#f2f4f7" }, unresolved: { main: "#664eff", light: "#3a1bff", bg: "#f2f4f7" },
divider: border.light, divider: border.light,
other: { other: {
icon: "#e6e6e6", icon: "#e6e6e6",
line: "#27272a", line: "#27272a",
fill: "#18181a", fill: "#18181a",
grid: "#454546", grid: "#454546",
autofill: "#2d2d33",
}, },
}, },
spacing: 2, spacing: 2,
+12 -3
View File
@@ -20,7 +20,14 @@ const shadow =
"0px 4px 24px -4px rgba(16, 24, 40, 0.08), 0px 3px 3px -3px rgba(16, 24, 40, 0.03)"; "0px 4px 24px -4px rgba(16, 24, 40, 0.08), 0px 3px 3px -3px rgba(16, 24, 40, 0.03)";
const lightTheme = createTheme({ const lightTheme = createTheme({
typography: { fontFamily: fontFamilyDefault, fontSize: 13 }, typography: {
fontFamily: fontFamilyDefault,
fontSize: 13,
h1: { fontSize: 22, color: text.primary, fontWeight: 500 },
h2: { fontSize: 14.5, color: text.secondary, fontWeight: 400 },
body1: { fontSize: 13, color: text.tertiary, fontWeight: 400 },
body2: { fontSize: 12, color: text.tertiary, fontWeight: 400 },
},
palette: { palette: {
primary: { main: "#1570EF" }, primary: { main: "#1570EF" },
secondary: { main: "#F4F4F4", dark: "#e3e3e3", contrastText: "#475467" }, secondary: { main: "#F4F4F4", dark: "#e3e3e3", contrastText: "#475467" },
@@ -51,7 +58,7 @@ const lightTheme = createTheme({
text: "#DC6803", text: "#DC6803",
main: "#fdb022", main: "#fdb022",
light: "#ffecbc", light: "#ffecbc",
bg: "#fffcf5", bg: "#fef8ea",
border: "#fec84b", border: "#fec84b",
}, },
percentage: { percentage: {
@@ -67,6 +74,7 @@ const lightTheme = createTheme({
line: "#d6d9dd", line: "#d6d9dd",
fill: "#e3e3e3", fill: "#e3e3e3",
grid: "#a2a3a3", grid: "#a2a3a3",
autofill: "#e8f0fe",
}, },
}, },
spacing: 2, spacing: 2,
@@ -143,12 +151,14 @@ const lightTheme = createTheme({
styleOverrides: { styleOverrides: {
root: { root: {
marginTop: 4, marginTop: 4,
padding: 0,
border: 1, border: 1,
borderStyle: "solid", borderStyle: "solid",
borderColor: border.light, borderColor: border.light,
borderRadius: 4, borderRadius: 4,
boxShadow: shadow, boxShadow: shadow,
backgroundColor: background.main, backgroundColor: background.main,
backgroundImage: "none",
}, },
}, },
}, },
@@ -175,7 +185,6 @@ const lightTheme = createTheme({
color: text.secondary, color: text.secondary,
fontSize: 13, fontSize: 13,
margin: 2, margin: 2,
marginBottom: 0,
minWidth: 100, minWidth: 100,
"&:hover, &.Mui-selected, &.Mui-selected:hover, &.Mui-selected.Mui-focusVisible": "&:hover, &.Mui-selected, &.Mui-selected:hover, &.Mui-selected.Mui-focusVisible":
{ {
+18
View File
@@ -0,0 +1,18 @@
import { useState, useEffect } from "react";
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
};
export default useDebounce;
+6 -16
View File
@@ -155,30 +155,20 @@ const Greeting = ({ type = "" }) => {
return ( return (
<Box> <Box>
<Typography <Typography component="h1" variant="h1" mb={theme.spacing(1)}>
component="h1" <Typography component="span" fontSize="inherit">
lineHeight={1} {prepend},{" "}
fontWeight={500} </Typography>
color={theme.palette.text.primary}
mb={theme.spacing(1)}
>
<Typography <Typography
component="span" component="span"
fontSize="inherit" fontSize="inherit"
fontWeight="inherit"
color={theme.palette.text.secondary} color={theme.palette.text.secondary}
> >
{prepend},{" "}
</Typography>
<Typography component="span" fontSize="inherit" fontWeight="inherit">
{firstName} {emoji} {firstName} {emoji}
</Typography> </Typography>
</Typography> </Typography>
<Typography <Typography variant="h2" lineHeight={1} color={theme.palette.text.accent}>
lineHeight={1}
fontSize={14}
fontWeight={400}
color={theme.palette.text.accent}
>
{append} — Here’s an overview of your {type} monitors. {append} — Here’s an overview of your {type} monitors.
</Typography> </Typography>
</Box> </Box>
+11
View File
@@ -1,3 +1,9 @@
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
dayjs.extend(utc);
dayjs.extend(timezone);
export const formatDuration = (ms) => { export const formatDuration = (ms) => {
const seconds = Math.floor(ms / 1000); const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60); const minutes = Math.floor(seconds / 60);
@@ -76,3 +82,8 @@ export const formatDate = (date, customOptions) => {
.toLocaleString("en-US", options) .toLocaleString("en-US", options)
.replace(/\b(AM|PM)\b/g, (match) => match.toLowerCase()); .replace(/\b(AM|PM)\b/g, (match) => match.toLowerCase());
}; };
export const formatDateWithTz = (timestamp, format, timezone) => {
const formattedDate = dayjs(timestamp, timezone).tz(timezone).format(format);
return formattedDate;
};
File diff suppressed because it is too large. Load diff
+7
View File
@@ -146,9 +146,16 @@ const maintenanceWindowValidation = joi.object({
}), }),
}); });
const settingsValidation = joi.object({
ttl: joi.number().required().messages({
"string.empty": "TTL is required",
}),
});
export { export {
credentials, credentials,
imageValidation, imageValidation,
monitorValidation, monitorValidation,
maintenanceWindowValidation, maintenanceWindowValidation,
settingsValidation,
}; };
@@ -0,0 +1,19 @@
<svg width="250" height="176" viewBox="0 0 250 176" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M246 72.5H4C2.067 72.5 0.5 74.067 0.5 76V100C0.5 101.933 2.067 103.5 4 103.5H246C247.933 103.5 249.5 101.933 249.5 100V76C249.5 74.067 247.933 72.5 246 72.5Z" fill="white" stroke="#E1E1E1"/>
<path d="M112.5 81H42.5C38.3579 81 35 84.3579 35 88.5C35 92.6421 38.3579 96 42.5 96H112.5C116.642 96 120 92.6421 120 88.5C120 84.3579 116.642 81 112.5 81Z" fill="#F1F1F1"/>
<path d="M25 88.5C25 84.3579 21.6421 81 17.5 81C13.3579 81 10 84.3579 10 88.5C10 92.6421 13.3579 96 17.5 96C21.6421 96 25 92.6421 25 88.5Z" fill="#F1F1F1"/>
<path d="M219 34H31C28.7909 34 27 35.7909 27 38V56C27 58.2091 28.7909 60 31 60H219C221.209 60 223 58.2091 223 56V38C223 35.7909 221.209 34 219 34Z" fill="white"/>
<path d="M219 34.5H31C29.067 34.5 27.5 36.067 27.5 38V56C27.5 57.933 29.067 59.5 31 59.5H219C220.933 59.5 222.5 57.933 222.5 56V38C222.5 36.067 220.933 34.5 219 34.5Z" stroke="#E1E1E1" stroke-opacity="0.71"/>
<path d="M156.5 42H60.5C57.4624 42 55 44.4624 55 47.5C55 50.5376 57.4624 53 60.5 53H156.5C159.538 53 162 50.5376 162 47.5C162 44.4624 159.538 42 156.5 42Z" fill="#F4F4F4"/>
<path d="M41.5 42H40.5C37.4624 42 35 44.4624 35 47.5C35 50.5376 37.4624 53 40.5 53H41.5C44.5376 53 47 50.5376 47 47.5C47 44.4624 44.5376 42 41.5 42Z" fill="#F4F4F4"/>
<path d="M219 116H31C28.7909 116 27 117.791 27 120V138C27 140.209 28.7909 142 31 142H219C221.209 142 223 140.209 223 138V120C223 117.791 221.209 116 219 116Z" fill="white"/>
<path d="M219 116.5H31C29.067 116.5 27.5 118.067 27.5 120V138C27.5 139.933 29.067 141.5 31 141.5H219C220.933 141.5 222.5 139.933 222.5 138V120C222.5 118.067 220.933 116.5 219 116.5Z" stroke="#E1E1E1" stroke-opacity="0.71"/>
<path d="M156.5 124H60.5C57.4624 124 55 126.462 55 129.5C55 132.538 57.4624 135 60.5 135H156.5C159.538 135 162 132.538 162 129.5C162 126.462 159.538 124 156.5 124Z" fill="#F4F4F4"/>
<path d="M41.5 124H40.5C37.4624 124 35 126.462 35 129.5C35 132.538 37.4624 135 40.5 135H41.5C44.5376 135 47 132.538 47 129.5C47 126.462 44.5376 124 41.5 124Z" fill="#F4F4F4"/>
<path d="M176 0.5H59C57.067 0.5 55.5 2.067 55.5 4V18C55.5 19.933 57.067 21.5 59 21.5H176C177.933 21.5 179.5 19.933 179.5 18V4C179.5 2.067 177.933 0.5 176 0.5Z" fill="white" stroke="#F6F6F6"/>
<path d="M136.5 7H77.5C75.0147 7 73 9.01472 73 11.5C73 13.9853 75.0147 16 77.5 16H136.5C138.985 16 141 13.9853 141 11.5C141 9.01472 138.985 7 136.5 7Z" fill="#F6F6F6"/>
<path d="M68 11C68 8.79086 66.2091 7 64 7C61.7909 7 60 8.79086 60 11V12C60 14.2091 61.7909 16 64 16C66.2091 16 68 14.2091 68 12V11Z" fill="#F6F6F6"/>
<path d="M176 154.5H59C57.067 154.5 55.5 156.067 55.5 158V172C55.5 173.933 57.067 175.5 59 175.5H176C177.933 175.5 179.5 173.933 179.5 172V158C179.5 156.067 177.933 154.5 176 154.5Z" fill="white" stroke="#F6F6F6"/>
<path d="M136.5 161H77.5C75.0147 161 73 163.015 73 165.5C73 167.985 75.0147 170 77.5 170H136.5C138.985 170 141 167.985 141 165.5C141 163.015 138.985 161 136.5 161Z" fill="#F6F6F6"/>
<path d="M68 165C68 162.791 66.2091 161 64 161C61.7909 161 60 162.791 60 165V166C60 168.209 61.7909 170 64 170C66.2091 170 68 168.209 68 166V165Z" fill="#F6F6F6"/>
</svg>

After

Width:  |  Height:  |  Size: 3.1 KiB

@@ -0,0 +1,19 @@
<svg width="250" height="176" viewBox="0 0 250 176" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M246 72.5H4C2.067 72.5 0.5 74.067 0.5 76V100C0.5 101.933 2.067 103.5 4 103.5H246C247.933 103.5 249.5 101.933 249.5 100V76C249.5 74.067 247.933 72.5 246 72.5Z" fill="#151518" stroke="#1F1F23"/>
<path d="M112.5 81H42.5C38.3579 81 35 84.3579 35 88.5C35 92.6421 38.3579 96 42.5 96H112.5C116.642 96 120 92.6421 120 88.5C120 84.3579 116.642 81 112.5 81Z" fill="#1F1F23"/>
<path d="M25 88.5C25 84.3579 21.6421 81 17.5 81C13.3579 81 10 84.3579 10 88.5C10 92.6421 13.3579 96 17.5 96C21.6421 96 25 92.6421 25 88.5Z" fill="#1F1F23"/>
<path d="M219 34H31C28.7909 34 27 35.7909 27 38V56C27 58.2091 28.7909 60 31 60H219C221.209 60 223 58.2091 223 56V38C223 35.7909 221.209 34 219 34Z" fill="#151518"/>
<path d="M219 34.5H31C29.067 34.5 27.5 36.067 27.5 38V56C27.5 57.933 29.067 59.5 31 59.5H219C220.933 59.5 222.5 57.933 222.5 56V38C222.5 36.067 220.933 34.5 219 34.5Z" stroke="#1F1F23" stroke-opacity="0.71"/>
<path d="M156.5 42H60.5C57.4624 42 55 44.4624 55 47.5C55 50.5376 57.4624 53 60.5 53H156.5C159.538 53 162 50.5376 162 47.5C162 44.4624 159.538 42 156.5 42Z" fill="#252529"/>
<path d="M41.5 42H40.5C37.4624 42 35 44.4624 35 47.5C35 50.5376 37.4624 53 40.5 53H41.5C44.5376 53 47 50.5376 47 47.5C47 44.4624 44.5376 42 41.5 42Z" fill="#252529"/>
<path d="M219 116H31C28.7909 116 27 117.791 27 120V138C27 140.209 28.7909 142 31 142H219C221.209 142 223 140.209 223 138V120C223 117.791 221.209 116 219 116Z" fill="#151518"/>
<path d="M219 116.5H31C29.067 116.5 27.5 118.067 27.5 120V138C27.5 139.933 29.067 141.5 31 141.5H219C220.933 141.5 222.5 139.933 222.5 138V120C222.5 118.067 220.933 116.5 219 116.5Z" stroke="#1F1F23" stroke-opacity="0.71"/>
<path d="M156.5 124H60.5C57.4624 124 55 126.462 55 129.5C55 132.538 57.4624 135 60.5 135H156.5C159.538 135 162 132.538 162 129.5C162 126.462 159.538 124 156.5 124Z" fill="#252529"/>
<path d="M41.5 124H40.5C37.4624 124 35 126.462 35 129.5C35 132.538 37.4624 135 40.5 135H41.5C44.5376 135 47 132.538 47 129.5C47 126.462 44.5376 124 41.5 124Z" fill="#252529"/>
<path d="M176 0.5H59C57.067 0.5 55.5 2.067 55.5 4V18C55.5 19.933 57.067 21.5 59 21.5H176C177.933 21.5 179.5 19.933 179.5 18V4C179.5 2.067 177.933 0.5 176 0.5Z" fill="#151518" stroke="#202023"/>
<path d="M136.5 7H77.5C75.0147 7 73 9.01472 73 11.5C73 13.9853 75.0147 16 77.5 16H136.5C138.985 16 141 13.9853 141 11.5C141 9.01472 138.985 7 136.5 7Z" fill="#202023"/>
<path d="M68 11C68 8.79086 66.2091 7 64 7C61.7909 7 60 8.79086 60 11V12C60 14.2091 61.7909 16 64 16C66.2091 16 68 14.2091 68 12V11Z" fill="#202023"/>
<path d="M176 154.5H59C57.067 154.5 55.5 156.067 55.5 158V172C55.5 173.933 57.067 175.5 59 175.5H176C177.933 175.5 179.5 173.933 179.5 172V158C179.5 156.067 177.933 154.5 176 154.5Z" fill="#151518" stroke="#202023"/>
<path d="M136.5 161H77.5C75.0147 161 73 163.015 73 165.5C73 167.985 75.0147 170 77.5 170H136.5C138.985 170 141 167.985 141 165.5C141 163.015 138.985 161 136.5 161Z" fill="#202023"/>
<path d="M68 165C68 162.791 66.2091 161 64 161C61.7909 161 60 162.791 60 165V166C60 168.209 61.7909 170 64 170C66.2091 170 68 168.209 68 166V165Z" fill="#202023"/>
</svg>

After

Width:  |  Height:  |  Size: 3.1 KiB

File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,3 +1,3 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M21 10H3M21 12.5V8.8C21 7.11984 21 6.27976 20.673 5.63803C20.3854 5.07354 19.9265 4.6146 19.362 4.32698C18.7202 4 17.8802 4 16.2 4H7.8C6.11984 4 5.27976 4 4.63803 4.32698C4.07354 4.6146 3.6146 5.07354 3.32698 5.63803C3 6.27976 3 7.11984 3 8.8V17.2C3 18.8802 3 19.7202 3.32698 20.362C3.6146 20.9265 4.07354 21.3854 4.63803 21.673C5.27976 22 6.11984 22 7.8 22H12M16 2V6M8 2V6M14.5 19L16.5 21L21 16.5" stroke="black" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/> <path d="M6.5 20H5C3.89543 20 3 19.1046 3 18V4C3 2.89543 3.89543 2 5 2H19C20.1046 2 21 2.89543 21 4V18C21 19.1046 20.1046 20 19 20H17.5M12 19C13.6569 19 15 17.6569 15 16C15 14.3431 13.6569 13 12 13C10.3431 13 9 14.3431 9 16C9 17.6569 10.3431 19 12 19ZM12 19L12.0214 18.9998L8.82867 22.1926L6.00024 19.3641L9.01965 16.3447M12 19L15.1928 22.1926L18.0212 19.3641L15.0018 16.3447M9 6H15M7 9.5H17" stroke="#475466" stroke-width="1" stroke-linecap="round" stroke-linejoin="round"/>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 594 B

After

Width:  |  Height:  |  Size: 578 B

@@ -0,0 +1,3 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M22 12H18L15 21L9 3L6 12H2" stroke="black" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 223 B

@@ -0,0 +1,3 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9 18L2 22V6L9 2M9 18L16 22M9 18V2M16 22L22 18V2L16 6M16 22V6M16 6L9 2" stroke="black" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 267 B

+3
View File
@@ -0,0 +1,3 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14.5 5.50001L16 7.00001M11.5 8.50001L13 10M8.49996 11.5L9.99996 13M5.49996 14.5L6.99996 16M2.56561 17.5657L6.43424 21.4344C6.63225 21.6324 6.73125 21.7314 6.84542 21.7685C6.94584 21.8011 7.05401 21.8011 7.15443 21.7685C7.2686 21.7314 7.3676 21.6324 7.56561 21.4344L21.4342 7.56573C21.6322 7.36772 21.7313 7.26872 21.7683 7.15455C21.801 7.05413 21.801 6.94596 21.7683 6.84554C21.7313 6.73137 21.6322 6.63237 21.4342 6.43436L17.5656 2.56573C17.3676 2.36772 17.2686 2.26872 17.1544 2.23163C17.054 2.199 16.9458 2.199 16.8454 2.23163C16.7313 2.26872 16.6322 2.36772 16.4342 2.56573L2.56561 16.4344C2.3676 16.6324 2.2686 16.7314 2.2315 16.8455C2.19887 16.946 2.19887 17.0541 2.2315 17.1546C2.2686 17.2687 2.3676 17.3677 2.56561 17.5657Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 929 B

@@ -0,0 +1,3 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12M22 12C22 6.47715 17.5228 2 12 2M22 12H19.5M2 12C2 6.47715 6.47715 2 12 2M2 12H4.5M12 2V4.5M19.0784 5L13.4999 10.5M19.0784 19.0784L18.8745 18.8745C18.1827 18.1827 17.8368 17.8368 17.4331 17.5894C17.0753 17.3701 16.6851 17.2085 16.2769 17.1105C15.8166 17 15.3274 17 14.349 17L9.65096 17C8.6726 17 8.18342 17 7.72307 17.1106C7.31493 17.2086 6.92475 17.3702 6.56686 17.5895C6.1632 17.8369 5.8173 18.1828 5.12549 18.8746L4.92163 19.0784M4.92163 5L6.65808 6.73645M14 12C14 13.1046 13.1046 14 12 14C10.8954 14 10 13.1046 10 12C10 10.8954 10.8954 10 12 10C13.1046 10 14 10.8954 14 12Z" stroke="black" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 834 B

-2
View File
@@ -9,8 +9,6 @@ html {
} }
:root { :root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
font-weight: 400;
font-synthesis: none; font-synthesis: none;
text-rendering: optimizeLegibility; text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
+3 -2
View File
@@ -11,7 +11,7 @@ const {
deleteAlertParamValidation, deleteAlertParamValidation,
} = require("../validation/joi"); } = require("../validation/joi");
const { successMessages } = require("../utils/messages"); const { successMessages } = require("../utils/messages");
const SERVICE_NAME = "alerts"; const SERVICE_NAME = "alertController";
/** /**
* Creates an alert for a monitor * Creates an alert for a monitor
@@ -41,7 +41,8 @@ const createAlert = async (req, res, next) => {
.status(200) .status(200)
.json({ success: true, msg: successMessages.ALERT_CREATE, data: alert }); .json({ success: true, msg: successMessages.ALERT_CREATE, data: alert });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "createAlert") : null;
next(error); next(error);
} }
}; };
+35 -23
View File
@@ -17,6 +17,7 @@ require("dotenv").config();
const { errorMessages, successMessages } = require("../utils/messages"); const { errorMessages, successMessages } = require("../utils/messages");
var jwt = require("jsonwebtoken"); var jwt = require("jsonwebtoken");
const SERVICE_NAME = "auth"; const SERVICE_NAME = "auth";
const { getTokenFromHeaders } = require("../utils/utils");
/** /**
* Creates and returns JWT token with an arbitrary payload * Creates and returns JWT token with an arbitrary payload
@@ -30,17 +31,6 @@ const issueToken = (payload) => {
return jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: tokenTTL }); return jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: tokenTTL });
}; };
const getTokenFromHeaders = (headers) => {
const authorizationHeader = headers.authorization;
if (!authorizationHeader) throw new Error("No auth headers");
const parts = authorizationHeader.split(" ");
if (parts.length !== 2 || parts[0] !== "Bearer")
throw new Error("Invalid auth headers");
return parts[1];
};
/** /**
* @function * @function
* @param {express.Request} req * @param {express.Request} req
@@ -110,7 +100,8 @@ const registerController = async (req, res, next) => {
data: { user: newUser, token: token }, data: { user: newUser, token: token },
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "registerController") : null;
next(error); next(error);
} }
}; };
@@ -162,7 +153,8 @@ const loginController = async (req, res, next) => {
}); });
} catch (error) { } catch (error) {
error.status = 500; error.status = 500;
// Anything else should be an error error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "loginController") : null;
next(error); next(error);
} }
}; };
@@ -223,7 +215,8 @@ const userEditController = async (req, res, next) => {
data: updatedUser, data: updatedUser,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "userEditController") : null;
next(error); next(error);
return; return;
} }
@@ -269,7 +262,8 @@ const inviteController = async (req, res, next) => {
.status(200) .status(200)
.json({ success: true, msg: "Invite sent", data: inviteToken }); .json({ success: true, msg: "Invite sent", data: inviteToken });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "inviteController") : null;
next(error); next(error);
return; return;
} }
@@ -293,7 +287,10 @@ const inviteVerifyController = async (req, res, next) => {
.status(200) .status(200)
.json({ status: "success", msg: "Invite verified", data: invite }); .json({ status: "success", msg: "Invite verified", data: invite });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined
? (error.method = "inviteVerifyController")
: null;
next(error); next(error);
return; return;
} }
@@ -316,7 +313,10 @@ const checkSuperadminController = async (req, res) => {
data: superAdminExists, data: superAdminExists,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined
? (error.method = "checkSuperadminController")
: null;
next(error); next(error);
return; return;
} }
@@ -366,7 +366,10 @@ const recoveryRequestController = async (req, res, next) => {
}); });
} }
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined
? (error.method = "recoveryRequestController")
: null;
next(error); next(error);
return; return;
} }
@@ -401,7 +404,10 @@ const validateRecoveryTokenController = async (req, res, next) => {
msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN, msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined
? (error.method = "validateRecoveryTokenController")
: null;
next(error); next(error);
return; return;
} }
@@ -437,7 +443,10 @@ const resetPasswordController = async (req, res, next) => {
data: { user, token }, data: { user, token },
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined
? (error.method = "resetPasswordController")
: null;
next(error); next(error);
} }
}; };
@@ -492,8 +501,8 @@ const deleteUserController = async (req, res, next) => {
msg: successMessages.AUTH_DELETE_USER, msg: successMessages.AUTH_DELETE_USER,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined && error.method === "deleteUserController"; error.method === undefined ? (error.method = "deleteUserController") : null;
next(error); next(error);
} }
}; };
@@ -505,7 +514,10 @@ const getAllUsersController = async (req, res) => {
.status(200) .status(200)
.json({ success: true, msg: "Got all users", data: allUsers }); .json({ success: true, msg: "Got all users", data: allUsers });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined
? (error.method = "getAllUsersController")
: null;
next(error); next(error);
} }
}; };
+50 -9
View File
@@ -7,9 +7,12 @@ const {
getTeamChecksQueryValidation, getTeamChecksQueryValidation,
deleteChecksParamValidation, deleteChecksParamValidation,
deleteChecksByTeamIdParamValidation, deleteChecksByTeamIdParamValidation,
updateChecksTTLBodyValidation,
} = require("../validation/joi"); } = require("../validation/joi");
const { successMessages } = require("../utils/messages"); const { successMessages } = require("../utils/messages");
const SERVICE_NAME = "check"; const jwt = require("jsonwebtoken");
const { getTokenFromHeaders } = require("../utils/utils");
const SERVICE_NAME = "checkController";
const createCheck = async (req, res, next) => { const createCheck = async (req, res, next) => {
try { try {
@@ -31,7 +34,8 @@ const createCheck = async (req, res, next) => {
.status(200) .status(200)
.json({ success: true, msg: successMessages.CHECK_CREATE, data: check }); .json({ success: true, msg: successMessages.CHECK_CREATE, data: check });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.serivce = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "createCheck") : null;
next(error); next(error);
} }
}; };
@@ -58,7 +62,8 @@ const getChecks = async (req, res, next) => {
data: { checksCount, checks }, data: { checksCount, checks },
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.serivce = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "getChecks") : null;
next(error); next(error);
} }
}; };
@@ -83,7 +88,8 @@ const getTeamChecks = async (req, res, next) => {
data: checkData, data: checkData,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.serivce = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "getTeamChecks") : null;
next(error); next(error);
} }
}; };
@@ -108,7 +114,8 @@ const deleteChecks = async (req, res, next) => {
data: { deletedCount }, data: { deletedCount },
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.serivce = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "deleteChecks") : null;
next(error); next(error);
} }
}; };
@@ -117,10 +124,11 @@ const deleteChecksByTeamId = async (req, res, next) => {
try { try {
await deleteChecksByTeamIdParamValidation.validateAsync(req.params); await deleteChecksByTeamIdParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method = "deleteChecksByTeam"; error.method === undefined ? (error.method = "deleteChecksByTeam") : null;
error.status = 422; error.status = 422;
next(error); next(error);
return;
} }
try { try {
@@ -131,8 +139,40 @@ const deleteChecksByTeamId = async (req, res, next) => {
data: { deletedCount }, data: { deletedCount },
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method = "deleteChecksByTeamId"; error.method === undefined ? (error.method = "deleteChecksByTeamId") : null;
next(error);
}
};
const updateChecksTTL = async (req, res, next) => {
const SECONDS_PER_DAY = 86400;
try {
await updateChecksTTLBodyValidation.validateAsync(req.body);
} catch (error) {
error.status = 422;
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "updateChecksTTL") : null;
error.message =
error.details?.[0]?.message || error.message || "Validation Error";
next(error);
return;
}
try {
// Get user's teamId
const token = getTokenFromHeaders(req.headers);
const { teamId } = jwt.verify(token, process.env.JWT_SECRET);
const ttl = parseInt(req.body.ttl, 10) * SECONDS_PER_DAY;
await req.db.updateChecksTTL(teamId, ttl);
return res.status(200).json({
success: true,
msg: successMessages.CHECK_UPDATE_TTL,
});
} catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "updateTTL") : null;
next(error); next(error);
} }
}; };
@@ -143,4 +183,5 @@ module.exports = {
getTeamChecks, getTeamChecks,
deleteChecks, deleteChecks,
deleteChecksByTeamId, deleteChecksByTeamId,
updateChecksTTL,
}; };
+6 -2
View File
@@ -60,7 +60,8 @@ const inviteController = async (req, res, next) => {
.status(200) .status(200)
.json({ success: true, msg: "Invite sent", data: inviteToken }); .json({ success: true, msg: "Invite sent", data: inviteToken });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "inviteController") : null;
next(error); next(error);
return; return;
} }
@@ -84,7 +85,10 @@ const inviteVerifyController = async (req, res, next) => {
.status(200) .status(200)
.json({ status: "success", msg: "Invite verified", data: invite }); .json({ status: "success", msg: "Invite verified", data: invite });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined
? (error.method = "inviteVerifyController")
: null;
next(error); next(error);
return; return;
} }
@@ -39,7 +39,10 @@ const createMaintenanceWindow = async (req, res, next) => {
data: maintenanceWindow, data: maintenanceWindow,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined
? (error.method = "createMaintenanceWindow")
: null;
next(error); next(error);
} }
}; };
@@ -68,7 +71,10 @@ const getMaintenanceWindowsByUserId = async (req, res, next) => {
data: maintenanceWindows, data: maintenanceWindows,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined
? (error.method = "getMaintenanceWindowsByUserId")
: null;
next(error); next(error);
} }
}; };
@@ -98,7 +104,10 @@ const getMaintenanceWindowsByMonitorId = async (req, res, next) => {
data: maintenanceWindows, data: maintenanceWindows,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined
? (error.method = "getMaintenanceWindowsByMonitorId")
: null;
next(error); next(error);
} }
}; };
+66 -17
View File
@@ -18,6 +18,9 @@ const {
const sslChecker = require("ssl-checker"); const sslChecker = require("ssl-checker");
const SERVICE_NAME = "monitorController"; const SERVICE_NAME = "monitorController";
const { errorMessages, successMessages } = require("../utils/messages"); const { errorMessages, successMessages } = require("../utils/messages");
const jwt = require("jsonwebtoken");
const { getTokenFromHeaders } = require("../utils/utils");
/** /**
* Returns all monitors * Returns all monitors
* @async * @async
@@ -35,7 +38,8 @@ const getAllMonitors = async (req, res, next) => {
data: monitors, data: monitors,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "getAllMonitors") : null;
next(error); next(error);
} }
}; };
@@ -74,6 +78,10 @@ const getMonitorAggregateStats = async (req, res, next) => {
data: aggregateStats, data: aggregateStats,
}); });
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined
? (error.method = "getMonitorAggregateStats")
: null;
next(error); next(error);
} }
}; };
@@ -106,7 +114,8 @@ const getMonitorStatsById = async (req, res, next) => {
data: monitorStats, data: monitorStats,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "getMonitorStatsById") : null;
next(error); next(error);
} }
}; };
@@ -142,7 +151,10 @@ const getMonitorCertificate = async (req, res, next) => {
}); });
} }
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined
? (error.method = "getMonitorCertificate")
: null;
next(error); next(error);
} }
}; };
@@ -181,7 +193,8 @@ const getMonitorById = async (req, res, next) => {
data: monitor, data: monitor,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "getMonitorById") : null;
next(error); next(error);
} }
}; };
@@ -226,9 +239,10 @@ const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
data: monitorsSummary, data: monitorsSummary,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined && error.method === undefined
error.method === "getMonitorsAndSummaryByTeamId"; ? (error.method = "getMonitorsAndSummaryByTeamId")
: null;
next(error); next(error);
} }
}; };
@@ -257,14 +271,14 @@ const getMonitorsByTeamId = async (req, res, next) => {
try { try {
const teamId = req.params.teamId; const teamId = req.params.teamId;
const monitors = await req.db.getMonitorsByTeamId(req, res); const monitors = await req.db.getMonitorsByTeamId(req, res);
return res.json({ return res.json({
success: true, success: true,
msg: successMessages.MONITOR_GET_BY_USER_ID(teamId), msg: successMessages.MONITOR_GET_BY_USER_ID(teamId),
data: monitors, data: monitors,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "getMonitorsByTeamId") : null;
next(error); next(error);
} }
}; };
@@ -313,7 +327,8 @@ const createMonitor = async (req, res, next) => {
data: monitor, data: monitor,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "createMonitor") : null;
next(error); next(error);
} }
}; };
@@ -358,19 +373,31 @@ const deleteMonitor = async (req, res, next) => {
.status(200) .status(200)
.json({ success: true, msg: successMessages.MONITOR_DELETE }); .json({ success: true, msg: successMessages.MONITOR_DELETE });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "deleteMonitor") : null;
next(error); next(error);
} }
}; };
const deleteAllMonitors = async (req, res) => { const deleteAllMonitors = async (req, res) => {
try { try {
const deleteCount = await req.db.deleteAllMonitors(); const token = getTokenFromHeaders(req.headers);
const { teamId } = jwt.verify(token, process.env.JWT_SECRET);
const { monitors, deletedCount } = await req.db.deleteAllMonitors(teamId);
await monitors.forEach(async (monitor) => {
await req.jobQueue.deleteJob(monitor);
await req.db.deleteChecks(monitor._id);
await req.db.deleteAlertByMonitorId(monitor._id);
await req.db.deletePageSpeedChecksByMonitorId(monitor._id);
await req.db.deleteNotificationsByMonitorId(monitor._id);
});
return res return res
.status(200) .status(200)
.json({ success: true, msg: `Deleted ${deleteCount} monitors` }); .json({ success: true, msg: `Deleted ${deletedCount} monitors` });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "deleteAllMonitors") : null;
next(error); next(error);
} }
}; };
@@ -426,7 +453,8 @@ const editMonitor = async (req, res, next) => {
data: editedMonitor, data: editedMonitor,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "editMonitor") : null;
next(error); next(error);
} }
}; };
@@ -460,8 +488,28 @@ const pauseMonitor = async (req, res, next) => {
data: monitor, data: monitor,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method = "pauseMonitor"; error.method === undefined ? (error.method = "pauseMonitor") : null;
next(error);
}
};
const addDemoMonitors = async (req, res, next) => {
try {
const token = getTokenFromHeaders(req.headers);
const { _id, teamId } = jwt.verify(token, process.env.JWT_SECRET);
const demoMonitors = await req.db.addDemoMonitors(_id, teamId);
await demoMonitors.forEach(async (monitor) => {
await req.jobQueue.addJob(monitor._id, monitor);
});
return res.status(200).json({
success: true,
message: successMessages.MONITOR_DEMO_ADDED,
data: demoMonitors.length,
});
} catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "addDemoMonitors") : null;
next(error); next(error);
} }
}; };
@@ -479,4 +527,5 @@ module.exports = {
deleteAllMonitors, deleteAllMonitors,
editMonitor, editMonitor,
pauseMonitor, pauseMonitor,
addDemoMonitors,
}; };
@@ -1,7 +1,7 @@
const PageSpeedService = require("../service/pageSpeedService"); const PageSpeedService = require("../service/pageSpeedService");
const { successMessages } = require("../utils/messages"); const { successMessages } = require("../utils/messages");
const pageSpeedService = new PageSpeedService(); const pageSpeedService = new PageSpeedService();
const SERVICE_NAME = "pagespeed"; const SERVICE_NAME = "pagespeedCheckController";
const { const {
getPageSpeedCheckParamValidation, getPageSpeedCheckParamValidation,
createPageSpeedCheckParamValidation, createPageSpeedCheckParamValidation,
@@ -33,7 +33,8 @@ const getPageSpeedChecks = async (req, res, next) => {
try { try {
return res.status(200).json({ msg: "Hit getPageSpeedChecks" }); return res.status(200).json({ msg: "Hit getPageSpeedChecks" });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "getPageSpeedChecks") : null;
next(error); next(error);
} }
}; };
@@ -86,7 +87,8 @@ const createPageSpeedCheck = async (req, res, next) => {
data: newPageSpeedCheck, data: newPageSpeedCheck,
}); });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "createPageSpeedCheck") : null;
next(error); next(error);
} }
}; };
@@ -114,7 +116,8 @@ const deletePageSpeedCheck = async (req, res, next) => {
try { try {
return res.status(200).json({ msg: "Hit deletePageSpeedCheck" }); return res.status(200).json({ msg: "Hit deletePageSpeedCheck" });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "deletePageSpeedCheck") : null;
next(error); next(error);
} }
}; };
+9 -5
View File
@@ -1,4 +1,4 @@
const SERVICE_NAME = "JobQueue"; const SERVICE_NAME = "JobQueueController";
const getMetrics = async (req, res, next) => { const getMetrics = async (req, res, next) => {
try { try {
@@ -7,7 +7,8 @@ const getMetrics = async (req, res, next) => {
.status(200) .status(200)
.json({ success: true, msg: "Metrics retrieved", data: metrics }); .json({ success: true, msg: "Metrics retrieved", data: metrics });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "getMetrics") : null;
next(error); next(error);
return; return;
} }
@@ -18,7 +19,8 @@ const getJobs = async (req, res, next) => {
const jobs = await req.jobQueue.getJobStats(); const jobs = await req.jobQueue.getJobStats();
return res.status(200).json({ jobs }); return res.status(200).json({ jobs });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "getJobs") : null;
next(error); next(error);
return; return;
} }
@@ -29,7 +31,8 @@ const addJob = async (req, res, next) => {
await req.jobQueue.addJob(Math.random().toString(36).substring(7)); await req.jobQueue.addJob(Math.random().toString(36).substring(7));
return res.send("Added job"); return res.send("Added job");
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "addJob") : null;
next(error); next(error);
return; return;
} }
@@ -40,7 +43,8 @@ const obliterateQueue = async (req, res, next) => {
const obliterated = await req.jobQueue.obliterate(); const obliterated = await req.jobQueue.obliterate();
return res.status(200).send("Obliterated jobs"); return res.status(200).send("Obliterated jobs");
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "obliterateQueue") : null;
next(error); next(error);
return; return;
} }
+4
View File
@@ -73,6 +73,7 @@ const {
deleteAllMonitors, deleteAllMonitors,
deleteMonitorsByUserId, deleteMonitorsByUserId,
editMonitor, editMonitor,
addDemoMonitors,
} = require("./modules/monitorModule"); } = require("./modules/monitorModule");
//**************************************** //****************************************
@@ -96,6 +97,7 @@ const {
getTeamChecks, getTeamChecks,
deleteChecks, deleteChecks,
deleteChecksByTeamId, deleteChecksByTeamId,
updateChecksTTL,
} = require("./modules/checkModule"); } = require("./modules/checkModule");
//**************************************** //****************************************
@@ -153,12 +155,14 @@ module.exports = {
deleteMonitor, deleteMonitor,
deleteAllMonitors, deleteAllMonitors,
editMonitor, editMonitor,
addDemoMonitors,
createCheck, createCheck,
getChecksCount, getChecksCount,
getChecks, getChecks,
getTeamChecks, getTeamChecks,
deleteChecks, deleteChecks,
deleteChecksByTeamId, deleteChecksByTeamId,
updateChecksTTL,
createAlert, createAlert,
getAlertsByUserId, getAlertsByUserId,
getAlertsByMonitorId, getAlertsByMonitorId,
+56 -15
View File
@@ -1,6 +1,8 @@
const Check = require("../../../models/Check"); const Check = require("../../../models/Check");
const Monitor = require("../../../models/Monitor"); const Monitor = require("../../../models/Monitor");
const mongoose = require("mongoose"); const User = require("../../../models/user");
const logger = require("../../../utils/logger");
const SERVICE_NAME = "checkModule";
const dateRangeLookup = { const dateRangeLookup = {
day: new Date(new Date().setDate(new Date().getDate() - 1)), day: new Date(new Date().setDate(new Date().getDate() - 1)),
week: new Date(new Date().setDate(new Date().getDate() - 7)), week: new Date(new Date().setDate(new Date().getDate() - 7)),
@@ -23,28 +25,32 @@ const dateRangeLookup = {
const createCheck = async (checkData) => { const createCheck = async (checkData) => {
try { try {
const { monitorId, status } = checkData; const { monitorId, status } = checkData;
const n = (await Check.countDocuments({ monitorId })) + 1;
const n = await Check.countDocuments({ monitorId }) + 1;
const check = await new Check({ ...checkData }).save(); const check = await new Check({ ...checkData }).save();
const monitor = await Monitor.findById(monitorId); const monitor = await Monitor.findById(monitorId);
if (!monitor) { if (!monitor) {
throw new Error("Monitor not found"); logger.error("Monitor not found", {
service: SERVICE_NAME,
monitorId,
});
return;
} }
// Update uptime percentage
if (monitor.uptimePercentage === undefined) { if (monitor.uptimePercentage === undefined) {
monitor.uptimePercentage = (status === true) ? 1 : 0; monitor.uptimePercentage = status === true ? 1 : 0;
} else { } else {
monitor.uptimePercentage = monitor.uptimePercentage =
(monitor.uptimePercentage * (n - 1) + (status === true ? 1: 0)) / n; (monitor.uptimePercentage * (n - 1) + (status === true ? 1 : 0)) / n;
} }
await monitor.save(); await monitor.save();
return check; return check;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "createCheck";
throw error; throw error;
} }
}; };
@@ -132,6 +138,8 @@ const getChecks = async (req) => {
.sort({ createdAt: sortOrder }); .sort({ createdAt: sortOrder });
return checks; return checks;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "getChecks";
throw error; throw error;
} }
}; };
@@ -141,17 +149,15 @@ const getTeamChecks = async (req) => {
let { sortOrder, limit, dateRange, filter, page, rowsPerPage } = req.query; let { sortOrder, limit, dateRange, filter, page, rowsPerPage } = req.query;
// Get monitorIDs // Get monitorIDs
const userMonitors = await Monitor.find({ teamId: teamId }); const userMonitors = await Monitor.find({ teamId: teamId }).select("_id");
const monitorIds = userMonitors.map((monitor) => monitor._id);
//Build check query //Build check query
// Default limit to 0 if not provided // Default limit to 0 if not provided
limit = limit === "undefined" ? 0 : limit; limit = limit === undefined ? 0 : limit;
// Default sort order is newest -> oldest // Default sort order is newest -> oldest
sortOrder = sortOrder === "asc" ? 1 : -1; sortOrder = sortOrder === "asc" ? 1 : -1;
checksQuery = { monitorId: { $in: monitorIds } }; checksQuery = { monitorId: { $in: userMonitors } };
if (filter !== undefined) { if (filter !== undefined) {
checksQuery.status = false; checksQuery.status = false;
@@ -184,8 +190,8 @@ const getTeamChecks = async (req) => {
const checks = await Check.find(checksQuery) const checks = await Check.find(checksQuery)
.skip(skip) .skip(skip)
.limit(rowsPerPage) .limit(rowsPerPage)
.sort({ createdAt: sortOrder }); .sort({ createdAt: sortOrder })
.select(["monitorId", "status", "responseTime", "statusCode", "message"]);
return { checksCount, checks }; return { checksCount, checks };
}; };
@@ -202,6 +208,8 @@ const deleteChecks = async (monitorId) => {
const result = await Check.deleteMany({ monitorId }); const result = await Check.deleteMany({ monitorId });
return result.deletedCount; return result.deletedCount;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteChecks";
throw error; throw error;
} }
}; };
@@ -230,6 +238,38 @@ const deleteChecksByTeamId = async (teamId) => {
return totalDeletedCount; return totalDeletedCount;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteChecksByTeamId";
throw error;
}
};
const updateChecksTTL = async (teamId, ttl) => {
try {
await Check.collection.dropIndex("expiry_1");
} catch (error) {
logger.error("Failed to drop index", {
service: SERVICE_NAME,
method: "updateChecksTTL",
});
}
try {
await Check.collection.createIndex(
{ expiry: 1 },
{ expireAfterSeconds: ttl } // TTL in seconds, adjust as necessary
);
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateChecksTTL";
throw error;
}
// Update user
try {
await User.updateMany({ teamId: teamId }, { checkTTL: ttl });
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateChecksTTL";
throw error; throw error;
} }
}; };
@@ -241,4 +281,5 @@ module.exports = {
getTeamChecks, getTeamChecks,
deleteChecks, deleteChecks,
deleteChecksByTeamId, deleteChecksByTeamId,
updateChecksTTL,
}; };
+5
View File
@@ -1,6 +1,7 @@
const InviteToken = require("../../../models/InviteToken"); const InviteToken = require("../../../models/InviteToken");
const crypto = require("crypto"); const crypto = require("crypto");
const { errorMessages } = require("../../../utils/messages"); const { errorMessages } = require("../../../utils/messages");
const SERVICE_NAME = "inviteModule";
/** /**
* Request an invite token for a user. * Request an invite token for a user.
@@ -24,6 +25,8 @@ const requestInviteToken = async (userData) => {
await inviteToken.save(); await inviteToken.save();
return inviteToken; return inviteToken;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "requestInviteToken";
throw error; throw error;
} }
}; };
@@ -48,6 +51,8 @@ const getInviteToken = async (token) => {
} }
return invite; return invite;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "getInviteToken";
throw error; throw error;
} }
}; };
@@ -1,4 +1,5 @@
const MaintenanceWindow = require("../../../models/MaintenanceWindow"); const MaintenanceWindow = require("../../../models/MaintenanceWindow");
const SERVICE_NAME = "maintenanceWindowModule";
/** /**
* Asynchronously creates a new MaintenanceWindow document and saves it to the database. * Asynchronously creates a new MaintenanceWindow document and saves it to the database.
@@ -38,6 +39,8 @@ const createMaintenanceWindow = async (maintenanceWindowData) => {
const result = maintenanceWindow.save(); const result = maintenanceWindow.save();
return result; return result;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "createMaintenanceWindow";
throw error; throw error;
} }
}; };
@@ -59,6 +62,8 @@ const getMaintenanceWindowsByUserId = async (userId) => {
const maintenanceWindows = await MaintenanceWindow.find({ userId: userId }); const maintenanceWindows = await MaintenanceWindow.find({ userId: userId });
return maintenanceWindows; return maintenanceWindows;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowByUserId";
throw error; throw error;
} }
}; };
@@ -82,6 +87,8 @@ const getMaintenanceWindowsByMonitorId = async (monitorId) => {
}); });
return maintenanceWindows; return maintenanceWindows;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowsByMonitorId";
throw error; throw error;
} }
}; };
@@ -104,6 +111,8 @@ const deleteMaintenaceWindowById = async (maintenanceWindowId) => {
await MaintenanceWindow.findByIdAndDelete(maintenanceWindowId); await MaintenanceWindow.findByIdAndDelete(maintenanceWindowId);
return maintenanceWindow; return maintenanceWindow;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMaintenaceWindowById";
throw error; throw error;
} }
}; };
@@ -125,6 +134,8 @@ const deleteMaintenanceWindowByMonitorId = async (monitorId) => {
const result = await MaintenanceWindow.deleteMany({ monitorId: monitorId }); const result = await MaintenanceWindow.deleteMany({ monitorId: monitorId });
return result; return result;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMaintenanceWindowByMonitorId";
throw error; throw error;
} }
}; };
@@ -146,6 +157,8 @@ const deleteMaintenanceWindowByUserId = async (userId) => {
const result = await MaintenanceWindow.deleteMany({ userId: userId }); const result = await MaintenanceWindow.deleteMany({ userId: userId });
return result; return result;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMaintenanceWindowByUserId";
throw error; throw error;
} }
}; };
+95 -19
View File
@@ -4,6 +4,8 @@ const PageSpeedCheck = require("../../../models/PageSpeedCheck");
const { errorMessages } = require("../../../utils/messages"); const { errorMessages } = require("../../../utils/messages");
const Notification = require("../../../models/Notification"); const Notification = require("../../../models/Notification");
const { NormalizeData } = require("../../../utils/dataUtils"); const { NormalizeData } = require("../../../utils/dataUtils");
const demoMonitors = require("../../../utils/demoMonitors.json");
const SERVICE_NAME = "monitorModule";
/** /**
* Get all monitors * Get all monitors
@@ -18,6 +20,8 @@ const getAllMonitors = async (req, res) => {
const monitors = await Monitor.find(); const monitors = await Monitor.find();
return monitors; return monitors;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "getAllMonitors";
throw error; throw error;
} }
}; };
@@ -261,7 +265,8 @@ const getMonitorStatsById = async (req) => {
return monitorStats; return monitorStats;
} catch (error) { } catch (error) {
error.methodName = "getMonitorStatsById"; error.service = SERVICE_NAME;
error.method = "getMonitorStatsById";
throw error; throw error;
} }
}; };
@@ -288,6 +293,8 @@ const getMonitorById = async (monitorId) => {
const monitorWithNotifications = await monitor.save(); const monitorWithNotifications = await monitor.save();
return monitorWithNotifications; return monitorWithNotifications;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorById";
throw error; throw error;
} }
}; };
@@ -324,6 +331,7 @@ const getMonitorsAndSummaryByTeamId = async (teamId, type) => {
monitorCounts.total = monitors.length; monitorCounts.total = monitors.length;
return { monitors, monitorCounts }; return { monitors, monitorCounts };
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorsAndSummaryByTeamId"; error.method = "getMonitorsAndSummaryByTeamId";
throw error; throw error;
} }
@@ -339,13 +347,31 @@ const getMonitorsAndSummaryByTeamId = async (teamId, type) => {
*/ */
const getMonitorsByTeamId = async (req, res) => { const getMonitorsByTeamId = async (req, res) => {
try { try {
let { limit, type, status, sortOrder, normalize, page, rowsPerPage } = let {
req.query || {}; limit,
const monitorQuery = { teamId: req.params.teamId };
const monitorsCount = await Monitor.countDocuments({
teamId: req.params.teamId,
type, type,
}); status,
checkOrder,
normalize,
page,
rowsPerPage,
filter,
field,
order,
} = req.query || {};
const monitorQuery = { teamId: req.params.teamId };
if (type !== undefined) {
monitorQuery.type = type;
}
// Add filter if provided
// $options: "i" makes the search case-insensitive
if (filter !== undefined) {
monitorQuery.$or = [
{ name: { $regex: filter, $options: "i" } },
{ url: { $regex: filter, $options: "i" } },
];
}
const monitorsCount = await Monitor.countDocuments(monitorQuery);
// Pagination // Pagination
let skip = 0; let skip = 0;
@@ -359,18 +385,31 @@ const getMonitorsByTeamId = async (req, res) => {
} }
// Default sort order is newest -> oldest // Default sort order is newest -> oldest
if (sortOrder === "asc") { if (checkOrder === "asc") {
sortOrder = 1; checkOrder = 1;
} else if (sortOrder === "desc") { } else if (checkOrder === "desc") {
sortOrder = -1; checkOrder = -1;
} else sortOrder = -1; } else checkOrder = -1;
// Sort order for monitors
let sort = {};
if (field !== undefined && order !== undefined) {
sort[field] = order === "asc" ? 1 : -1;
}
const monitors = await Monitor.find(monitorQuery)
.skip(skip)
.limit(rowsPerPage)
.sort(sort);
// Early return if limit is set to -1, indicating we don't want any checks
if (limit === "-1") {
return { monitors, monitorCount: monitorsCount };
}
// This effectively removes limit, returning all checks // This effectively removes limit, returning all checks
if (limit === undefined) limit = 0; if (limit === undefined) limit = 0;
const monitors = await Monitor.find(monitorQuery)
.skip(skip)
.limit(rowsPerPage);
// Map each monitor to include its associated checks // Map each monitor to include its associated checks
const monitorsWithChecks = await Promise.all( const monitorsWithChecks = await Promise.all(
monitors.map(async (monitor) => { monitors.map(async (monitor) => {
@@ -388,7 +427,7 @@ const getMonitorsByTeamId = async (req, res) => {
let checks = await model let checks = await model
.find(checksQuery) .find(checksQuery)
.sort({ .sort({
createdAt: sortOrder, createdAt: checkOrder,
}) })
.limit(limit); .limit(limit);
@@ -401,6 +440,8 @@ const getMonitorsByTeamId = async (req, res) => {
); );
return { monitors: monitorsWithChecks, monitorCount: monitorsCount }; return { monitors: monitorsWithChecks, monitorCount: monitorsCount };
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorsByTeamId";
throw error; throw error;
} }
}; };
@@ -421,6 +462,8 @@ const createMonitor = async (req, res) => {
await monitor.save(); await monitor.save();
return monitor; return monitor;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "createMonitor";
throw error; throw error;
} }
}; };
@@ -442,6 +485,8 @@ const deleteMonitor = async (req, res) => {
} }
return monitor; return monitor;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMonitor";
throw error; throw error;
} }
}; };
@@ -450,11 +495,15 @@ const deleteMonitor = async (req, res) => {
* DELETE ALL MONITORS (TEMP) * DELETE ALL MONITORS (TEMP)
*/ */
const deleteAllMonitors = async (req, res) => { const deleteAllMonitors = async (teamId) => {
try { try {
const deletedCount = await Monitor.deleteMany({}); const monitors = await Monitor.find({ teamId });
return deletedCount.deletedCount; const { deletedCount } = await Monitor.deleteMany({ teamId });
return { monitors, deletedCount };
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteAllMonitors";
throw error; throw error;
} }
}; };
@@ -470,6 +519,8 @@ const deleteMonitorsByUserId = async (userId) => {
const result = await Monitor.deleteMany({ userId: userId }); const result = await Monitor.deleteMany({ userId: userId });
return result; return result;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMonitorsByUserId";
throw error; throw error;
} }
}; };
@@ -493,6 +544,30 @@ const editMonitor = async (candidateId, candidateMonitor) => {
); );
return editedMonitor; return editedMonitor;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "editMonitor";
throw error;
}
};
const addDemoMonitors = async (userId, teamId) => {
try {
const demoMonitorsToInsert = demoMonitors.map((monitor) => {
return {
userId,
teamId,
name: monitor.name,
description: monitor.name,
type: "http",
url: monitor.url,
interval: 60000,
};
});
const insertedMonitors = await Monitor.insertMany(demoMonitorsToInsert);
return insertedMonitors;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "addDemoMonitors";
throw error; throw error;
} }
}; };
@@ -508,4 +583,5 @@ module.exports = {
deleteAllMonitors, deleteAllMonitors,
deleteMonitorsByUserId, deleteMonitorsByUserId,
editMonitor, editMonitor,
addDemoMonitors,
}; };
@@ -1,5 +1,5 @@
const Notification = require("../../../models/Notification"); const Notification = require("../../../models/Notification");
const SERVICE_NAME = "notificationModule";
/** /**
* Creates a new notification. * Creates a new notification.
* @param {Object} notificationData - The data for the new notification. * @param {Object} notificationData - The data for the new notification.
@@ -15,6 +15,8 @@ const createNotification = async (notificationData) => {
const notification = await new Notification({ ...notificationData }).save(); const notification = await new Notification({ ...notificationData }).save();
return notification; return notification;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "createNotification";
throw error; throw error;
} }
}; };
@@ -30,6 +32,8 @@ const getNotificationsByMonitorId = async (monitorId) => {
const notifications = await Notification.find({ monitorId }); const notifications = await Notification.find({ monitorId });
return notifications; return notifications;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "getNotificationsByMonitorId";
throw error; throw error;
} }
}; };
@@ -39,6 +43,8 @@ const deleteNotificationsByMonitorId = async (monitorId) => {
const result = await Notification.deleteMany({ monitorId }); const result = await Notification.deleteMany({ monitorId });
return result.deletedCount; return result.deletedCount;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteNotificationsByMonitorId";
throw error; throw error;
} }
}; };
@@ -1,5 +1,5 @@
const PageSpeedCheck = require("../../../models/PageSpeedCheck"); const PageSpeedCheck = require("../../../models/PageSpeedCheck");
const SERVICE_NAME = "pageSpeedCheckModule";
/** /**
* Create a PageSpeed check for a monitor * Create a PageSpeed check for a monitor
* @async * @async
@@ -19,6 +19,8 @@ const createPageSpeedCheck = async (pageSpeedCheckData) => {
}).save(); }).save();
return pageSpeedCheck; return pageSpeedCheck;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "createPageSpeedCheck";
throw error; throw error;
} }
}; };
@@ -36,6 +38,8 @@ const getPageSpeedChecks = async (monitorId) => {
const pageSpeedChecks = await PageSpeedCheck.find({ monitorId }); const pageSpeedChecks = await PageSpeedCheck.find({ monitorId });
return pageSpeedChecks; return pageSpeedChecks;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "getPageSpeedChecks";
throw error; throw error;
} }
}; };
@@ -53,6 +57,8 @@ const deletePageSpeedChecksByMonitorId = async (monitorId) => {
const result = await PageSpeedCheck.deleteMany({ monitorId }); const result = await PageSpeedCheck.deleteMany({ monitorId });
return result.deletedCount; return result.deletedCount;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "deletePageSpeedChecksByMonitorId";
throw error; throw error;
} }
}; };
@@ -2,6 +2,7 @@ const UserModel = require("../../../models/user");
const RecoveryToken = require("../../../models/RecoveryToken"); const RecoveryToken = require("../../../models/RecoveryToken");
const crypto = require("crypto"); const crypto = require("crypto");
const { errorMessages } = require("../../../utils/messages"); const { errorMessages } = require("../../../utils/messages");
const SERVICE_NAME = "recoveryModule";
/** /**
* Request a recovery token * Request a recovery token
@@ -22,6 +23,8 @@ const requestRecoveryToken = async (req, res) => {
await recoveryToken.save(); await recoveryToken.save();
return recoveryToken; return recoveryToken;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "requestRecoveryToken";
throw error; throw error;
} }
}; };
@@ -38,6 +41,8 @@ const validateRecoveryToken = async (req, res) => {
throw new Error(errorMessages.DB_TOKEN_NOT_FOUND); throw new Error(errorMessages.DB_TOKEN_NOT_FOUND);
} }
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "validateRecoveryToken";
throw error; throw error;
} }
}; };
@@ -70,6 +75,8 @@ const resetPassword = async (req, res) => {
throw new Error(errorMessages.DB_USER_NOT_FOUND); throw new Error(errorMessages.DB_USER_NOT_FOUND);
} }
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "resetPassword";
throw error; throw error;
} }
}; };
+14 -1
View File
@@ -5,6 +5,7 @@ const { GenerateAvatarImage } = require("../../../utils/imageProcessing");
const DUPLICATE_KEY_CODE = 11000; // MongoDB error code for duplicate key const DUPLICATE_KEY_CODE = 11000; // MongoDB error code for duplicate key
const { ParseBoolean } = require("../../../utils/utils"); const { ParseBoolean } = require("../../../utils/utils");
SERVICE_NAME = "userModule";
/** /**
* Insert a User * Insert a User
@@ -44,8 +45,10 @@ const insertUser = async (userData, imageFile) => {
.select("-profileImage"); // .select() doesn't work with create, need to save then find .select("-profileImage"); // .select() doesn't work with create, need to save then find
} catch (error) { } catch (error) {
if (error.code === DUPLICATE_KEY_CODE) { if (error.code === DUPLICATE_KEY_CODE) {
throw new Error(errorMessages.DB_USER_EXISTS); error.message = errorMessages.DB_USER_EXISTS;
} }
error.service = SERVICE_NAME;
error.method = "insertUser";
throw error; throw error;
} }
}; };
@@ -74,6 +77,8 @@ const getUserByEmail = async (email) => {
throw new Error(errorMessages.DB_USER_NOT_FOUND); throw new Error(errorMessages.DB_USER_NOT_FOUND);
} }
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "getUserByEmail";
throw error; throw error;
} }
}; };
@@ -123,6 +128,8 @@ const updateUser = async (req, res) => {
.select("-profileImage"); .select("-profileImage");
return updatedUser; return updatedUser;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "updateUser";
throw error; throw error;
} }
}; };
@@ -143,6 +150,8 @@ const deleteUser = async (userId) => {
} }
return deletedUser; return deletedUser;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteUser";
throw error; throw error;
} }
}; };
@@ -154,6 +163,8 @@ const getAllUsers = async (req, res) => {
.select("-profileImage"); .select("-profileImage");
return users; return users;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "getAllUsers";
throw error; throw error;
} }
}; };
@@ -163,6 +174,8 @@ const logoutUser = async (userId) => {
await UserModel.updateOne({ _id: userId }, { $unset: { authToken: null } }); await UserModel.updateOne({ _id: userId }, { $unset: { authToken: null } });
return true; return true;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME;
error.method = "logoutUser";
throw error; throw error;
} }
}; };
+1 -1
View File
@@ -7,7 +7,7 @@ const handleErrors = (error, req, res, next) => {
const service = error.service || errorMessages.UNKNOWN_SERVICE; const service = error.service || errorMessages.UNKNOWN_SERVICE;
logger.error(error.message, { logger.error(error.message, {
service: service, service: service,
methodName: error.methodName, method: error.method,
}); });
res.status(status).json({ success: false, msg: message }); res.status(status).json({ success: false, msg: message });
}; };
+1
View File
@@ -43,6 +43,7 @@ const isAllowed = (allowedRoles) => {
} }
} catch (error) { } catch (error) {
error.status = 401; error.status = 401;
error.method = "isAllowed";
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
next(error); next(error);
return; return;
+1
View File
@@ -28,6 +28,7 @@ const verifyJWT = (req, res, next) => {
const error = new Error(errorMessages.INVALID_AUTH_TOKEN); // Instantiate a new Error object for improperly formatted token const error = new Error(errorMessages.INVALID_AUTH_TOKEN); // Instantiate a new Error object for improperly formatted token
error.status = 400; error.status = 400;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "verifyJWT";
next(error); next(error);
return; return;
} }
+1
View File
@@ -39,6 +39,7 @@ const verifyOwnership = (Model, paramName) => {
return; return;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "verifyOwnership";
next(error); next(error);
return; return;
} }
+1
View File
@@ -26,6 +26,7 @@ const verifySuperAdmin = (req, res, next) => {
const error = new Error(errorMessages.INVALID_AUTH_TOKEN); // Instantiate a new Error object for improperly formatted token const error = new Error(errorMessages.INVALID_AUTH_TOKEN); // Instantiate a new Error object for improperly formatted token
error.status = 400; error.status = 400;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "verifySuperAdmin";
next(error); next(error);
return; return;
} }
+5
View File
@@ -19,6 +19,7 @@ const CheckSchema = mongoose.Schema(
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
ref: "Monitor", ref: "Monitor",
immutable: true, immutable: true,
index: true,
}, },
/** /**
* Status of the check (true for up, false for down). * Status of the check (true for up, false for down).
@@ -27,6 +28,7 @@ const CheckSchema = mongoose.Schema(
*/ */
status: { status: {
type: Boolean, type: Boolean,
index: true,
}, },
/** /**
* Response time of the check in milliseconds. * Response time of the check in milliseconds.
@@ -43,6 +45,7 @@ const CheckSchema = mongoose.Schema(
*/ */
statusCode: { statusCode: {
type: Number, type: Number,
index: true,
}, },
/** /**
* Message or description of the check result. * Message or description of the check result.
@@ -69,4 +72,6 @@ const CheckSchema = mongoose.Schema(
} }
); );
CheckSchema.index({ createdAt: 1 });
module.exports = mongoose.model("Check", CheckSchema); module.exports = mongoose.model("Check", CheckSchema);
+3
View File
@@ -45,6 +45,9 @@ const UserSchema = mongoose.Schema(
ref: "Team", ref: "Team",
immutable: true, immutable: true,
}, },
checkTTL: {
type: Number,
},
}, },
{ {
timestamps: true, timestamps: true,
+6
View File
@@ -26,4 +26,10 @@ router.delete(
checkController.deleteChecksByTeamId checkController.deleteChecksByTeamId
); );
router.put(
"/ttl",
isAllowed(["admin", "superadmin"]),
checkController.updateChecksTTL
);
module.exports = router; module.exports = router;
+7 -1
View File
@@ -32,7 +32,7 @@ router.put(
); );
router.delete( router.delete(
"/all", "/",
isAllowed(["superadmin"]), isAllowed(["superadmin"]),
monitorController.deleteAllMonitors monitorController.deleteAllMonitors
); );
@@ -43,4 +43,10 @@ router.post(
monitorController.pauseMonitor monitorController.pauseMonitor
); );
router.post(
"/demo",
isAllowed(["admin", "superadmin"]),
monitorController.addDemoMonitors
);
module.exports = router; module.exports = router;
+16 -8
View File
@@ -7,7 +7,6 @@ const connection = {
const JOBS_PER_WORKER = 5; const JOBS_PER_WORKER = 5;
const logger = require("../utils/logger"); const logger = require("../utils/logger");
const { errorMessages, successMessages } = require("../utils/messages"); const { errorMessages, successMessages } = require("../utils/messages");
const NetworkService = require("./networkService");
const SERVICE_NAME = "JobQueue"; const SERVICE_NAME = "JobQueue";
class JobQueue { class JobQueue {
@@ -47,6 +46,8 @@ class JobQueue {
await queue.scaleWorkers(workerStats); await queue.scaleWorkers(workerStats);
return queue; return queue;
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "createJobQueue") : null;
throw error; throw error;
} }
} }
@@ -126,8 +127,10 @@ class JobQueue {
const load = jobs.length / this.workers.length; const load = jobs.length / this.workers.length;
return { jobs, load }; return { jobs, load };
} catch (error) { } catch (error) {
console.log(error); error.service === undefined ? (error.service = SERVICE_NAME) : null;
errorObject.method === undefined
? (error.method = "getWorkerStats")
: null;
throw error; throw error;
} }
} }
@@ -204,8 +207,8 @@ class JobQueue {
const jobs = await this.queue.getRepeatableJobs(); const jobs = await this.queue.getRepeatableJobs();
return jobs; return jobs;
} catch (error) { } catch (error) {
console.log(error); error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "getJobs") : null;
throw error; throw error;
} }
} }
@@ -221,8 +224,8 @@ class JobQueue {
); );
return { jobs: ret, workers: this.workers.length }; return { jobs: ret, workers: this.workers.length };
} catch (error) { } catch (error) {
console.log(error); error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "getJobStats") : null;
throw error; throw error;
} }
} }
@@ -248,7 +251,8 @@ class JobQueue {
const workerStats = await this.getWorkerStats(); const workerStats = await this.getWorkerStats();
await this.scaleWorkers(workerStats); await this.scaleWorkers(workerStats);
} catch (error) { } catch (error) {
console.log(error); error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "addJob") : null;
throw error; throw error;
} }
} }
@@ -277,6 +281,8 @@ class JobQueue {
}); });
} }
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "deleteJob") : null;
throw error; throw error;
} }
} }
@@ -329,6 +335,8 @@ class JobQueue {
}); });
return true; return true;
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "obliterate") : null;
throw error; throw error;
} }
} }
+9 -2
View File
@@ -89,6 +89,10 @@ class NetworkService {
} catch (error) { } catch (error) {
const endTime = Date.now(); const endTime = Date.now();
error.responseTime = endTime - startTime; error.responseTime = endTime - startTime;
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.mheotd === undefined
? (error.method = "measureResponseTime")
: null;
throw error; throw error;
} }
} }
@@ -278,6 +282,7 @@ class NetworkService {
default: default:
logger.error(`Unsupported type: ${job.data.type}`, { logger.error(`Unsupported type: ${job.data.type}`, {
service: this.SERVICE_NAME, service: this.SERVICE_NAME,
method: "getStatus",
jobId: job.id, jobId: job.id,
}); });
return false; return false;
@@ -296,11 +301,13 @@ class NetworkService {
async logAndStoreCheck(data, writeToDB) { async logAndStoreCheck(data, writeToDB) {
try { try {
const insertedCheck = await writeToDB(data); const insertedCheck = await writeToDB(data);
return insertedCheck.status; if (insertedCheck !== null && insertedCheck !== undefined) {
return insertedCheck.status;
}
} catch (error) { } catch (error) {
console.log(error);
logger.error(`Error wrtiting check for ${data.monitorId}`, { logger.error(`Error wrtiting check for ${data.monitorId}`, {
service: this.SERVICE_NAME, service: this.SERVICE_NAME,
method: "logAndStoreCheck",
monitorId: data.monitorId, monitorId: data.monitorId,
error: error, error: error,
}); });
+13 -3
View File
@@ -24,7 +24,9 @@ class PageSpeedService {
service: this.SERVICE_NAME, service: this.SERVICE_NAME,
error: error.message, error: error.message,
}); });
throw new Error("Failed to run PageSpeed check"); error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "runPageSpeedCheck") : null;
throw error;
} }
} }
@@ -34,8 +36,16 @@ class PageSpeedService {
* @returns {Promise<PageSpeedCheck>} The created PageSpeedCheck document. * @returns {Promise<PageSpeedCheck>} The created PageSpeedCheck document.
*/ */
async createPageSpeedCheck(data) { async createPageSpeedCheck(data) {
const newPageSpeedCheck = new PageSpeedCheck(data); try {
return await newPageSpeedCheck.save(); const newPageSpeedCheck = new PageSpeedCheck(data);
return await newPageSpeedCheck.save();
} catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined
? (error.method = "createPageSpeedCheck")
: null;
throw error;
}
} }
} }
File diff suppressed because it is too large. Load diff
+2
View File
@@ -73,6 +73,7 @@ const successMessages = {
CHECK_CREATE: "Check created successfully", CHECK_CREATE: "Check created successfully",
CHECK_GET: "Got checks successfully", CHECK_GET: "Got checks successfully",
CHECK_DELETE: "Checks deleted successfully", CHECK_DELETE: "Checks deleted successfully",
CHECK_UPDATE_TTL: "Checks TTL updated successfully",
//Monitor Controller //Monitor Controller
MONITOR_GET_ALL: "Got all monitors successfully", MONITOR_GET_ALL: "Got all monitors successfully",
@@ -83,6 +84,7 @@ const successMessages = {
MONITOR_DELETE: "Monitor deleted successfully", MONITOR_DELETE: "Monitor deleted successfully",
MONITOR_EDIT: "Monitor edited successfully", MONITOR_EDIT: "Monitor edited successfully",
MONITOR_CERTIFICATE: "Got monitor certificate successfully", MONITOR_CERTIFICATE: "Got monitor certificate successfully",
MONITOR_DEMO_ADDED: "Successfully added demo monitors",
//Job Queue //Job Queue
JOB_QUEUE_DELETE_JOB: "Job removed successfully", JOB_QUEUE_DELETE_JOB: "Job removed successfully",
+12
View File
@@ -16,6 +16,18 @@ const ParseBoolean = (value) => {
} }
}; };
const getTokenFromHeaders = (headers) => {
const authorizationHeader = headers.authorization;
if (!authorizationHeader) throw new Error("No auth headers");
const parts = authorizationHeader.split(" ");
if (parts.length !== 2 || parts[0] !== "Bearer")
throw new Error("Invalid auth headers");
return parts[1];
};
module.exports = { module.exports = {
ParseBoolean, ParseBoolean,
getTokenFromHeaders,
}; };
+9 -1
View File
@@ -180,7 +180,7 @@ const getMonitorsByTeamIdValidation = joi.object({
const getMonitorsByTeamIdQueryValidation = joi.object({ const getMonitorsByTeamIdQueryValidation = joi.object({
status: joi.boolean(), status: joi.boolean(),
sortOrder: joi.string().valid("asc", "desc"), checkOrder: joi.string().valid("asc", "desc"),
limit: joi.number(), limit: joi.number(),
normalize: joi.boolean(), normalize: joi.boolean(),
type: joi type: joi
@@ -191,6 +191,9 @@ const getMonitorsByTeamIdQueryValidation = joi.object({
), ),
page: joi.number(), page: joi.number(),
rowsPerPage: joi.number(), rowsPerPage: joi.number(),
filter: joi.string(),
field: joi.string(),
order: joi.string().valid("asc", "desc"),
}); });
const getMonitorStatsByIdParamValidation = joi.object({ const getMonitorStatsByIdParamValidation = joi.object({
@@ -335,6 +338,10 @@ const deleteChecksByTeamIdParamValidation = joi.object({
teamId: joi.string().required(), teamId: joi.string().required(),
}); });
const updateChecksTTLBodyValidation = joi.object({
ttl: joi.number().required(),
});
//**************************************** //****************************************
// PageSpeedCheckValidation // PageSpeedCheckValidation
//**************************************** //****************************************
@@ -423,6 +430,7 @@ module.exports = {
getTeamChecksQueryValidation, getTeamChecksQueryValidation,
deleteChecksParamValidation, deleteChecksParamValidation,
deleteChecksByTeamIdParamValidation, deleteChecksByTeamIdParamValidation,
updateChecksTTLBodyValidation,
deleteUserParamValidation, deleteUserParamValidation,
getPageSpeedCheckParamValidation, getPageSpeedCheckParamValidation,
createPageSpeedCheckParamValidation, createPageSpeedCheckParamValidation,