resolving conflicts

This commit is contained in:
Caio Cabral committed 2024-10-18 18:47:21 -04:00
commit 1293a5f8ee
154 files changed
+2873 -3077

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@
"bracketSameLine": false, "bracketSameLine": false,
"singleAttributePerLine": true, "singleAttributePerLine": true,
"semi": true, "semi": true,
"jsx-single-quote": false, "jsxSingleQuote": false,
"quoteProps": "as-needed", "quoteProps": "as-needed",
"arrowParens": "always", "arrowParens": "always",
"trailingComma": "es5", "trailingComma": "es5",
+11 -14
View File
@@ -2,20 +2,17 @@ module.exports = {
root: true, root: true,
env: { browser: true, es2020: true }, env: { browser: true, es2020: true },
extends: [ extends: [
'eslint:recommended', "eslint:recommended",
'plugin:react/recommended', "plugin:react/recommended",
'plugin:react/jsx-runtime', "plugin:react/jsx-runtime",
'plugin:react-hooks/recommended', "plugin:react-hooks/recommended",
], ],
ignorePatterns: ['dist', '.eslintrc.cjs'], ignorePatterns: ["dist", ".eslintrc.cjs"],
parserOptions: { ecmaVersion: 'latest', sourceType: 'module' }, parserOptions: { ecmaVersion: "latest", sourceType: "module" },
settings: { react: { version: '18.2' } }, settings: { react: { version: "18.2" } },
plugins: ['react-refresh'], plugins: ["react-refresh"],
rules: { rules: {
'react/jsx-no-target-blank': 'off', "react/jsx-no-target-blank": "off",
'react-refresh/only-export-components': [ "react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
'warn',
{ allowConstantExport: true },
],
}, },
} };
+13 -4
View File
@@ -1,14 +1,23 @@
<!DOCTYPE html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" href="./bluewave_favicon.ico" /> <link
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> rel="icon"
href="./bluewave_favicon.ico"
/>
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<title>BlueWave Uptime</title> <title>BlueWave Uptime</title>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
<script type="module" src="/src/main.jsx"></script> <script
type="module"
src="/src/main.jsx"
></script>
</body> </body>
</html> </html>
+8 -10
View File
@@ -42,25 +42,23 @@ const Alert = ({ variant, title, body, isToast, hasIcon = true, onClick }) => {
className="alert row-stack" className="alert row-stack"
gap={theme.spacing(8)} gap={theme.spacing(8)}
sx={{ sx={{
padding: hasIcon padding: hasIcon ? theme.spacing(8) : `${theme.spacing(4)} ${theme.spacing(8)}`,
? theme.spacing(8)
: `${theme.spacing(4)} ${theme.spacing(8)}`,
backgroundColor: bg, backgroundColor: bg,
border: `solid 1px ${border}`, border: `solid 1px ${border}`,
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
}} }}
> >
{hasIcon && <Box sx={{ color: text }}>{icon}</Box>} {hasIcon && <Box sx={{ color: text }}>{icon}</Box>}
<Stack direction="column" gap="2px" sx={{ flex: 1 }}> <Stack
direction="column"
gap="2px"
sx={{ flex: 1 }}
>
{title && ( {title && (
<Typography sx={{ fontWeight: "700", color: `${text}` }}> <Typography sx={{ fontWeight: "700", color: `${text}` }}>{title}</Typography>
{title}
</Typography>
)} )}
{body && ( {body && (
<Typography sx={{ fontWeight: "400", color: `${text}` }}> <Typography sx={{ fontWeight: "400", color: `${text}` }}>{body}</Typography>
{body}
</Typography>
)} )}
{hasIcon && isToast && ( {hasIcon && isToast && (
<Button <Button
+1 -3
View File
@@ -52,9 +52,7 @@ const Avatar = ({ src, small, sx }) => {
return ( return (
<MuiAvatar <MuiAvatar
alt={`${user?.firstName} ${user?.lastName}`} alt={`${user?.firstName} ${user?.lastName}`}
src={ src={src ? src : user?.avatarImage ? image : "/static/images/avatar/2.jpg"}
src ? src : user?.avatarImage ? image : "/static/images/avatar/2.jpg"
}
sx={{ sx={{
fontSize: small ? "16px" : "22px", fontSize: small ? "16px" : "22px",
color: "white", color: "white",
+2 -5
View File
@@ -18,10 +18,7 @@
.MuiPaper-root:has(table.MuiTable-root) { .MuiPaper-root:has(table.MuiTable-root) {
box-shadow: none; box-shadow: none;
} }
.MuiTable-root .MuiTable-root .MuiTableBody-root .MuiTableRow-root:last-child .MuiTableCell-root {
.MuiTableBody-root
.MuiTableRow-root:last-child
.MuiTableCell-root {
border: none; border: none;
} }
@@ -120,7 +117,7 @@
opacity: 0.4; opacity: 0.4;
} }
.monitors .MuiTable-root .MuiTableHead-root .MuiTableCell-root { .table-container .MuiTable-root .MuiTableHead-root .MuiTableCell-root {
text-transform: uppercase; text-transform: uppercase;
opacity: 0.8; opacity: 0.8;
font-size: var(--env-var-font-size-small-plus); font-size: var(--env-var-font-size-small-plus);
+6 -5
View File
@@ -243,7 +243,11 @@ const BasicTable = ({ data, paginated, reversed, table }) => {
}, },
}} }}
> >
<Typography px={theme.spacing(2)} fontSize={12} sx={{ opacity: 0.7 }}> <Typography
px={theme.spacing(2)}
fontSize={12}
sx={{ opacity: 0.7 }}
>
Showing {getRange()} of {data.rows.length} monitor(s) Showing {getRange()} of {data.rows.length} monitor(s)
</Typography> </Typography>
<TablePagination <TablePagination
@@ -257,10 +261,7 @@ const BasicTable = ({ data, paginated, reversed, table }) => {
ActionsComponent={TablePaginationActions} ActionsComponent={TablePaginationActions}
labelRowsPerPage="Rows per page" labelRowsPerPage="Rows per page"
labelDisplayedRows={({ page, count }) => labelDisplayedRows={({ page, count }) =>
`Page ${page + 1} of ${Math.max( `Page ${page + 1} of ${Math.max(0, Math.ceil(count / rowsPerPage))}`
0,
Math.ceil(count / rowsPerPage)
)}`
} }
slotProps={{ slotProps={{
select: { select: {
@@ -65,9 +65,7 @@ const BarChart = ({ checks = [] }) => {
width={theme.spacing(4)} width={theme.spacing(4)}
height={theme.spacing(4)} height={theme.spacing(4)}
backgroundColor={ backgroundColor={
check.status check.status ? theme.palette.success.main : theme.palette.error.text
? theme.palette.success.main
: theme.palette.error.text
} }
sx={{ borderRadius: "50%" }} sx={{ borderRadius: "50%" }}
/> />
@@ -78,12 +76,18 @@ const BarChart = ({ checks = [] }) => {
ml={theme.spacing(2)} ml={theme.spacing(2)}
gap={theme.spacing(12)} gap={theme.spacing(12)}
> >
<Typography component="span" sx={{ opacity: 0.8 }}> <Typography
component="span"
sx={{ opacity: 0.8 }}
>
Response Time Response Time
</Typography> </Typography>
<Typography component="span"> <Typography component="span">
{check.originalResponseTime} {check.originalResponseTime}
<Typography component="span" sx={{ opacity: 0.8 }}> <Typography
component="span"
sx={{ opacity: 0.8 }}
>
{" "} {" "}
ms ms
</Typography> </Typography>
@@ -149,9 +153,7 @@ const BarChart = ({ checks = [] }) => {
width="100%" width="100%"
height={`${animate ? check.responseTime : 0}%`} height={`${animate ? check.responseTime : 0}%`}
backgroundColor={ backgroundColor={
check.status check.status ? theme.palette.success.main : theme.palette.error.text
? theme.palette.success.main
: theme.palette.error.text
} }
sx={{ sx={{
borderRadius: theme.spacing(1.5), borderRadius: theme.spacing(1.5),
@@ -62,12 +62,18 @@ const CustomToolTip = ({ active, payload, label }) => {
}, },
}} }}
> >
<Typography component="span" sx={{ opacity: 0.8 }}> <Typography
component="span"
sx={{ opacity: 0.8 }}
>
Response Time Response Time
</Typography>{" "} </Typography>{" "}
<Typography component="span"> <Typography component="span">
{payload[0].payload.originalResponseTime} {payload[0].payload.originalResponseTime}
<Typography component="span" sx={{ opacity: 0.8 }}> <Typography
component="span"
sx={{ opacity: 0.8 }}
>
{" "} {" "}
ms ms
</Typography> </Typography>
@@ -115,7 +121,11 @@ const MonitorDetailsAreaChart = ({ checks }) => {
const [isHovered, setIsHovered] = useState(false); const [isHovered, setIsHovered] = useState(false);
return ( return (
<ResponsiveContainer width="100%" minWidth={25} height={220}> <ResponsiveContainer
width="100%"
minWidth={25}
height={220}
>
<AreaChart <AreaChart
width="100%" width="100%"
height="100%" height="100%"
@@ -137,7 +147,13 @@ const MonitorDetailsAreaChart = ({ checks }) => {
vertical={false} vertical={false}
/> />
<defs> <defs>
<linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1"> <linearGradient
id="colorUv"
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop <stop
offset="0%" offset="0%"
stopColor={theme.palette.primary.main} stopColor={theme.palette.primary.main}
+1 -2
View File
@@ -50,8 +50,7 @@ const Check = ({ text, variant = "info", outlined = false }) => {
<Typography <Typography
component="span" component="span"
sx={{ sx={{
color: color: variant === "info" ? theme.palette.text.tertiary : colors[variant],
variant === "info" ? theme.palette.text.tertiary : colors[variant],
opacity: 0.8, opacity: 0.8,
}} }}
> >
-1
View File
@@ -1 +0,0 @@
+103
View File
@@ -0,0 +1,103 @@
import LoadingButton from "@mui/lab/LoadingButton";
import { Button, Modal, Stack, Typography } from "@mui/material";
import PropTypes from "prop-types";
const Dialog = ({
modelTitle,
modelDescription,
open,
onClose,
title,
confirmationBtnLbl,
confirmationBtnOnClick,
cancelBtnLbl,
cancelBtnOnClick,
theme,
isLoading,
description,
}) => {
return (
<Modal
aria-labelledby={modelTitle}
aria-describedby={modelDescription}
open={open}
onClose={onClose}
>
<Stack
gap={theme.spacing(2)}
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
boxShadow: 24,
p: theme.spacing(15),
"&:focus": {
outline: "none",
},
}}
>
<Typography
id={modelTitle}
component="h2"
fontSize={16}
color={theme.palette.text.primary}
fontWeight={600}
>
{title}
</Typography>
{description && (
<Typography
id={modelDescription}
color={theme.palette.text.tertiary}
>
{description}
</Typography>
)}
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(12)}
justifyContent="flex-end"
>
<Button
variant="text"
color="info"
onClick={cancelBtnOnClick}
>
{cancelBtnLbl}
</Button>
<LoadingButton
variant="contained"
color="error"
loading={isLoading}
onClick={confirmationBtnOnClick}
>
{confirmationBtnLbl}
</LoadingButton>
</Stack>
</Stack>
</Modal>
);
};
Dialog.propTypes = {
modelTitle: PropTypes.string.isRequired,
modelDescription: PropTypes.string.isRequired,
open: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
title: PropTypes.string.isRequired,
confirmationBtnLbl: PropTypes.string.isRequired,
confirmationBtnOnClick: PropTypes.func.isRequired,
cancelBtnLbl: PropTypes.string.isRequired,
cancelBtnOnClick: PropTypes.func.isRequired,
theme: PropTypes.object.isRequired,
isLoading: PropTypes.bool.isRequired,
description: PropTypes.string,
};
export default Dialog;
+5 -1
View File
@@ -46,7 +46,11 @@ const Fallback = ({ title, checks, link = "/", isAdmin }) => {
> >
<Background style={{ width: "100%" }} /> <Background style={{ width: "100%" }} />
</Box> </Box>
<Stack gap={theme.spacing(4)} maxWidth={"275px"} zIndex={1}> <Stack
gap={theme.spacing(4)}
maxWidth={"275px"}
zIndex={1}
>
<Typography <Typography
component="h1" component="h1"
marginY={theme.spacing(4)} marginY={theme.spacing(4)}
+3 -18
View File
@@ -1,13 +1,7 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { forwardRef, useState } from "react"; import { forwardRef, useState } from "react";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { import { IconButton, InputAdornment, Stack, TextField, Typography } from "@mui/material";
IconButton,
InputAdornment,
Stack,
TextField,
Typography,
} from "@mui/material";
import VisibilityOff from "@mui/icons-material/VisibilityOff"; import VisibilityOff from "@mui/icons-material/VisibilityOff";
import Visibility from "@mui/icons-material/Visibility"; import Visibility from "@mui/icons-material/Visibility";
import "./index.css"; import "./index.css";
@@ -142,9 +136,7 @@ const Field = forwardRef(
borderBottomLeftRadius: theme.shape.borderRadius, borderBottomLeftRadius: theme.shape.borderRadius,
}, },
} }
: { : {}
}
} }
InputProps={{ InputProps={{
startAdornment: type === "url" && ( startAdornment: type === "url" && (
@@ -212,14 +204,7 @@ const Field = forwardRef(
Field.displayName = "Field"; Field.displayName = "Field";
Field.propTypes = { Field.propTypes = {
type: PropTypes.oneOf([ type: PropTypes.oneOf(["text", "password", "url", "email", "description", "number"]),
"text",
"password",
"url",
"email",
"description",
"number",
]),
id: PropTypes.string.isRequired, id: PropTypes.string.isRequired,
name: PropTypes.string, name: PropTypes.string,
label: PropTypes.string, label: PropTypes.string,
+8 -2
View File
@@ -92,7 +92,10 @@ const ImageField = ({ id, src, loading, onChange }) => {
> >
<CloudUploadIcon /> <CloudUploadIcon />
</IconButton> </IconButton>
<Typography component="h2" color={theme.palette.text.tertiary}> <Typography
component="h2"
color={theme.palette.text.tertiary}
>
<Typography <Typography
component="span" component="span"
fontSize="inherit" fontSize="inherit"
@@ -121,7 +124,10 @@ const ImageField = ({ id, src, loading, onChange }) => {
</Typography> </Typography>
</> </>
) : ( ) : (
<Stack direction="row" justifyContent="center"> <Stack
direction="row"
justifyContent="center"
>
<Box <Box
sx={{ sx={{
width: "250px", width: "250px",
@@ -1 +0,0 @@
@@ -1,11 +1,6 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { import { MenuItem, Select as MuiSelect, Stack, Typography } from "@mui/material";
MenuItem,
Select as MuiSelect,
Stack,
Typography,
} from "@mui/material";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown"; import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import "./index.css"; import "./index.css";
@@ -63,7 +58,10 @@ const Select = ({
}; };
return ( return (
<Stack gap={theme.spacing(2)} className="select-wrapper"> <Stack
gap={theme.spacing(2)}
className="select-wrapper"
>
{label && ( {label && (
<Typography <Typography
component="h3" component="h3"
+2 -11
View File
@@ -86,10 +86,7 @@ const lightenColor = (color, percent) => {
const ColoredLabel = ({ label, color }) => { const ColoredLabel = ({ label, color }) => {
const theme = useTheme(); const theme = useTheme();
// If an invalid color is passed, default to the labelGray color // If an invalid color is passed, default to the labelGray color
if ( if (typeof color !== "string" || !/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(color)) {
typeof color !== "string" ||
!/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(color)
) {
color = theme.palette.border.light; color = theme.palette.border.light;
} }
@@ -180,13 +177,7 @@ const StatusLabel = ({ status, text, customStyles }) => {
}; };
StatusLabel.propTypes = { StatusLabel.propTypes = {
status: PropTypes.oneOf([ status: PropTypes.oneOf(["up", "down", "paused", "pending", "cannot resolve"]),
"up",
"down",
"paused",
"pending",
"cannot resolve",
]),
text: PropTypes.string, text: PropTypes.string,
customStyles: PropTypes.object, customStyles: PropTypes.object,
}; };
+14 -18
View File
@@ -1,13 +1,7 @@
import React from "react"; import React from "react";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { import { Box, IconButton, LinearProgress, Stack, Typography } from "@mui/material";
Box,
IconButton,
LinearProgress,
Stack,
Typography,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close"; import CloseIcon from "@mui/icons-material/Close";
import ErrorOutlineOutlinedIcon from "@mui/icons-material/ErrorOutlineOutlined"; import ErrorOutlineOutlinedIcon from "@mui/icons-material/ErrorOutlineOutlined";
import "./index.css"; import "./index.css";
@@ -23,14 +17,7 @@ import "./index.css";
* @returns {JSX.Element} The rendered component. * @returns {JSX.Element} The rendered component.
*/ */
const ProgressUpload = ({ const ProgressUpload = ({ icon, label, size, progress = 0, onClick, error }) => {
icon,
label,
size,
progress = 0,
onClick,
error,
}) => {
const theme = useTheme(); const theme = useTheme();
return ( return (
@@ -104,10 +91,16 @@ const ProgressUpload = ({
</Typography> </Typography>
) : ( ) : (
<Box color={theme.palette.text.tertiary}> <Box color={theme.palette.text.tertiary}>
<Typography component="h2" mb={theme.spacing(1.5)}> <Typography
component="h2"
mb={theme.spacing(1.5)}
>
{error ? error : label} {error ? error : label}
</Typography> </Typography>
<Typography component="p" sx={{ opacity: 0.6 }}> <Typography
component="p"
sx={{ opacity: 0.6 }}
>
{!error && size} {!error && size}
</Typography> </Typography>
</Box> </Box>
@@ -142,7 +135,10 @@ const ProgressUpload = ({
</IconButton> </IconButton>
</Stack> </Stack>
{!error ? ( {!error ? (
<Stack direction="row" alignItems="center"> <Stack
direction="row"
alignItems="center"
>
<Box sx={{ width: "100%", mr: theme.spacing(5) }}> <Box sx={{ width: "100%", mr: theme.spacing(5) }}>
<LinearProgress <LinearProgress
variant="determinate" variant="determinate"
@@ -27,11 +27,17 @@ CustomStepIcon.propTypes = {
const ProgressStepper = ({ steps }) => { const ProgressStepper = ({ steps }) => {
const [activeStep, setActiveStep] = React.useState(1); const [activeStep, setActiveStep] = React.useState(1);
return ( return (
<Stepper activeStep={activeStep} alternativeLabel> <Stepper
activeStep={activeStep}
alternativeLabel
>
{steps.map((step, index) => { {steps.map((step, index) => {
const color = activeStep === index ? "primary" : "inherit"; const color = activeStep === index ? "primary" : "inherit";
return ( return (
<Step key={step.label} onClick={() => setActiveStep(index)}> <Step
key={step.label}
onClick={() => setActiveStep(index)}
>
<StepLabel StepIconComponent={CustomStepIcon}> <StepLabel StepIconComponent={CustomStepIcon}>
<Typography <Typography
variant="body1" variant="body1"
@@ -41,7 +47,10 @@ const ProgressStepper = ({ steps }) => {
{step.label} {step.label}
</Typography> </Typography>
</StepLabel> </StepLabel>
<Typography variant="body1" color={color}> <Typography
variant="body1"
color={color}
>
{step.content} {step.content}
</Typography> </Typography>
</Step> </Step>
@@ -19,7 +19,10 @@ const ProtectedRoute = ({ Component, ...rest }) => {
return authState.authToken ? ( return authState.authToken ? (
<Component {...rest} /> <Component {...rest} />
) : ( ) : (
<Navigate to="/login" replace /> <Navigate
to="/login"
replace
/>
); );
}; };
+37 -26
View File
@@ -172,8 +172,16 @@ function Sidebar() {
}, },
}} }}
> >
<Stack pt={theme.spacing(6)} pb={theme.spacing(12)} pl={theme.spacing(8)}> <Stack
<Stack direction="row" alignItems="center" gap={theme.spacing(4)}> pt={theme.spacing(6)}
pb={theme.spacing(12)}
pl={theme.spacing(8)}
>
<Stack
direction="row"
alignItems="center"
gap={theme.spacing(4)}
>
<Stack <Stack
justifyContent="center" justifyContent="center"
alignItems="center" alignItems="center"
@@ -223,9 +231,9 @@ function Sidebar() {
}, },
}} }}
onClick={() => { onClick={() => {
setOpen(prev => setOpen((prev) =>
Object.fromEntries(Object.keys(prev).map(key => [key, false])) Object.fromEntries(Object.keys(prev).map((key) => [key, false]))
) );
dispatch(toggleSidebar()); dispatch(toggleSidebar());
}} }}
> >
@@ -273,9 +281,7 @@ function Sidebar() {
disableInteractive disableInteractive
> >
<ListItemButton <ListItemButton
className={ className={location.pathname.includes(item.path) ? "selected-path" : ""}
location.pathname.includes(item.path) ? "selected-path" : ""
}
onClick={() => navigate(`/${item.path}`)} onClick={() => navigate(`/${item.path}`)}
sx={{ sx={{
height: "37px", height: "37px",
@@ -309,9 +315,7 @@ function Sidebar() {
> >
<ListItemButton <ListItemButton
className={ className={
Boolean(anchorEl) && popup === item.name Boolean(anchorEl) && popup === item.name ? "selected-path" : ""
? "selected-path"
: ""
} }
onClick={(event) => openPopup(event, item.name)} onClick={(event) => openPopup(event, item.name)}
sx={{ sx={{
@@ -363,9 +367,7 @@ function Sidebar() {
return ( return (
<MenuItem <MenuItem
className={ className={
location.pathname.includes(child.path) location.pathname.includes(child.path) ? "selected-path" : ""
? "selected-path"
: ""
} }
key={child.path} key={child.path}
onClick={() => { onClick={() => {
@@ -400,8 +402,8 @@ function Sidebar() {
<ListItemButton <ListItemButton
onClick={() => onClick={() =>
setOpen((prev) => ({ setOpen((prev) => ({
...Object.fromEntries(Object.keys(prev).map(key => [key, false])), ...Object.fromEntries(Object.keys(prev).map((key) => [key, false])),
[item.name]: !prev[item.name] [item.name]: !prev[item.name],
})) }))
} }
sx={{ sx={{
@@ -414,7 +416,10 @@ function Sidebar() {
<ListItemText>{item.name}</ListItemText> <ListItemText>{item.name}</ListItemText>
{open[`${item.name}`] ? <ArrowUp /> : <ArrowDown />} {open[`${item.name}`] ? <ArrowUp /> : <ArrowDown />}
</ListItemButton> </ListItemButton>
<Collapse in={open[`${item.name}`]} timeout="auto"> <Collapse
in={open[`${item.name}`]}
timeout="auto"
>
<List <List
component="div" component="div"
disablePadding disablePadding
@@ -432,9 +437,7 @@ function Sidebar() {
return ( return (
<ListItemButton <ListItemButton
className={ className={
location.pathname.includes(child.path) location.pathname.includes(child.path) ? "selected-path" : ""
? "selected-path"
: ""
} }
key={child.path} key={child.path}
onClick={() => { onClick={() => {
@@ -477,9 +480,7 @@ function Sidebar() {
}, },
}} }}
> >
<ListItemIcon sx={{ minWidth: 0 }}> <ListItemIcon sx={{ minWidth: 0 }}>{child.icon}</ListItemIcon>
{child.icon}
</ListItemIcon>
<ListItemText>{child.name}</ListItemText> <ListItemText>{child.name}</ListItemText>
</ListItemButton> </ListItemButton>
); );
@@ -531,14 +532,20 @@ function Sidebar() {
<> <>
<Avatar small={true} /> <Avatar small={true} />
<Box ml={theme.spacing(2)}> <Box ml={theme.spacing(2)}>
<Typography component="span" fontWeight={500}> <Typography
component="span"
fontWeight={500}
>
{authState.user?.firstName} {authState.user?.lastName} {authState.user?.firstName} {authState.user?.lastName}
</Typography> </Typography>
<Typography sx={{ textTransform: "capitalize" }}> <Typography sx={{ textTransform: "capitalize" }}>
{authState.user?.role} {authState.user?.role}
</Typography> </Typography>
</Box> </Box>
<Tooltip title="Controls" disableInteractive> <Tooltip
title="Controls"
disableInteractive
>
<IconButton <IconButton
sx={{ sx={{
ml: "auto", ml: "auto",
@@ -593,7 +600,11 @@ function Sidebar() {
{collapsed && ( {collapsed && (
<MenuItem sx={{ cursor: "default", minWidth: "150px" }}> <MenuItem sx={{ cursor: "default", minWidth: "150px" }}>
<Box mb={theme.spacing(2)}> <Box mb={theme.spacing(2)}>
<Typography component="span" fontWeight={500} fontSize={13}> <Typography
component="span"
fontWeight={500}
fontSize={13}
>
{authState.user?.firstName} {authState.user?.lastName} {authState.user?.firstName} {authState.user?.lastName}
</Typography> </Typography>
<Typography sx={{ textTransform: "capitalize", fontSize: 12 }}> <Typography sx={{ textTransform: "capitalize", fontSize: 12 }}>
@@ -171,7 +171,10 @@ const PasswordPanel = () => {
/> />
</Box> </Box>
</Stack> </Stack>
<Stack direction="row" justifyContent="flex-end"> <Stack
direction="row"
justifyContent="flex-end"
>
<LoadingButton <LoadingButton
variant="contained" variant="contained"
color="primary" color="primary"
@@ -7,11 +7,7 @@ import Field from "../../Inputs/Field";
import ImageField from "../../Inputs/Image"; import ImageField from "../../Inputs/Image";
import { credentials, imageValidation } from "../../../Validation/validation"; import { credentials, imageValidation } from "../../../Validation/validation";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { import { clearAuthState, deleteUser, update } from "../../../Features/Auth/authSlice";
clearAuthState,
deleteUser,
update,
} from "../../../Features/Auth/authSlice";
import ImageIcon from "@mui/icons-material/Image"; import ImageIcon from "@mui/icons-material/Image";
import ProgressUpload from "../../ProgressBars"; import ProgressUpload from "../../ProgressBars";
import { formatBytes } from "../../../Utils/fileUtils"; import { formatBytes } from "../../../Utils/fileUtils";
@@ -69,10 +65,7 @@ const ProfilePanel = () => {
// Handles image file // Handles image file
const handlePicture = (event) => { const handlePicture = (event) => {
const pic = event.target.files[0]; const pic = event.target.files[0];
let error = validateField( let error = validateField({ type: pic.type, size: pic.size }, imageValidation);
{ type: pic.type, size: pic.size },
imageValidation
);
if (error) return; if (error) return;
setProgress((prev) => ({ ...prev, isLoading: true })); setProgress((prev) => ({ ...prev, isLoading: true }));
@@ -259,7 +252,10 @@ const ProfilePanel = () => {
<Stack direction="row"> <Stack direction="row">
<Stack flex={0.9}> <Stack flex={0.9}>
<Typography component="h1">Email</Typography> <Typography component="h1">Email</Typography>
<Typography component="p" sx={{ opacity: 0.6 }}> <Typography
component="p"
sx={{ opacity: 0.6 }}
>
This is your current email address — it cannot be changed. This is your current email address — it cannot be changed.
</Typography> </Typography>
</Stack> </Stack>
@@ -276,11 +272,18 @@ const ProfilePanel = () => {
<Stack direction="row"> <Stack direction="row">
<Stack flex={0.9}> <Stack flex={0.9}>
<Typography component="h1">Your photo</Typography> <Typography component="h1">Your photo</Typography>
<Typography component="p" sx={{ opacity: 0.6 }}> <Typography
component="p"
sx={{ opacity: 0.6 }}
>
This photo will be displayed in your profile page. This photo will be displayed in your profile page.
</Typography> </Typography>
</Stack> </Stack>
<Stack direction="row" alignItems="center" flex={1}> <Stack
direction="row"
alignItems="center"
flex={1}
>
<Avatar <Avatar
src={ src={
localData?.deleteProfileImage localData?.deleteProfileImage
@@ -291,10 +294,18 @@ const ProfilePanel = () => {
} }
sx={{ mr: "8px" }} sx={{ mr: "8px" }}
/> />
<Button variant="text" color="info" onClick={handleDeletePicture}> <Button
variant="text"
color="info"
onClick={handleDeletePicture}
>
Delete Delete
</Button> </Button>
<Button variant="text" color="primary" onClick={openPictureModal}> <Button
variant="text"
color="primary"
onClick={openPictureModal}
>
Update Update
</Button> </Button>
</Stack> </Stack>
@@ -306,7 +317,10 @@ const ProfilePanel = () => {
marginY: theme.spacing(1), marginY: theme.spacing(1),
}} }}
/> />
<Stack direction="row" justifyContent="flex-end"> <Stack
direction="row"
justifyContent="flex-end"
>
<Box width="fit-content"> <Box width="fit-content">
<LoadingButton <LoadingButton
variant="contained" variant="contained"
@@ -314,9 +328,7 @@ const ProfilePanel = () => {
onClick={handleSaveProfile} onClick={handleSaveProfile}
loading={isLoading} loading={isLoading}
loadingIndicator="Saving..." loadingIndicator="Saving..."
disabled={ disabled={Object.keys(errors).length !== 0 && !errors?.picture && true}
Object.keys(errors).length !== 0 && !errors?.picture && true
}
sx={{ px: theme.spacing(12) }} sx={{ px: theme.spacing(12) }}
> >
Save Save
@@ -332,12 +344,19 @@ const ProfilePanel = () => {
}} }}
/> />
{!user.role.includes("demo") && ( {!user.role.includes("demo") && (
<Box component="form" noValidate spellCheck="false"> <Box
component="form"
noValidate
spellCheck="false"
>
<Box mb={theme.spacing(6)}> <Box mb={theme.spacing(6)}>
<Typography component="h1">Delete account</Typography> <Typography component="h1">Delete account</Typography>
<Typography component="p" sx={{ opacity: 0.6 }}> <Typography
Note that deleting your account will remove all data from our component="p"
system. This is permanent and non-recoverable. sx={{ opacity: 0.6 }}
>
Note that deleting your account will remove all data from our system. This
is permanent and non-recoverable.
</Typography> </Typography>
</Box> </Box>
<Button <Button
@@ -376,13 +395,19 @@ const ProfilePanel = () => {
}, },
}} }}
> >
<Typography id="modal-delete-account" component="h1"> <Typography
id="modal-delete-account"
component="h1"
>
Really delete this account? Really delete this account?
</Typography> </Typography>
<Typography id="delete-account-confirmation" component="p"> <Typography
If you delete your account, you will no longer be able to sign in, id="delete-account-confirmation"
and all of your data will be deleted. Deleting your account is component="p"
permanent and non-recoverable action. >
If you delete your account, you will no longer be able to sign in, and all of
your data will be deleted. Deleting your account is permanent and
non-recoverable action.
</Typography> </Typography>
<Stack <Stack
direction="row" direction="row"
@@ -390,7 +415,11 @@ const ProfilePanel = () => {
mt={theme.spacing(5)} mt={theme.spacing(5)}
justifyContent="flex-end" justifyContent="flex-end"
> >
<Button variant="text" color="info" onClick={() => setIsOpen("")}> <Button
variant="text"
color="info"
onClick={() => setIsOpen("")}
>
Cancel Cancel
</Button> </Button>
<LoadingButton <LoadingButton
@@ -469,7 +498,11 @@ const ProfilePanel = () => {
gap={theme.spacing(5)} gap={theme.spacing(5)}
justifyContent="flex-end" justifyContent="flex-end"
> >
<Button variant="text" color="info" onClick={removePicture}> <Button
variant="text"
color="info"
onClick={removePicture}
>
Remove Remove
</Button> </Button>
<Button <Button
@@ -1,13 +1,6 @@
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import TabPanel from "@mui/lab/TabPanel"; import TabPanel from "@mui/lab/TabPanel";
import { import { Box, Button, ButtonGroup, Modal, Stack, Typography } from "@mui/material";
Box,
Button,
ButtonGroup,
Modal,
Stack,
Typography,
} from "@mui/material";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import Field from "../../Inputs/Field"; import Field from "../../Inputs/Field";
import { credentials } from "../../../Validation/validation"; import { credentials } from "../../../Validation/validation";
@@ -75,9 +68,7 @@ const TeamPanel = () => {
if (filter !== "all") if (filter !== "all")
team = members.filter((member) => { team = members.filter((member) => {
if (filter === "admin") { if (filter === "admin") {
return ( return member.role.includes("admin") || member.role.includes("superadmin");
member.role.includes("admin") || member.role.includes("superadmin")
);
} }
return member.role.includes(filter); return member.role.includes(filter);
}); });
@@ -158,10 +149,7 @@ const TeamPanel = () => {
email: value, email: value,
})); }));
const validation = credentials.validate( const validation = credentials.validate({ email: value }, { abortEarly: false });
{ email: value },
{ abortEarly: false }
);
setErrors((prev) => { setErrors((prev) => {
const updatedErrors = { ...prev }; const updatedErrors = { ...prev };
@@ -223,6 +211,7 @@ const TeamPanel = () => {
return ( return (
<TabPanel <TabPanel
className="team-panel table-container"
value="team" value="team"
sx={{ sx={{
"& h1": { "& h1": {
@@ -288,7 +277,10 @@ const TeamPanel = () => {
gap={theme.spacing(12)} gap={theme.spacing(12)}
> >
<Typography component="h1">Team members</Typography> <Typography component="h1">Team members</Typography>
<Stack direction="row" justifyContent="space-between"> <Stack
direction="row"
justifyContent="space-between"
>
<Stack <Stack
direction="row" direction="row"
alignItems="flex-end" alignItems="flex-end"
@@ -376,8 +368,7 @@ const TeamPanel = () => {
color={theme.palette.text.accent} color={theme.palette.text.accent}
sx={{ mt: theme.spacing(1), mb: theme.spacing(4) }} sx={{ mt: theme.spacing(1), mb: theme.spacing(4) }}
> >
When you add a new team member, they will get access to all When you add a new team member, they will get access to all monitors.
monitors.
</Typography> </Typography>
</Box> </Box>
<Field <Field
+10 -26
View File
@@ -11,9 +11,7 @@ const initialState = {
msg: null, msg: null,
}; };
export const register = createAsyncThunk( export const register = createAsyncThunk("auth/register", async (form, thunkApi) => {
"auth/register",
async (form, thunkApi) => {
try { try {
const res = await networkService.registerUser(form); const res = await networkService.registerUser(form);
return res.data; return res.data;
@@ -27,8 +25,7 @@ export const register = createAsyncThunk(
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} });
);
export const login = createAsyncThunk("auth/login", async (form, thunkApi) => { export const login = createAsyncThunk("auth/login", async (form, thunkApi) => {
try { try {
@@ -46,9 +43,7 @@ export const login = createAsyncThunk("auth/login", async (form, thunkApi) => {
} }
}); });
export const update = createAsyncThunk( export const update = createAsyncThunk("auth/update", async (data, thunkApi) => {
"auth/update",
async (data, thunkApi) => {
const { authToken: token, localData: form } = data; const { authToken: token, localData: form } = data;
const user = jwtDecode(token); const user = jwtDecode(token);
try { try {
@@ -63,8 +58,7 @@ export const update = createAsyncThunk(
}); });
fd.append("profileImage", imageResult.data); fd.append("profileImage", imageResult.data);
} }
form.deleteProfileImage && form.deleteProfileImage && fd.append("deleteProfileImage", form.deleteProfileImage);
fd.append("deleteProfileImage", form.deleteProfileImage);
const res = await networkService.updateUser({ const res = await networkService.updateUser({
authToken: token, authToken: token,
@@ -82,12 +76,9 @@ export const update = createAsyncThunk(
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} });
);
export const deleteUser = createAsyncThunk( export const deleteUser = createAsyncThunk("auth/delete", async (data, thunkApi) => {
"auth/delete",
async (data, thunkApi) => {
const user = jwtDecode(data); const user = jwtDecode(data);
try { try {
@@ -106,8 +97,7 @@ export const deleteUser = createAsyncThunk(
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} });
);
export const forgotPassword = createAsyncThunk( export const forgotPassword = createAsyncThunk(
"auth/forgotPassword", "auth/forgotPassword",
@@ -162,9 +152,7 @@ const handleAuthFulfilled = (state, action) => {
const handleAuthRejected = (state, action) => { const handleAuthRejected = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload ? action.payload.msg : "Failed to login or register";
? action.payload.msg
: "Failed to login or register";
}; };
const handleUpdateFulfilled = (state, action) => { const handleUpdateFulfilled = (state, action) => {
state.isLoading = false; state.isLoading = false;
@@ -175,9 +163,7 @@ const handleUpdateFulfilled = (state, action) => {
const handleUpdateRejected = (state, action) => { const handleUpdateRejected = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload ? action.payload.msg : "Failed to update profile data.";
? action.payload.msg
: "Failed to update profile data.";
}; };
const handleDeleteFulfilled = (state, action) => { const handleDeleteFulfilled = (state, action) => {
state.isLoading = false; state.isLoading = false;
@@ -197,9 +183,7 @@ const handleForgotFulfilled = (state, action) => {
const handleForgotRejected = (state, action) => { const handleForgotRejected = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload ? action.payload.msg : "Failed to send reset instructions.";
? action.payload.msg
: "Failed to send reset instructions.";
}; };
const handleNewPasswordRejected = (state, action) => { const handleNewPasswordRejected = (state, action) => {
state.isLoading = false; state.isLoading = false;
@@ -89,9 +89,7 @@ const handleUpdateSettingsFulfilled = (state, action) => {
const handleUpdateSettingsRejected = (state, action) => { const handleUpdateSettingsRejected = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload ? action.payload.msg : "Failed to update settings.";
? action.payload.msg
: "Failed to update settings.";
}; };
const settingsSlice = createSlice({ const settingsSlice = createSlice({
+2 -7
View File
@@ -47,10 +47,5 @@ const uiSlice = createSlice({
}); });
export default uiSlice.reducer; export default uiSlice.reducer;
export const { export const { setRowsPerPage, toggleSidebar, setMode, setGreeting, setTimezone } =
setRowsPerPage, uiSlice.actions;
toggleSidebar,
setMode,
setGreeting,
setTimezone,
} = uiSlice.actions;
@@ -284,9 +284,7 @@ const uptimeMonitorsSlice = createSlice({
.addCase(getUptimeMonitorById.rejected, (state, action) => { .addCase(getUptimeMonitorById.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload ? action.payload.msg : "Failed to get uptime monitor";
? action.payload.msg
: "Failed to get uptime monitor";
}) })
// ***************************************************** // *****************************************************
// update Monitor // update Monitor
@@ -393,14 +391,11 @@ const uptimeMonitorsSlice = createSlice({
.addCase(deleteAllMonitors.rejected, (state, action) => { .addCase(deleteAllMonitors.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload ? action.payload.msg : "Failed to delete all monitors";
? action.payload.msg
: "Failed to delete all monitors";
}); });
}, },
}); });
export const { setUptimeMonitors, clearUptimeMonitorState } = export const { setUptimeMonitors, clearUptimeMonitorState } = uptimeMonitorsSlice.actions;
uptimeMonitorsSlice.actions;
export default uptimeMonitorsSlice.reducer; export default uptimeMonitorsSlice.reducer;
+6 -1
View File
@@ -20,7 +20,12 @@ const withAdminCheck = (WrappedComponent) => {
logger.error(error); logger.error(error);
}); });
}, [navigate]); }, [navigate]);
return <WrappedComponent {...props} isSuperAdmin={true} />; return (
<WrappedComponent
{...props}
isSuperAdmin={true}
/>
);
}; };
const wrappedComponentName = const wrappedComponentName =
WrappedComponent.displayName || WrappedComponent.name || "Component"; WrappedComponent.displayName || WrappedComponent.name || "Component";
+6 -1
View File
@@ -7,7 +7,12 @@ const withAdminProp = (WrappedComponent) => {
(user?.role?.includes("admin") ?? false) || (user?.role?.includes("admin") ?? false) ||
(user?.role?.includes("superadmin") ?? false); (user?.role?.includes("superadmin") ?? false);
return <WrappedComponent {...props} isAdmin={isAdmin} />; return (
<WrappedComponent
{...props}
isAdmin={isAdmin}
/>
);
}; };
const wrappedComponentName = const wrappedComponentName =
+5 -1
View File
@@ -6,7 +6,11 @@ import "./index.css";
const HomeLayout = () => { const HomeLayout = () => {
return ( return (
<Stack className="home-layout" flexDirection="row" gap={14}> <Stack
className="home-layout"
flexDirection="row"
gap={14}
>
<Sidebar /> <Sidebar />
<Outlet /> <Outlet />
</Stack> </Stack>
+4 -1
View File
@@ -54,7 +54,10 @@ const Account = ({ open = "profile" }) => {
"& .MuiTabs-root": { height: "fit-content", minHeight: "0" }, "& .MuiTabs-root": { height: "fit-content", minHeight: "0" },
}} }}
> >
<TabList onChange={handleTabChange} aria-label="account tabs"> <TabList
onChange={handleTabChange}
aria-label="account tabs"
>
{tabList.map((label, index) => ( {tabList.map((label, index) => (
<Tab <Tab
label={label} label={label}
+8 -10
View File
@@ -9,10 +9,7 @@ import PropTypes from "prop-types";
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import { ConfigBox } from "../Settings/styled"; import { ConfigBox } from "../Settings/styled";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
import { import { getAppSettings, updateAppSettings } from "../../Features/Settings/settingsSlice";
getAppSettings,
updateAppSettings,
} from "../../Features/Settings/settingsSlice";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import Select from "../../Components/Inputs/Select"; import Select from "../../Components/Inputs/Select";
@@ -136,8 +133,8 @@ const AdvancedSettings = ({ isAdmin }) => {
<Box> <Box>
<Typography component="h1">Email settings</Typography> <Typography component="h1">Email settings</Typography>
<Typography sx={{ mt: theme.spacing(2) }}> <Typography sx={{ mt: theme.spacing(2) }}>
Set your host email settings here. These settings are used for Set your host email settings here. These settings are used for sending
sending system emails. system emails.
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
@@ -231,9 +228,7 @@ const AdvancedSettings = ({ isAdmin }) => {
</Box> </Box>
<Box> <Box>
<Typography component="h2">BlueWave Uptime v1.0.0</Typography> <Typography component="h2">BlueWave Uptime v1.0.0</Typography>
<Typography <Typography sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }}>
sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }}
>
Developed by Bluewave Labs. Developed by Bluewave Labs.
</Typography> </Typography>
<Link <Link
@@ -243,7 +238,10 @@ const AdvancedSettings = ({ isAdmin }) => {
/> />
</Box> </Box>
</ConfigBox> </ConfigBox>
<Stack direction="row" justifyContent="flex-end"> <Stack
direction="row"
justifyContent="flex-end"
>
<LoadingButton <LoadingButton
loading={settings.isLoading || settings.authIsLoading} loading={settings.isLoading || settings.authIsLoading}
variant="contained" variant="contained"
+8 -2
View File
@@ -150,7 +150,10 @@ const CheckEmail = () => {
<Typography component="h1">Check your email</Typography> <Typography component="h1">Check your email</Typography>
<Typography> <Typography>
We sent a password reset link to{" "} We sent a password reset link to{" "}
<Typography className="email-sent-to" component="span"> <Typography
className="email-sent-to"
component="span"
>
{email || "username@email.com"} {email || "username@email.com"}
</Typography> </Typography>
</Typography> </Typography>
@@ -184,7 +187,10 @@ const CheckEmail = () => {
</Typography> </Typography>
</Stack> </Stack>
</Stack> </Stack>
<Box textAlign="center" p={theme.spacing(12)}> <Box
textAlign="center"
p={theme.spacing(12)}
>
<Typography display="inline-block">Go back to —</Typography> <Typography display="inline-block">Go back to —</Typography>
<Typography <Typography
component="span" component="span"
+6 -8
View File
@@ -73,10 +73,7 @@ const ForgotPassword = () => {
const { value } = event.target; const { value } = event.target;
setForm({ email: value }); setForm({ email: value });
const { error } = credentials.validate( const { error } = credentials.validate({ email: value }, { abortEarly: false });
{ email: value },
{ abortEarly: false }
);
if (error) setErrors({ email: error.details[0].message }); if (error) setErrors({ email: error.details[0].message });
else delete errors.email; else delete errors.email;
@@ -153,9 +150,7 @@ const ForgotPassword = () => {
<Key alt="password key icon" /> <Key alt="password key icon" />
</IconBox> </IconBox>
<Typography component="h1">Forgot password?</Typography> <Typography component="h1">Forgot password?</Typography>
<Typography> <Typography>No worries, we&apos;ll send you reset instructions.</Typography>
No worries, we&apos;ll send you reset instructions.
</Typography>
</Box> </Box>
<Box <Box
component="form" component="form"
@@ -191,7 +186,10 @@ const ForgotPassword = () => {
</Box> </Box>
</Stack> </Stack>
</Stack> </Stack>
<Box textAlign="center" p={theme.spacing(12)}> <Box
textAlign="center"
p={theme.spacing(12)}
>
<Typography display="inline-block">Go back to —</Typography> <Typography display="inline-block">Go back to —</Typography>
<Typography <Typography
component="span" component="span"
+33 -16
View File
@@ -137,8 +137,15 @@ const StepOne = ({ form, errors, onSubmit, onChange, onBack }) => {
<Typography component="h1">Log In</Typography> <Typography component="h1">Log In</Typography>
<Typography>Enter your email address</Typography> <Typography>Enter your email address</Typography>
</Box> </Box>
<Box textAlign="left" mb={theme.spacing(5)}> <Box
<form noValidate spellCheck={false} onSubmit={onSubmit}> textAlign="left"
mb={theme.spacing(5)}
>
<form
noValidate
spellCheck={false}
onSubmit={onSubmit}
>
<Field <Field
type="email" type="email"
id="login-email-input" id="login-email-input"
@@ -154,7 +161,10 @@ const StepOne = ({ form, errors, onSubmit, onChange, onBack }) => {
/> />
</form> </form>
</Box> </Box>
<Stack direction="row" justifyContent="space-between"> <Stack
direction="row"
justifyContent="space-between"
>
<Button <Button
variant="outlined" variant="outlined"
color="info" color="info"
@@ -233,8 +243,15 @@ const StepTwo = ({ form, errors, onSubmit, onChange, onBack }) => {
<Typography component="h1">Log In</Typography> <Typography component="h1">Log In</Typography>
<Typography>Enter your password</Typography> <Typography>Enter your password</Typography>
</Box> </Box>
<Box textAlign="left" mb={theme.spacing(5)}> <Box
<form noValidate spellCheck={false} onSubmit={onSubmit}> textAlign="left"
mb={theme.spacing(5)}
>
<form
noValidate
spellCheck={false}
onSubmit={onSubmit}
>
<Field <Field
type="password" type="password"
id="login-password-input" id="login-password-input"
@@ -249,7 +266,10 @@ const StepTwo = ({ form, errors, onSubmit, onChange, onBack }) => {
/> />
</form> </form>
</Box> </Box>
<Stack direction="row" justifyContent="space-between"> <Stack
direction="row"
justifyContent="space-between"
>
<Button <Button
variant="outlined" variant="outlined"
color="info" color="info"
@@ -359,10 +379,7 @@ const Login = () => {
[name]: value, [name]: value,
})); }));
const { error } = credentials.validate( const { error } = credentials.validate({ [name]: value }, { abortEarly: false });
{ [name]: value },
{ abortEarly: false }
);
setErrors((prev) => { setErrors((prev) => {
const prevErrors = { ...prev }; const prevErrors = { ...prev };
@@ -413,8 +430,7 @@ const Login = () => {
if (action.payload) { if (action.payload) {
if (action.payload.msg === "Incorrect password") if (action.payload.msg === "Incorrect password")
setErrors({ setErrors({
password: password: "The password you provided does not match our records",
"The password you provided does not match our records",
}); });
// dispatch errors // dispatch errors
createToast({ createToast({
@@ -507,10 +523,11 @@ const Login = () => {
) )
)} )}
</Stack> </Stack>
<Box textAlign="center" p={theme.spacing(12)}> <Box
<Typography display="inline-block"> textAlign="center"
Don&apos;t have an account? — p={theme.spacing(12)}
</Typography> >
<Typography display="inline-block">Don&apos;t have an account? —</Typography>
<Typography <Typography
component="span" component="span"
color={theme.palette.primary.main} color={theme.palette.primary.main}
@@ -85,8 +85,7 @@ const NewPasswordConfirmed = () => {
</IconBox> </IconBox>
<Typography component="h1">Password reset</Typography> <Typography component="h1">Password reset</Typography>
<Typography mb={theme.spacing(2)}> <Typography mb={theme.spacing(2)}>
Your password has been successfully reset. Click below to log in Your password has been successfully reset. Click below to log in magically.
magically.
</Typography> </Typography>
</Box> </Box>
<Button <Button
@@ -102,7 +101,10 @@ const NewPasswordConfirmed = () => {
</Button> </Button>
</Stack> </Stack>
</Stack> </Stack>
<Box textAlign="center" p={theme.spacing(12)}> <Box
textAlign="center"
p={theme.spacing(12)}
>
<Typography display="inline-block">Go back to —</Typography> <Typography display="inline-block">Go back to —</Typography>
<Typography <Typography
component="span" component="span"
+25 -20
View File
@@ -38,8 +38,7 @@ const LandingPage = ({ isSuperAdmin, onSignup }) => {
<Box> <Box>
<Typography component="h1">Sign Up</Typography> <Typography component="h1">Sign Up</Typography>
<Typography> <Typography>
Create your {isSuperAdmin ? "Super admin " : ""}account to get Create your {isSuperAdmin ? "Super admin " : ""}account to get started.
started.
</Typography> </Typography>
</Box> </Box>
<Box width="100%"> <Box width="100%">
@@ -181,7 +180,10 @@ const StepOne = ({ form, errors, onSubmit, onChange, onBack }) => {
/> />
</Box> </Box>
</Box> </Box>
<Stack direction="row" justifyContent="space-between"> <Stack
direction="row"
justifyContent="space-between"
>
<Button <Button
variant="outlined" variant="outlined"
color="info" color="info"
@@ -274,7 +276,10 @@ const StepTwo = ({ form, errors, onSubmit, onChange, onBack }) => {
/> />
</Box> </Box>
</Box> </Box>
<Stack direction="row" justifyContent="space-between"> <Stack
direction="row"
justifyContent="space-between"
>
<Button <Button
variant="outlined" variant="outlined"
color="info" color="info"
@@ -396,8 +401,8 @@ const StepThree = ({ form, errors, onSubmit, onChange, onBack }) => {
<Check <Check
text={ text={
<> <>
<Typography component="span">Must be at least</Typography> 8 <Typography component="span">Must be at least</Typography> 8 characters
characters long long
</> </>
} }
variant={ variant={
@@ -413,8 +418,8 @@ const StepThree = ({ form, errors, onSubmit, onChange, onBack }) => {
<Check <Check
text={ text={
<> <>
<Typography component="span">Must contain</Typography> one <Typography component="span">Must contain</Typography> one special
special character and a number character and a number
</> </>
} }
variant={ variant={
@@ -422,9 +427,7 @@ const StepThree = ({ form, errors, onSubmit, onChange, onBack }) => {
? "error" ? "error"
: form.password === "" : form.password === ""
? "info" ? "info"
: !/^(?=.*[!@#$%^&*(),.?":{}|])(?=.*\d).+$/.test( : !/^(?=.*[!@#$%^&*(),.?":{}|])(?=.*\d).+$/.test(form.password)
form.password
)
? "error" ? "error"
: "success" : "success"
} }
@@ -432,10 +435,8 @@ const StepThree = ({ form, errors, onSubmit, onChange, onBack }) => {
<Check <Check
text={ text={
<> <>
<Typography component="span"> <Typography component="span">Must contain at least</Typography> one
Must contain at least upper and lower character
</Typography>{" "}
one upper and lower character
</> </>
} }
variant={ variant={
@@ -450,7 +451,10 @@ const StepThree = ({ form, errors, onSubmit, onChange, onBack }) => {
/> />
</Stack> </Stack>
</Box> </Box>
<Stack direction="row" justifyContent="space-between"> <Stack
direction="row"
justifyContent="space-between"
>
<Button <Button
variant="outlined" variant="outlined"
color="info" color="info"
@@ -738,10 +742,11 @@ const Register = ({ isSuperAdmin }) => {
"" ""
)} )}
</Stack> </Stack>
<Box textAlign="center" p={theme.spacing(12)}> <Box
<Typography display="inline-block"> textAlign="center"
Already have an account? — p={theme.spacing(12)}
</Typography> >
<Typography display="inline-block">Already have an account? —</Typography>
<Typography <Typography
component="span" component="span"
ml={theme.spacing(2)} ml={theme.spacing(2)}
+14 -14
View File
@@ -59,9 +59,7 @@ const SetNewPassword = () => {
}); });
} else { } else {
delete passwordForm.confirm; delete passwordForm.confirm;
const action = await dispatch( const action = await dispatch(setNewPassword({ token: token, form: passwordForm }));
setNewPassword({ token: token, form: passwordForm })
);
if (action.payload.success) { if (action.payload.success) {
navigate("/new-password-confirmed"); navigate("/new-password-confirmed");
createToast({ createToast({
@@ -217,7 +215,10 @@ const SetNewPassword = () => {
error={errors.confirm} error={errors.confirm}
/> />
</Box> </Box>
<Stack gap={theme.spacing(4)} mb={theme.spacing(12)}> <Stack
gap={theme.spacing(4)}
mb={theme.spacing(12)}
>
<Check <Check
text={ text={
<> <>
@@ -238,8 +239,8 @@ const SetNewPassword = () => {
<Check <Check
text={ text={
<> <>
<Typography component="span">Must contain</Typography> one <Typography component="span">Must contain</Typography> one special
special character and a number character and a number
</> </>
} }
variant={ variant={
@@ -247,9 +248,7 @@ const SetNewPassword = () => {
? "error" ? "error"
: form.password === "" : form.password === ""
? "info" ? "info"
: !/^(?=.*[!@#$%^&*(),.?":{}|])(?=.*\d).+$/.test( : !/^(?=.*[!@#$%^&*(),.?":{}|])(?=.*\d).+$/.test(form.password)
form.password
)
? "error" ? "error"
: "success" : "success"
} }
@@ -257,10 +256,8 @@ const SetNewPassword = () => {
<Check <Check
text={ text={
<> <>
<Typography component="span"> <Typography component="span">Must contain at least</Typography> one
Must contain at least upper and lower character
</Typography>{" "}
one upper and lower character
</> </>
} }
variant={ variant={
@@ -287,7 +284,10 @@ const SetNewPassword = () => {
</LoadingButton> </LoadingButton>
</Stack> </Stack>
</Stack> </Stack>
<Box textAlign="center" p={theme.spacing(12)}> <Box
textAlign="center"
p={theme.spacing(12)}
>
<Typography display="inline-block">Go back to —</Typography> <Typography display="inline-block">Go back to —</Typography>
<Typography <Typography
component="span" component="span"
+25 -5
View File
@@ -11,9 +11,21 @@ const SkeletonLayout = () => {
return ( return (
<> <>
<Stack direction="row" alignItems="center" gap={theme.spacing(6)}> <Stack
<Skeleton variant="rounded" width={150} height={34} /> direction="row"
<Skeleton variant="rounded" width="15%" height={34} /> alignItems="center"
gap={theme.spacing(6)}
>
<Skeleton
variant="rounded"
width={150}
height={34}
/>
<Skeleton
variant="rounded"
width="15%"
height={34}
/>
<Skeleton <Skeleton
variant="rounded" variant="rounded"
width="20%" width="20%"
@@ -21,8 +33,16 @@ const SkeletonLayout = () => {
sx={{ ml: "auto" }} sx={{ ml: "auto" }}
/> />
</Stack> </Stack>
<Skeleton variant="rounded" width="100%" height={300} /> <Skeleton
<Skeleton variant="rounded" width="100%" height={100} /> variant="rounded"
width="100%"
height={300}
/>
<Skeleton
variant="rounded"
width="100%"
height={100}
/>
</> </>
); );
}; };
+13 -3
View File
@@ -20,7 +20,11 @@ const IntegrationsComponent = ({ icon, header, info, onClick }) => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<Grid item lg={6} flexGrow={1}> <Grid
item
lg={6}
flexGrow={1}
>
<Stack <Stack
direction="row" direction="row"
justifyContent="space-between" justifyContent="space-between"
@@ -34,7 +38,10 @@ const IntegrationsComponent = ({ icon, header, info, onClick }) => {
backgroundColor={theme.palette.background.main} backgroundColor={theme.palette.background.main}
> >
{icon} {icon}
<Stack gap={theme.spacing(2)} flex={1}> <Stack
gap={theme.spacing(2)}
flex={1}
>
<Typography component="h1">{header}</Typography> <Typography component="h1">{header}</Typography>
<Typography <Typography
sx={{ sx={{
@@ -127,7 +134,10 @@ const Integrations = () => {
<Typography mb={theme.spacing(12)}> <Typography mb={theme.spacing(12)}>
Connect BlueWave Uptime to your favorite service. Connect BlueWave Uptime to your favorite service.
</Typography> </Typography>
<Grid container spacing={theme.spacing(12)}> <Grid
container
spacing={theme.spacing(12)}
>
{integrations.map((integration, index) => ( {integrations.map((integration, index) => (
<IntegrationsComponent <IntegrationsComponent
key={index} key={index}
@@ -310,8 +310,14 @@ const CreateMaintenance = () => {
mt={theme.spacing(6)} mt={theme.spacing(6)}
> >
<Box> <Box>
<Typography component="h1" variant="h1"> <Typography
<Typography component="span" fontSize="inherit"> component="h1"
variant="h1"
>
<Typography
component="span"
fontSize="inherit"
>
{`${maintenanceWindowId === undefined ? "Create a" : "Edit"}`}{" "} {`${maintenanceWindowId === undefined ? "Create a" : "Edit"}`}{" "}
</Typography> </Typography>
<Typography <Typography
@@ -322,16 +328,26 @@ const CreateMaintenance = () => {
> >
maintenance{" "} maintenance{" "}
</Typography> </Typography>
<Typography component="span" fontSize="inherit"> <Typography
component="span"
fontSize="inherit"
>
window window
</Typography> </Typography>
</Typography> </Typography>
<Typography component="h2" variant="body2" fontSize={14}> <Typography
component="h2"
variant="body2"
fontSize={14}
>
Your pings won&apos;t be sent during this time frame Your pings won&apos;t be sent during this time frame
</Typography> </Typography>
</Box> </Box>
<ConfigBox direction="row"> <ConfigBox direction="row">
<Typography component="h2" variant="h2"> <Typography
component="h2"
variant="h2"
>
General Settings General Settings
</Typography> </Typography>
<Box <Box
@@ -352,7 +368,10 @@ const CreateMaintenance = () => {
}} }}
items={repeatConfig} items={repeatConfig}
/> />
<Stack gap={theme.spacing(2)} mt={theme.spacing(16)}> <Stack
gap={theme.spacing(2)}
mt={theme.spacing(16)}
>
<Typography component="h3">Date</Typography> <Typography component="h3">Date</Typography>
<LocalizationProvider dateAdapter={AdapterDayjs}> <LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker <DatePicker
@@ -411,12 +430,13 @@ const CreateMaintenance = () => {
<ConfigBox> <ConfigBox>
<Stack direction="row"> <Stack direction="row">
<Box> <Box>
<Typography component="h2" variant="h2"> <Typography
component="h2"
variant="h2"
>
Start time Start time
</Typography> </Typography>
<Typography> <Typography>All dates and times are in GMT+0 time zone.</Typography>
All dates and times are in GMT+0 time zone.
</Typography>
</Box> </Box>
<Stack direction="row"> <Stack direction="row">
<LocalizationProvider dateAdapter={AdapterDayjs}> <LocalizationProvider dateAdapter={AdapterDayjs}>
@@ -457,11 +477,17 @@ const CreateMaintenance = () => {
</Stack> </Stack>
<Stack direction="row"> <Stack direction="row">
<Box> <Box>
<Typography component="h2" variant="h2"> <Typography
component="h2"
variant="h2"
>
Duration Duration
</Typography> </Typography>
</Box> </Box>
<Stack direction="row" spacing={theme.spacing(8)}> <Stack
direction="row"
spacing={theme.spacing(8)}
>
<Field <Field
type="number" type="number"
id="duration" id="duration"
@@ -498,7 +524,10 @@ const CreateMaintenance = () => {
<ConfigBox> <ConfigBox>
<Stack direction="row"> <Stack direction="row">
<Box> <Box>
<Typography component="h2" variant="h2"> <Typography
component="h2"
variant="h2"
>
Friendly name Friendly name
</Typography> </Typography>
</Box> </Box>
@@ -516,7 +545,10 @@ const CreateMaintenance = () => {
</Stack> </Stack>
<Stack direction="row"> <Stack direction="row">
<Box> <Box>
<Typography component="h2" variant="h2"> <Typography
component="h2"
variant="h2"
>
Add monitors Add monitors
</Typography> </Typography>
</Box> </Box>
@@ -539,7 +571,10 @@ const CreateMaintenance = () => {
</Stack> </Stack>
</ConfigBox> </ConfigBox>
</Box> </Box>
<Box ml="auto" display="inline-block"> <Box
ml="auto"
display="inline-block"
>
<Button <Button
variant="contained" variant="contained"
color="secondary" color="secondary"
@@ -183,7 +183,11 @@ const ActionsMenu = ({ isAdmin, maintenanceWindow, updateCallback }) => {
}, },
}} }}
> >
<Typography id="modal-delete-maintenance" component="h2" variant="h2"> <Typography
id="modal-delete-maintenance"
component="h2"
variant="h2"
>
Do you really want to remove this maintenance window? Do you really want to remove this maintenance window?
</Typography> </Typography>
<Stack <Stack
@@ -169,10 +169,7 @@ const MaintenanceTable = ({
*/ */
const getRange = () => { const getRange = () => {
let start = page * rowsPerPage + 1; let start = page * rowsPerPage + 1;
let end = Math.min( let end = Math.min(page * rowsPerPage + rowsPerPage, maintenanceWindowCount);
page * rowsPerPage + rowsPerPage,
maintenanceWindowCount
);
return `${start} - ${end}`; return `${start} - ${end}`;
}; };
@@ -221,8 +218,7 @@ const MaintenanceTable = ({
Status Status
<span <span
style={{ style={{
visibility: visibility: sort.field === "active" ? "visible" : "hidden",
sort.field === "active" ? "visible" : "hidden",
}} }}
> >
{sort.order === "asc" ? ( {sort.order === "asc" ? (
@@ -282,7 +278,11 @@ const MaintenanceTable = ({
justifyContent="space-between" justifyContent="space-between"
px={theme.spacing(4)} px={theme.spacing(4)}
> >
<Typography px={theme.spacing(2)} variant="body2" sx={{ opacity: 0.7 }}> <Typography
px={theme.spacing(2)}
variant="body2"
sx={{ opacity: 0.7 }}
>
Showing {getRange()} of {maintenanceWindowCount} maintenance window(s) Showing {getRange()} of {maintenanceWindowCount} maintenance window(s)
</Typography> </Typography>
<TablePagination <TablePagination
+1 -1
View File
@@ -45,7 +45,7 @@ const Maintenance = ({ isAdmin }) => {
return ( return (
<Box <Box
className="maintenance" className="maintenance table-container"
sx={{ sx={{
':has(> [class*="fallback__"])': { ':has(> [class*="fallback__"])': {
position: "relative", position: "relative",
+43 -88
View File
@@ -2,7 +2,7 @@ import { useNavigate, useParams } from "react-router";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Box, Button, Modal, Stack, Tooltip, Typography } from "@mui/material"; import { Box, Stack, Tooltip, Typography } from "@mui/material";
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";
@@ -24,6 +24,7 @@ import PulseDot from "../../../Components/Animated/PulseDot";
import SkeletonLayout from "./skeleton"; import SkeletonLayout from "./skeleton";
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import "./index.css"; import "./index.css";
import Dialog from "../../../Components/Dialog";
/** /**
* Parses a URL string and returns a URL object. * Parses a URL string and returns a URL object.
@@ -64,9 +65,7 @@ const Configure = () => {
useEffect(() => { useEffect(() => {
const fetchMonitor = async () => { const fetchMonitor = async () => {
try { try {
const action = await dispatch( const action = await dispatch(getUptimeMonitorById({ authToken, monitorId }));
getUptimeMonitorById({ authToken, monitorId })
);
if (getUptimeMonitorById.fulfilled.match(action)) { if (getUptimeMonitorById.fulfilled.match(action)) {
const monitor = action.payload.data; const monitor = action.payload.data;
@@ -128,8 +127,7 @@ const Configure = () => {
setErrors((prev) => { setErrors((prev) => {
const updatedErrors = { ...prev }; const updatedErrors = { ...prev };
if (validation.error) if (validation.error) updatedErrors[name] = validation.error.details[0].message;
updatedErrors[name] = validation.error.details[0].message;
else delete updatedErrors[name]; else delete updatedErrors[name];
return updatedErrors; return updatedErrors;
}); });
@@ -138,9 +136,7 @@ const Configure = () => {
const handlePause = async () => { const handlePause = async () => {
try { try {
const action = await dispatch( const action = await dispatch(pauseUptimeMonitor({ authToken, monitorId }));
pauseUptimeMonitor({ authToken, monitorId })
);
if (pauseUptimeMonitor.fulfilled.match(action)) { if (pauseUptimeMonitor.fulfilled.match(action)) {
const monitor = action.payload.data; const monitor = action.payload.data;
setMonitor(monitor); setMonitor(monitor);
@@ -155,9 +151,7 @@ const Configure = () => {
const handleSubmit = async (event) => { const handleSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
const action = await dispatch( const action = await dispatch(updateUptimeMonitor({ authToken, monitor: monitor }));
updateUptimeMonitor({ authToken, monitor: monitor })
);
if (action.meta.requestStatus === "fulfilled") { if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Monitor updated successfully!" }); createToast({ body: "Monitor updated successfully!" });
dispatch(getUptimeMonitorsByTeamId(authToken)); dispatch(getUptimeMonitorsByTeamId(authToken));
@@ -202,7 +196,10 @@ const Configure = () => {
}; };
return ( return (
<Stack className="configure-monitor" gap={theme.spacing(10)}> <Stack
className="configure-monitor"
gap={theme.spacing(10)}
>
{Object.keys(monitor).length === 0 ? ( {Object.keys(monitor).length === 0 ? (
<SkeletonLayout /> <SkeletonLayout />
) : ( ) : (
@@ -221,9 +218,15 @@ const Configure = () => {
gap={theme.spacing(12)} gap={theme.spacing(12)}
flex={1} flex={1}
> >
<Stack direction="row" gap={theme.spacing(2)}> <Stack
direction="row"
gap={theme.spacing(2)}
>
<Box> <Box>
<Typography component="h1" variant="h1"> <Typography
component="h1"
variant="h1"
>
{monitor.name} {monitor.name}
</Typography> </Typography>
<Stack <Stack
@@ -249,12 +252,13 @@ const Configure = () => {
}} }}
> >
<Box> <Box>
<PulseDot <PulseDot color={statusColor[monitor?.status ?? undefined]} />
color={statusColor[monitor?.status ?? undefined]}
/>
</Box> </Box>
</Tooltip> </Tooltip>
<Typography component="h2" variant="h2"> <Typography
component="h2"
variant="h2"
>
{monitor.url?.replace(/^https?:\/\//, "") || "..."} {monitor.url?.replace(/^https?:\/\//, "") || "..."}
</Typography> </Typography>
<Typography <Typography
@@ -334,8 +338,8 @@ const Configure = () => {
<Box> <Box>
<Typography component="h2">General settings</Typography> <Typography component="h2">General settings</Typography>
<Typography component="p"> <Typography component="p">
Here you can select the URL of the host, together with the Here you can select the URL of the host, together with the type of
type of monitor. monitor.
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
@@ -369,9 +373,7 @@ const Configure = () => {
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(6)}> <Stack gap={theme.spacing(6)}>
<Typography component="p"> <Typography component="p">When there is a new incident,</Typography>
When there is a new incident,
</Typography>
<Checkbox <Checkbox
id="notify-sms" id="notify-sms"
label="Notify via SMS (coming soon)" label="Notify via SMS (coming soon)"
@@ -433,7 +435,11 @@ const Configure = () => {
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
<Stack direction="row" justifyContent="flex-end" mt="auto"> <Stack
direction="row"
justifyContent="flex-end"
mt="auto"
>
<LoadingButton <LoadingButton
variant="contained" variant="contained"
color="primary" color="primary"
@@ -447,71 +453,20 @@ const Configure = () => {
</Stack> </Stack>
</> </>
)} )}
<Modal <Dialog
aria-labelledby="modal-delete-monitor" modelTitle="modal-delete-monitor"
aria-describedby="delete-monitor-confirmation" modelDescription="delete-monitor-confirmation"
open={isOpen} open={isOpen}
onClose={() => setIsOpen(false)} onClose={() => setIsOpen(false)}
disablePortal title="Do you really want to delete this monitor?"
> confirmationBtnLbl="Delete"
<Stack confirmationBtnOnClick={handleRemove}
gap={theme.spacing(2)} cancelBtnLbl="Cancel"
sx={{ cancelBtnOnClick={() => setIsOpen(false)}
position: "absolute", theme={theme}
top: "50%", isLoading={isLoading}
left: "50%", description="Once deleted, this monitor cannot be retrieved."
transform: "translate(-50%, -50%)", ></Dialog>
width: 400,
bgcolor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
boxShadow: 24,
p: theme.spacing(15),
"&:focus": {
outline: "none",
},
}}
>
<Typography
id="modal-delete-monitor"
component="h2"
fontSize={16}
color={theme.palette.text.primary}
fontWeight={600}
>
Do you really want to delete this monitor?
</Typography>
<Typography
id="delete-monitor-confirmation"
color={theme.palette.text.tertiary}
>
Once deleted, this monitor cannot be retrieved.
</Typography>
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(12)}
justifyContent="flex-end"
>
<Button
variant="text"
color="info"
onClick={() => setIsOpen(false)}
>
Cancel
</Button>
<LoadingButton
variant="contained"
color="error"
loading={isLoading}
onClick={handleRemove}
>
Delete
</LoadingButton>
</Stack>
</Stack>
</Modal>
</Stack> </Stack>
); );
}; };
@@ -11,9 +11,20 @@ const SkeletonLayout = () => {
return ( return (
<> <>
<Skeleton variant="rounded" width="15%" height={34} /> <Skeleton
<Stack gap={theme.spacing(20)} mt={theme.spacing(6)}> variant="rounded"
<Stack direction="row" gap={theme.spacing(4)} mt={theme.spacing(4)}> width="15%"
height={34}
/>
<Stack
gap={theme.spacing(20)}
mt={theme.spacing(6)}
>
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(4)}
>
<Skeleton <Skeleton
variant="circular" variant="circular"
style={{ minWidth: 24, minHeight: 24 }} style={{ minWidth: 24, minHeight: 24 }}
@@ -25,7 +36,11 @@ const SkeletonLayout = () => {
height={24} height={24}
sx={{ mb: theme.spacing(4) }} sx={{ mb: theme.spacing(4) }}
/> />
<Skeleton variant="rounded" width="50%" height={18} /> <Skeleton
variant="rounded"
width="50%"
height={18}
/>
</Box> </Box>
<Stack <Stack
direction="row" direction="row"
@@ -35,14 +50,37 @@ const SkeletonLayout = () => {
alignSelf: "flex-end", alignSelf: "flex-end",
}} }}
> >
<Skeleton variant="rounded" width={150} height={34} /> <Skeleton
variant="rounded"
width={150}
height={34}
/>
</Stack> </Stack>
</Stack> </Stack>
<Skeleton variant="rounded" width="100%" height={200} /> <Skeleton
<Skeleton variant="rounded" width="100%" height={200} /> variant="rounded"
<Skeleton variant="rounded" width="100%" height={200} /> width="100%"
<Stack direction="row" justifyContent="flex-end"> height={200}
<Skeleton variant="rounded" width="15%" height={34} /> />
<Skeleton
variant="rounded"
width="100%"
height={200}
/>
<Skeleton
variant="rounded"
width="100%"
height={200}
/>
<Stack
direction="row"
justifyContent="flex-end"
>
<Skeleton
variant="rounded"
width="15%"
height={34}
/>
</Stack> </Stack>
</Stack> </Stack>
</> </>
@@ -46,9 +46,7 @@ const CreateMonitor = () => {
useEffect(() => { useEffect(() => {
const fetchMonitor = async () => { const fetchMonitor = async () => {
if (monitorId) { if (monitorId) {
const action = await dispatch( const action = await dispatch(getUptimeMonitorById({ authToken, monitorId }));
getUptimeMonitorById({ authToken, monitorId })
);
if (action.payload.success) { if (action.payload.success) {
const data = action.payload.data; const data = action.payload.data;
@@ -155,9 +153,7 @@ const CreateMonitor = () => {
userId: user._id, userId: user._id,
notifications: monitor.notifications, notifications: monitor.notifications,
}; };
const action = await dispatch( const action = await dispatch(createUptimeMonitor({ authToken, monitor: form }));
createUptimeMonitor({ authToken, monitor: form })
);
if (action.meta.requestStatus === "fulfilled") { if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Monitor created successfully!" }); createToast({ body: "Monitor created successfully!" });
navigate("/monitors"); navigate("/monitors");
@@ -193,8 +189,14 @@ const CreateMonitor = () => {
gap={theme.spacing(12)} gap={theme.spacing(12)}
mt={theme.spacing(6)} mt={theme.spacing(6)}
> >
<Typography component="h1" variant="h1"> <Typography
<Typography component="span" fontSize="inherit"> component="h1"
variant="h1"
>
<Typography
component="span"
fontSize="inherit"
>
Create your{" "} Create your{" "}
</Typography> </Typography>
<Typography <Typography
@@ -210,8 +212,7 @@ const CreateMonitor = () => {
<Box> <Box>
<Typography component="h2">General settings</Typography> <Typography component="h2">General settings</Typography>
<Typography component="p"> <Typography component="p">
Here you can select the URL of the host, together with the type of Here you can select the URL of the host, together with the type of monitor.
monitor.
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(15)}> <Stack gap={theme.spacing(15)}>
@@ -368,7 +369,10 @@ const CreateMonitor = () => {
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
<Stack direction="row" justifyContent="flex-end"> <Stack
direction="row"
justifyContent="flex-end"
>
<Button <Button
variant="contained" variant="contained"
color="primary" color="primary"
@@ -13,27 +13,28 @@ import { memo, useMemo, useState } from "react";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { formatDateWithTz } from "../../../../Utils/timeUtils"; import { formatDateWithTz } from "../../../../Utils/timeUtils";
const CustomLabels = ({ const CustomLabels = ({ x, width, height, firstDataPoint, lastDataPoint, type }) => {
x,
width,
height,
firstDataPoint,
lastDataPoint,
type,
}) => {
const uiTimezone = useSelector((state) => state.ui.timezone); const uiTimezone = useSelector((state) => state.ui.timezone);
const dateFormat = type === "day" ? "MMM D, h:mm A" : "MMM D"; const dateFormat = type === "day" ? "MMM D, h:mm A" : "MMM D";
return ( return (
<> <>
<text x={x} y={height} dy={-3} textAnchor="start" fontSize={11}> <text
{formatDateWithTz( x={x}
new Date(firstDataPoint.time), y={height}
dateFormat, dy={-3}
uiTimezone textAnchor="start"
)} fontSize={11}
>
{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}
>
{formatDateWithTz(new Date(lastDataPoint.time), dateFormat, uiTimezone)} {formatDateWithTz(new Date(lastDataPoint.time), dateFormat, uiTimezone)}
</text> </text>
</> </>
@@ -67,7 +68,11 @@ const UpBarChart = memo(({ data, type, onBarHover }) => {
const reversedData = useMemo(() => [...data].reverse(), [data]); const reversedData = useMemo(() => [...data].reverse(), [data]);
return ( return (
<ResponsiveContainer width="100%" minWidth={210} height={155}> <ResponsiveContainer
width="100%"
minWidth={210}
height={155}
>
<BarChart <BarChart
width="100%" width="100%"
height="100%" height="100%"
@@ -108,9 +113,7 @@ const UpBarChart = memo(({ data, type, onBarHover }) => {
return ( return (
<Cell <Cell
key={`cell-${entry.time}`} key={`cell-${entry.time}`}
fill={ fill={hoveredBarIndex === index ? main : chartHovered ? light : main}
hoveredBarIndex === index ? main : chartHovered ? light : main
}
onMouseEnter={() => { onMouseEnter={() => {
setHoveredBarIndex(index); setHoveredBarIndex(index);
onBarHover(entry); onBarHover(entry);
@@ -153,7 +156,11 @@ const DownBarChart = memo(({ data, type, onBarHover }) => {
const reversedData = useMemo(() => [...data].reverse(), [data]); const reversedData = useMemo(() => [...data].reverse(), [data]);
return ( return (
<ResponsiveContainer width="100%" minWidth={250} height={155}> <ResponsiveContainer
width="100%"
minWidth={250}
height={155}
>
<BarChart <BarChart
width="100%" width="100%"
height="100%" height="100%"
@@ -260,7 +267,11 @@ const ResponseGaugeChart = ({ data }) => {
}; };
return ( return (
<ResponsiveContainer width="100%" minWidth={210} height={155}> <ResponsiveContainer
width="100%"
minWidth={210}
height={155}
>
<RadialBarChart <RadialBarChart
width="100%" width="100%"
height="100%" height="100%"
@@ -271,10 +282,24 @@ const ResponseGaugeChart = ({ data }) => {
innerRadius={100} innerRadius={100}
outerRadius={150} outerRadius={150}
> >
<text x={0} y="100%" dx="5%" dy={-2} textAnchor="start" fontSize={11}> <text
x={0}
y="100%"
dx="5%"
dy={-2}
textAnchor="start"
fontSize={11}
>
low low
</text> </text>
<text x="100%" y="100%" dx="-3%" dy={-2} textAnchor="end" fontSize={11}> <text
x="100%"
y="100%"
dx="-3%"
dy={-2}
textAnchor="end"
fontSize={11}
>
high high
</text> </text>
<text <text
@@ -294,8 +319,7 @@ const ResponseGaugeChart = ({ data }) => {
dominantBaseline="hanging" dominantBaseline="hanging"
fontSize={25} fontSize={25}
> >
<tspan fontWeight={600}>{responseTime}</tspan>{" "} <tspan fontWeight={600}>{responseTime}</tspan> <tspan opacity={0.8}>ms</tspan>
<tspan opacity={0.8}>ms</tspan>
</text> </text>
<RadialBar <RadialBar
background={{ fill: responseProps.bg }} background={{ fill: responseProps.bg }}
@@ -303,7 +327,11 @@ const ResponseGaugeChart = ({ data }) => {
dataKey="response" dataKey="response"
stroke="none" stroke="none"
> >
<Cell fill="transparent" background={false} barSize={0} /> <Cell
fill="transparent"
background={false}
barSize={0}
/>
<Cell fill={responseProps.main} /> <Cell fill={responseProps.main} />
</RadialBar> </RadialBar>
</RadialBarChart> </RadialBarChart>
@@ -125,9 +125,7 @@ const PaginationTable = ({ monitorId, dateRange }) => {
uiTimezone uiTimezone
)} )}
</TableCell> </TableCell>
<TableCell> <TableCell>{check.statusCode ? check.statusCode : "N/A"}</TableCell>
{check.statusCode ? check.statusCode : "N/A"}
</TableCell>
<TableCell>{check.message}</TableCell> <TableCell>{check.message}</TableCell>
</TableRow> </TableRow>
); );
@@ -1 +0,0 @@
+37 -32
View File
@@ -13,10 +13,7 @@ import { useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
import { networkService } from "../../../main"; import { networkService } from "../../../main";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
import { import { formatDurationRounded, formatDurationSplit } from "../../../Utils/timeUtils";
formatDurationRounded,
formatDurationSplit,
} from "../../../Utils/timeUtils";
import MonitorDetailsAreaChart from "../../../Components/Charts/MonitorDetailsAreaChart"; import MonitorDetailsAreaChart from "../../../Components/Charts/MonitorDetailsAreaChart";
import ButtonGroup from "@mui/material/ButtonGroup"; import ButtonGroup from "@mui/material/ButtonGroup";
import SettingsIcon from "../../../assets/icons/settings-bold.svg?react"; import SettingsIcon from "../../../assets/icons/settings-bold.svg?react";
@@ -93,14 +90,9 @@ const DetailsPage = ({ isAdmin }) => {
authToken: authToken, authToken: authToken,
monitorId: monitorId, monitorId: monitorId,
}); });
if (res?.data?.data?.certificateDate) { if (res?.data?.data?.certificateDate) {
let [month, day, year] = res.data.data.certificateDate.split("/"); const date = res.data.data.certificateDate;
const date = new Date(year, month - 1, day); setCertificateExpiry(formatDateWithTz(date, dateFormat, uiTimezone) ?? "N/A");
setCertificateExpiry(
formatDateWithTz(date, dateFormat, uiTimezone) ?? "N/A"
);
} }
} catch (error) { } catch (error) {
console.error(error); console.error(error);
@@ -136,10 +128,19 @@ const DetailsPage = ({ isAdmin }) => {
{ name: "details", path: `/monitors/${monitorId}` }, { name: "details", path: `/monitors/${monitorId}` },
]} ]}
/> />
<Stack gap={theme.spacing(10)} mt={theme.spacing(10)}> <Stack
<Stack direction="row" gap={theme.spacing(2)}> gap={theme.spacing(10)}
mt={theme.spacing(10)}
>
<Stack
direction="row"
gap={theme.spacing(2)}
>
<Box> <Box>
<Typography component="h1" variant="h1"> <Typography
component="h1"
variant="h1"
>
{monitor.name} {monitor.name}
</Typography> </Typography>
<Stack <Stack
@@ -168,7 +169,10 @@ const DetailsPage = ({ isAdmin }) => {
<PulseDot color={statusColor[determineState(monitor)]} /> <PulseDot color={statusColor[determineState(monitor)]} />
</Box> </Box>
</Tooltip> </Tooltip>
<Typography component="h2" variant="h2"> <Typography
component="h2"
variant="h2"
>
{monitor.url?.replace(/^https?:\/\//, "") || "..."} {monitor.url?.replace(/^https?:\/\//, "") || "..."}
</Typography> </Typography>
<Typography <Typography
@@ -273,12 +277,13 @@ const DetailsPage = ({ isAdmin }) => {
)} )}
</Stack> </Stack>
</Stack> </Stack>
<Stack direction="row" gap={theme.spacing(8)}> <Stack
direction="row"
gap={theme.spacing(8)}
>
<StatBox sx={statusStyles[determineState(monitor)]}> <StatBox sx={statusStyles[determineState(monitor)]}>
<Typography component="h2">active for</Typography> <Typography component="h2">active for</Typography>
<Typography> <Typography>{splitDuration(monitor?.uptimeDuration)}</Typography>
{splitDuration(monitor?.uptimeDuration)}
</Typography>
</StatBox> </StatBox>
<StatBox> <StatBox>
<Typography component="h2">last check</Typography> <Typography component="h2">last check</Typography>
@@ -336,7 +341,11 @@ const DetailsPage = ({ isAdmin }) => {
</Button> </Button>
</ButtonGroup> </ButtonGroup>
</Stack> </Stack>
<Stack direction="row" flexWrap="wrap" gap={theme.spacing(8)}> <Stack
direction="row"
flexWrap="wrap"
gap={theme.spacing(8)}
>
<ChartBox> <ChartBox>
<Stack> <Stack>
<IconBox> <IconBox>
@@ -352,8 +361,7 @@ const DetailsPage = ({ isAdmin }) => {
? hoveredUptimeData.totalChecks ? hoveredUptimeData.totalChecks
: monitor?.periodTotalChecks} : monitor?.periodTotalChecks}
</Typography> </Typography>
{hoveredUptimeData !== null && {hoveredUptimeData !== null && hoveredUptimeData.time !== null && (
hoveredUptimeData.time !== null && (
<Typography <Typography
component="h5" component="h5"
position="absolute" position="absolute"
@@ -373,9 +381,7 @@ const DetailsPage = ({ isAdmin }) => {
<Typography>Uptime Percentage</Typography> <Typography>Uptime Percentage</Typography>
<Typography component="span"> <Typography component="span">
{hoveredUptimeData !== null {hoveredUptimeData !== null
? Math.floor( ? Math.floor(hoveredUptimeData.uptimePercentage * 10) / 10
hoveredUptimeData.uptimePercentage * 10
) / 10
: Math.floor(monitor?.periodUptime * 10) / 10} : Math.floor(monitor?.periodUptime * 10) / 10}
<Typography component="span">%</Typography> <Typography component="span">%</Typography>
</Typography> </Typography>
@@ -429,24 +435,23 @@ const DetailsPage = ({ isAdmin }) => {
<IconBox> <IconBox>
<AverageResponseIcon /> <AverageResponseIcon />
</IconBox> </IconBox>
<Typography component="h2"> <Typography component="h2">Average Response Time</Typography>
Average Response Time
</Typography>
</Stack> </Stack>
<ResponseGaugeChart <ResponseGaugeChart
data={[{ response: monitor?.periodAvgResponseTime }]} data={[{ response: monitor?.periodAvgResponseTime }]}
/> />
</ChartBox> </ChartBox>
<ChartBox sx={{ padding: 0 }}> <ChartBox sx={{ padding: 0 }}>
<Stack pt={theme.spacing(8)} pl={theme.spacing(8)}> <Stack
pt={theme.spacing(8)}
pl={theme.spacing(8)}
>
<IconBox> <IconBox>
<ResponseTimeIcon /> <ResponseTimeIcon />
</IconBox> </IconBox>
<Typography component="h2">Response Times</Typography> <Typography component="h2">Response Times</Typography>
</Stack> </Stack>
<MonitorDetailsAreaChart <MonitorDetailsAreaChart checks={[...monitor.checks].reverse()} />
checks={[...monitor.checks].reverse()}
/>
</ChartBox> </ChartBox>
<ChartBox <ChartBox
gap={theme.spacing(8)} gap={theme.spacing(8)}
+59 -12
View File
@@ -10,15 +10,30 @@ const SkeletonLayout = () => {
return ( return (
<> <>
<Skeleton variant="rounded" width="20%" height={34} /> <Skeleton
<Stack gap={theme.spacing(20)} mt={theme.spacing(6)}> variant="rounded"
<Stack direction="row" gap={theme.spacing(4)} mt={theme.spacing(4)}> width="20%"
height={34}
/>
<Stack
gap={theme.spacing(20)}
mt={theme.spacing(6)}
>
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(4)}
>
<Skeleton <Skeleton
variant="circular" variant="circular"
style={{ minWidth: 24, minHeight: 24 }} style={{ minWidth: 24, minHeight: 24 }}
/> />
<Box width="80%"> <Box width="80%">
<Skeleton variant="rounded" width="50%" height={24} /> <Skeleton
variant="rounded"
width="50%"
height={24}
/>
<Skeleton <Skeleton
variant="rounded" variant="rounded"
width="50%" width="50%"
@@ -38,9 +53,21 @@ const SkeletonLayout = () => {
justifyContent="space-between" justifyContent="space-between"
gap={theme.spacing(12)} gap={theme.spacing(12)}
> >
<Skeleton variant="rounded" width="100%" height={80} /> <Skeleton
<Skeleton variant="rounded" width="100%" height={80} /> variant="rounded"
<Skeleton variant="rounded" width="100%" height={80} /> width="100%"
height={80}
/>
<Skeleton
variant="rounded"
width="100%"
height={80}
/>
<Skeleton
variant="rounded"
width="100%"
height={80}
/>
</Stack> </Stack>
<Box> <Box>
<Stack <Stack
@@ -54,16 +81,36 @@ const SkeletonLayout = () => {
height={24} height={24}
sx={{ alignSelf: "flex-end" }} sx={{ alignSelf: "flex-end" }}
/> />
<Skeleton variant="rounded" width="20%" height={34} /> <Skeleton
variant="rounded"
width="20%"
height={34}
/>
</Stack> </Stack>
<Box sx={{ height: "200px" }}> <Box sx={{ height: "200px" }}>
<Skeleton variant="rounded" width="100%" height="100%" /> <Skeleton
variant="rounded"
width="100%"
height="100%"
/>
</Box> </Box>
</Box> </Box>
<Stack gap={theme.spacing(8)}> <Stack gap={theme.spacing(8)}>
<Skeleton variant="rounded" width="20%" height={24} /> <Skeleton
<Skeleton variant="rounded" width="100%" height={200} /> variant="rounded"
<Skeleton variant="rounded" width="100%" height={50} /> width="20%"
height={24}
/>
<Skeleton
variant="rounded"
width="100%"
height={200}
/>
<Skeleton
variant="rounded"
width="100%"
height={50}
/>
</Stack> </Stack>
</Stack> </Stack>
</> </>
+20 -75
View File
@@ -4,15 +4,7 @@ import { useTheme } from "@emotion/react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { createToast } from "../../../Utils/toastUtils"; import { createToast } from "../../../Utils/toastUtils";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
import { import { IconButton, Menu, MenuItem } from "@mui/material";
Button,
IconButton,
Menu,
MenuItem,
Modal,
Stack,
Typography,
} from "@mui/material";
import { import {
deleteUptimeMonitor, deleteUptimeMonitor,
pauseUptimeMonitor, pauseUptimeMonitor,
@@ -20,6 +12,7 @@ import {
} from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
import Settings from "../../../assets/icons/settings-bold.svg?react"; import Settings from "../../../assets/icons/settings-bold.svg?react";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import Dialog from "../../../Components/Dialog";
const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => { const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
const [anchorEl, setAnchorEl] = useState(null); const [anchorEl, setAnchorEl] = useState(null);
@@ -29,7 +22,7 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
const theme = useTheme(); const theme = useTheme();
const authState = useSelector((state) => state.auth); const authState = useSelector((state) => state.auth);
const authToken = authState.authToken; const authToken = authState.authToken;
const { isLoading } = useSelector((state) => state.uptimeMonitors);
const handleRemove = async (event) => { const handleRemove = async (event) => {
event.preventDefault(); event.preventDefault();
@@ -90,11 +83,7 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
aria-label="monitor actions" aria-label="monitor actions"
onClick={(event) => { onClick={(event) => {
event.stopPropagation(); event.stopPropagation();
openMenu( openMenu(event, monitor._id, monitor.type === "ping" ? null : monitor.url);
event,
monitor._id,
monitor.type === "ping" ? null : monitor.url
);
}} }}
sx={{ sx={{
"&:focus": { "&:focus": {
@@ -185,7 +174,6 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
}} }}
> >
{monitor?.isActive === true ? "Pause" : "Resume"} {monitor?.isActive === true ? "Pause" : "Resume"}
</MenuItem> </MenuItem>
)} )}
{isAdmin && ( {isAdmin && (
@@ -199,69 +187,26 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
</MenuItem> </MenuItem>
)} )}
</Menu> </Menu>
<Modal <Dialog
aria-labelledby="modal-delete-monitor" modelTitle="modal-delete-monitor"
aria-describedby="delete-monitor-confirmation" modelDescription="delete-monitor-confirmation"
open={isOpen} open={isOpen}
onClose={(e) => { onClose={() => setIsOpen(false)}
title="Do you really want to delete this monitor?"
confirmationBtnLbl="Delete"
confirmationBtnOnClick={(e) => {
e.stopPropagation(); e.stopPropagation();
setIsOpen(false);
}}
>
<Stack
gap={theme.spacing(2)}
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
boxShadow: 24,
p: theme.spacing(15),
"&:focus": {
outline: "none",
},
}}
>
<Typography id="modal-delete-monitor" component="h2" variant="h2">
Do you really want to delete this monitor?
</Typography>
<Typography id="delete-monitor-confirmation" variant="body1">
Once deleted, this monitor cannot be retrieved.
</Typography>
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(12)}
justifyContent="flex-end"
>
<Button
variant="text"
color="info"
onClick={(e) => {
e.stopPropagation();
setIsOpen(false);
}}
>
Cancel
</Button>
<Button
variant="contained"
color="error"
onClick={(e) => {
e.stopPropagation(e);
handleRemove(e); handleRemove(e);
}} }}
> cancelBtnLbl="Cancel"
Delete cancelBtnOnClick={(e) => {
</Button> e.stopPropagation();
</Stack> setIsOpen(false);
</Stack> }}
</Modal> theme={theme}
isLoading={isLoading}
description="Once deleted, this monitor cannot be retrieved."
></Dialog>
</> </>
); );
}; };
+5 -1
View File
@@ -26,7 +26,11 @@ const Fallback = ({ isAdmin }) => {
<Box pb={theme.spacing(20)}> <Box pb={theme.spacing(20)}>
{mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />} {mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />}
</Box> </Box>
<Typography component="h2" variant="h2" fontWeight={500}> <Typography
component="h2"
variant="h2"
fontWeight={500}
>
No monitors found to display No monitors found to display
</Typography> </Typography>
<Typography variant="body1"> <Typography variant="body1">
+36 -7
View File
@@ -11,20 +11,49 @@ const SkeletonLayout = () => {
return ( return (
<> <>
<Stack direction="row" justifyContent="space-between" alignItems="center"> <Stack
<Skeleton variant="rounded" width="50%" height={36} /> direction="row"
<Skeleton variant="rounded" width="15%" height={36} /> justifyContent="space-between"
alignItems="center"
>
<Skeleton
variant="rounded"
width="50%"
height={36}
/>
<Skeleton
variant="rounded"
width="15%"
height={36}
/>
</Stack> </Stack>
<Stack <Stack
gap={theme.spacing(12)} gap={theme.spacing(12)}
direction="row" direction="row"
justifyContent="space-between" justifyContent="space-between"
> >
<Skeleton variant="rounded" width="100%" height={100} /> <Skeleton
<Skeleton variant="rounded" width="100%" height={100} /> variant="rounded"
<Skeleton variant="rounded" width="100%" height={100} /> width="100%"
height={100}
/>
<Skeleton
variant="rounded"
width="100%"
height={100}
/>
<Skeleton
variant="rounded"
width="100%"
height={100}
/>
</Stack> </Stack>
<Skeleton variant="rounded" width="100%" height="100%" flex={1} /> <Skeleton
variant="rounded"
width="100%"
height="100%"
flex={1}
/>
</> </>
); );
}; };
+18 -4
View File
@@ -35,10 +35,24 @@ const NotFound = ({ title = DefaultValue.title, desc = DefaultValue.desc }) => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<Stack height="100vh" justifyContent="center"> <Stack
<Stack gap={theme.spacing(2)} alignItems="center"> height="100vh"
<img src={NotFoundSvg} alt="404" style={{ maxHeight: "25rem" }} /> justifyContent="center"
<Typography component="h1" variant="h1" fontSize={16}> >
<Stack
gap={theme.spacing(2)}
alignItems="center"
>
<img
src={NotFoundSvg}
alt="404"
style={{ maxHeight: "25rem" }}
/>
<Typography
component="h1"
variant="h1"
fontSize={16}
>
{title} {title}
</Typography> </Typography>
<Typography variant="body1">{desc}</Typography> <Typography variant="body1">{desc}</Typography>
+36 -20
View File
@@ -58,9 +58,7 @@ const PageSpeedConfigure = () => {
useEffect(() => { useEffect(() => {
const fetchMonitor = async () => { const fetchMonitor = async () => {
try { try {
const action = await dispatch( const action = await dispatch(getPagespeedMonitorById({ authToken, monitorId }));
getPagespeedMonitorById({ authToken, monitorId })
);
if (getPagespeedMonitorById.fulfilled.match(action)) { if (getPagespeedMonitorById.fulfilled.match(action)) {
const monitor = action.payload.data; const monitor = action.payload.data;
@@ -122,8 +120,7 @@ const PageSpeedConfigure = () => {
setErrors((prev) => { setErrors((prev) => {
const updatedErrors = { ...prev }; const updatedErrors = { ...prev };
if (validation.error) if (validation.error) updatedErrors[name] = validation.error.details[0].message;
updatedErrors[name] = validation.error.details[0].message;
else delete updatedErrors[name]; else delete updatedErrors[name];
return updatedErrors; return updatedErrors;
}); });
@@ -147,9 +144,7 @@ const PageSpeedConfigure = () => {
const handleSave = async (event) => { const handleSave = async (event) => {
event.preventDefault(); event.preventDefault();
const action = await dispatch( const action = await dispatch(updatePageSpeed({ authToken, monitor: monitor }));
updatePageSpeed({ authToken, monitor: monitor })
);
if (action.meta.requestStatus === "fulfilled") { if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Monitor updated successfully!" }); createToast({ body: "Monitor updated successfully!" });
dispatch(getPageSpeedByTeamId(authToken)); dispatch(getPageSpeedByTeamId(authToken));
@@ -170,7 +165,10 @@ const PageSpeedConfigure = () => {
}; };
return ( return (
<Stack className="configure-pagespeed" gap={theme.spacing(10)}> <Stack
className="configure-pagespeed"
gap={theme.spacing(10)}
>
{Object.keys(monitor).length === 0 ? ( {Object.keys(monitor).length === 0 ? (
<SkeletonLayout /> <SkeletonLayout />
) : ( ) : (
@@ -190,9 +188,15 @@ const PageSpeedConfigure = () => {
flex={1} flex={1}
gap={theme.spacing(10)} gap={theme.spacing(10)}
> >
<Stack direction="row" gap={theme.spacing(2)}> <Stack
direction="row"
gap={theme.spacing(2)}
>
<Box> <Box>
<Typography component="h1" variant="h1"> <Typography
component="h1"
variant="h1"
>
{monitor.name} {monitor.name}
</Typography> </Typography>
<Stack <Stack
@@ -221,7 +225,10 @@ const PageSpeedConfigure = () => {
<PulseDot color={statusColor[determineState(monitor)]} /> <PulseDot color={statusColor[determineState(monitor)]} />
</Box> </Box>
</Tooltip> </Tooltip>
<Typography component="h2" variant="h2"> <Typography
component="h2"
variant="h2"
>
{monitor.url?.replace(/^https?:\/\//, "") || "..."} {monitor.url?.replace(/^https?:\/\//, "") || "..."}
</Typography> </Typography>
<Typography <Typography
@@ -248,7 +255,10 @@ const PageSpeedConfigure = () => {
</Typography> </Typography>
</Stack> </Stack>
</Box> </Box>
<Box alignSelf="flex-end" ml="auto"> <Box
alignSelf="flex-end"
ml="auto"
>
<LoadingButton <LoadingButton
onClick={handlePause} onClick={handlePause}
loading={isLoading} loading={isLoading}
@@ -295,8 +305,8 @@ const PageSpeedConfigure = () => {
<Box> <Box>
<Typography component="h2">General settings</Typography> <Typography component="h2">General settings</Typography>
<Typography component="p"> <Typography component="p">
Here you can select the URL of the host, together with the Here you can select the URL of the host, together with the type of
type of monitor. monitor.
</Typography> </Typography>
</Box> </Box>
<Stack <Stack
@@ -337,9 +347,7 @@ const PageSpeedConfigure = () => {
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(6)}> <Stack gap={theme.spacing(6)}>
<Typography component="p"> <Typography component="p">When there is a new incident,</Typography>
When there is a new incident,
</Typography>
<Checkbox <Checkbox
id="notify-sms" id="notify-sms"
label="Notify via SMS (coming soon)" label="Notify via SMS (coming soon)"
@@ -401,7 +409,11 @@ const PageSpeedConfigure = () => {
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
<Stack direction="row" justifyContent="flex-end" mt="auto"> <Stack
direction="row"
justifyContent="flex-end"
mt="auto"
>
<LoadingButton <LoadingButton
loading={isLoading} loading={isLoading}
type="submit" type="submit"
@@ -469,7 +481,11 @@ const PageSpeedConfigure = () => {
> >
Cancel Cancel
</Button> </Button>
<Button variant="contained" color="error" onClick={handleRemove}> <Button
variant="contained"
color="error"
onClick={handleRemove}
>
Delete Delete
</Button> </Button>
</Stack> </Stack>
@@ -11,9 +11,21 @@ const SkeletonLayout = () => {
return ( return (
<> <>
<Skeleton variant="rounded" width="15%" height={34} /> <Skeleton
<Stack gap={theme.spacing(20)} mt={theme.spacing(6)} maxWidth="1000px"> variant="rounded"
<Stack direction="row" gap={theme.spacing(4)} mt={theme.spacing(4)}> width="15%"
height={34}
/>
<Stack
gap={theme.spacing(20)}
mt={theme.spacing(6)}
maxWidth="1000px"
>
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(4)}
>
<Skeleton <Skeleton
variant="circular" variant="circular"
style={{ minWidth: 24, minHeight: 24 }} style={{ minWidth: 24, minHeight: 24 }}
@@ -25,7 +37,11 @@ const SkeletonLayout = () => {
height={24} height={24}
sx={{ mb: theme.spacing(4) }} sx={{ mb: theme.spacing(4) }}
/> />
<Skeleton variant="rounded" width="50%" height={18} /> <Skeleton
variant="rounded"
width="50%"
height={18}
/>
</Box> </Box>
<Stack <Stack
direction="row" direction="row"
@@ -35,13 +51,32 @@ const SkeletonLayout = () => {
alignSelf: "flex-end", alignSelf: "flex-end",
}} }}
> >
<Skeleton variant="rounded" width={100} height={34} /> <Skeleton
<Skeleton variant="rounded" width={100} height={34} /> variant="rounded"
width={100}
height={34}
/>
<Skeleton
variant="rounded"
width={100}
height={34}
/>
</Stack> </Stack>
</Stack> </Stack>
<Skeleton variant="rounded" width="100%" height={500} /> <Skeleton
<Stack direction="row" justifyContent="flex-end"> variant="rounded"
<Skeleton variant="rounded" width="15%" height={34} /> width="100%"
height={500}
/>
<Stack
direction="row"
justifyContent="flex-end"
>
<Skeleton
variant="rounded"
width="15%"
height={34}
/>
</Stack> </Stack>
</Stack> </Stack>
</> </>
@@ -118,9 +118,7 @@ const CreatePageSpeed = () => {
userId: user._id, userId: user._id,
notifications: monitor.notifications, notifications: monitor.notifications,
}; };
const action = await dispatch( const action = await dispatch(createPageSpeed({ authToken, monitor: form }));
createPageSpeed({ authToken, monitor: form })
);
if (action.meta.requestStatus === "fulfilled") { if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Monitor created successfully!" }); createToast({ body: "Monitor created successfully!" });
navigate("/pagespeed"); navigate("/pagespeed");
@@ -164,8 +162,14 @@ const CreatePageSpeed = () => {
gap={theme.spacing(12)} gap={theme.spacing(12)}
mt={theme.spacing(6)} mt={theme.spacing(6)}
> >
<Typography component="h1" variant="h1"> <Typography
<Typography component="span" fontSize="inherit"> component="h1"
variant="h1"
>
<Typography
component="span"
fontSize="inherit"
>
Create your{" "} Create your{" "}
</Typography> </Typography>
<Typography <Typography
@@ -181,8 +185,7 @@ const CreatePageSpeed = () => {
<Box> <Box>
<Typography component="h2">General settings</Typography> <Typography component="h2">General settings</Typography>
<Typography component="p"> <Typography component="p">
Here you can select the URL of the host, together with the type of Here you can select the URL of the host, together with the type of monitor.
monitor.
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(15)}> <Stack gap={theme.spacing(15)}>
@@ -326,7 +329,10 @@ const CreatePageSpeed = () => {
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
<Stack direction="row" justifyContent="flex-end"> <Stack
direction="row"
justifyContent="flex-end"
>
<Button <Button
variant="contained" variant="contained"
color="primary" color="primary"
@@ -105,9 +105,7 @@ const CustomToolTip = ({ active, payload, label, config }) => {
> >
{config[key].text} {config[key].text}
</Typography>{" "} </Typography>{" "}
<Typography component="span"> <Typography component="span">{payload[0].payload[key]}</Typography>
{payload[0].payload[key]}
</Typography>
</Stack> </Stack>
); );
})} })}
@@ -216,10 +214,7 @@ CustomTick.propTypes = {
const PagespeedDetailsAreaChart = ({ data, interval, metrics }) => { const PagespeedDetailsAreaChart = ({ data, interval, metrics }) => {
const theme = useTheme(); const theme = useTheme();
const [isHovered, setIsHovered] = useState(false); const [isHovered, setIsHovered] = useState(false);
const memoizedData = useMemo( const memoizedData = useMemo(() => processDataWithGaps(data, interval), [data[0]]);
() => processDataWithGaps(data, interval),
[data[0]]
);
const filteredConfig = Object.keys(config).reduce((result, key) => { const filteredConfig = Object.keys(config).reduce((result, key) => {
if (metrics[key]) { if (metrics[key]) {
@@ -229,7 +224,11 @@ const PagespeedDetailsAreaChart = ({ data, interval, metrics }) => {
}, {}); }, {});
return ( return (
<ResponsiveContainer width="100%" minWidth={25} height={215}> <ResponsiveContainer
width="100%"
minWidth={25}
height={215}
>
<AreaChart <AreaChart
width="100%" width="100%"
height="100%" height="100%"
@@ -265,9 +264,24 @@ const PagespeedDetailsAreaChart = ({ data, interval, metrics }) => {
const endColor = theme.palette[color].light; const endColor = theme.palette[color].light;
return ( return (
<linearGradient id={id} x1="0" y1="0" x2="0" y2="1" key={id}> <linearGradient
<stop offset="0%" stopColor={startColor} stopOpacity={0.8} /> id={id}
<stop offset="100%" stopColor={endColor} stopOpacity={0} /> 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> </linearGradient>
); );
})} })}
@@ -299,12 +313,9 @@ PagespeedDetailsAreaChart.propTypes = {
data: PropTypes.arrayOf( data: PropTypes.arrayOf(
PropTypes.shape({ PropTypes.shape({
createdAt: PropTypes.string.isRequired, createdAt: PropTypes.string.isRequired,
accessibility: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) accessibility: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
.isRequired, bestPractices: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
bestPractices: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) performance: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
.isRequired,
performance: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
.isRequired,
seo: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, seo: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
}) })
).isRequired, ).isRequired,
@@ -20,7 +20,12 @@ const PieCenterLabel = ({ value, color, setExpand }) => {
transform={`translate(${width / 2}, ${height / 2})`} transform={`translate(${width / 2}, ${height / 2})`}
onMouseEnter={() => setExpand(true)} onMouseEnter={() => setExpand(true)}
> >
<circle cx={0} cy={0} r={width / 4} fill="transparent" /> <circle
cx={0}
cy={0}
r={width / 4}
fill="transparent"
/>
<text <text
className="pie-label" className="pie-label"
style={{ style={{
+65 -29
View File
@@ -1,20 +1,10 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { import { Box, Button, Divider, Stack, Tooltip, Typography } from "@mui/material";
Box,
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 { formatDurationRounded, formatDurationSplit } from "../../../Utils/timeUtils";
formatDurationRounded,
formatDurationSplit,
} from "../../../Utils/timeUtils";
import { ChartBox, IconBox, StatBox } from "./styled"; import { ChartBox, IconBox, StatBox } from "./styled";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
import { networkService } from "../../../main"; import { networkService } from "../../../main";
@@ -88,7 +78,10 @@ const PageSpeedDetails = ({ isAdmin }) => {
}; };
return ( return (
<Stack className="page-speed-details" gap={theme.spacing(10)}> <Stack
className="page-speed-details"
gap={theme.spacing(10)}
>
{loading ? ( {loading ? (
<SkeletonLayout /> <SkeletonLayout />
) : ( ) : (
@@ -99,9 +92,15 @@ const PageSpeedDetails = ({ isAdmin }) => {
{ name: "details", path: `/pagespeed/${monitorId}` }, { name: "details", path: `/pagespeed/${monitorId}` },
]} ]}
/> />
<Stack direction="row" gap={theme.spacing(2)}> <Stack
direction="row"
gap={theme.spacing(2)}
>
<Box> <Box>
<Typography component="h1" variant="h1"> <Typography
component="h1"
variant="h1"
>
{monitor.name} {monitor.name}
</Typography> </Typography>
<Stack <Stack
@@ -130,7 +129,10 @@ const PageSpeedDetails = ({ isAdmin }) => {
<PulseDot color={statusColor[determineState(monitor)]} /> <PulseDot color={statusColor[determineState(monitor)]} />
</Box> </Box>
</Tooltip> </Tooltip>
<Typography component="h2" variant="h2"> <Typography
component="h2"
variant="h2"
>
{monitor?.url} {monitor?.url}
</Typography> </Typography>
<Typography <Typography
@@ -179,7 +181,10 @@ const PageSpeedDetails = ({ isAdmin }) => {
</Button> </Button>
)} )}
</Stack> </Stack>
<Stack direction="row" gap={theme.spacing(8)}> <Stack
direction="row"
gap={theme.spacing(8)}
>
<StatBox> <StatBox>
<Typography component="h2">checks since</Typography> <Typography component="h2">checks since</Typography>
<Typography> <Typography>
@@ -196,11 +201,18 @@ const PageSpeedDetails = ({ isAdmin }) => {
</StatBox> </StatBox>
</Stack> </Stack>
<Box> <Box>
<Typography variant="body2" my={theme.spacing(8)}> <Typography
variant="body2"
my={theme.spacing(8)}
>
Showing statistics for past 24 hours. Showing statistics for past 24 hours.
</Typography> </Typography>
<ChartBox sx={{ gridTemplateColumns: "75% 25%" }}> <ChartBox sx={{ gridTemplateColumns: "75% 25%" }}>
<Stack direction="row" alignItems="center" gap={theme.spacing(6)}> <Stack
direction="row"
alignItems="center"
gap={theme.spacing(6)}
>
<IconBox> <IconBox>
<ScoreIcon /> <ScoreIcon />
</IconBox> </IconBox>
@@ -232,7 +244,10 @@ const PageSpeedDetails = ({ isAdmin }) => {
}} }}
> >
<Box> <Box>
<Typography fontSize={11} fontWeight={500}> <Typography
fontSize={11}
fontWeight={500}
>
Shown Shown
</Typography> </Typography>
<Divider sx={{ mt: theme.spacing(2) }} /> <Divider sx={{ mt: theme.spacing(2) }} />
@@ -273,7 +288,11 @@ const PageSpeedDetails = ({ isAdmin }) => {
flex={1} flex={1}
sx={{ gridTemplateColumns: "50% 50%", gridTemplateRows: "15% 85%" }} sx={{ gridTemplateColumns: "50% 50%", gridTemplateRows: "15% 85%" }}
> >
<Stack direction="row" alignItems="center" gap={theme.spacing(6)}> <Stack
direction="row"
alignItems="center"
gap={theme.spacing(6)}
>
<IconBox> <IconBox>
<PerformanceIcon /> <PerformanceIcon />
</IconBox> </IconBox>
@@ -288,7 +307,10 @@ const PageSpeedDetails = ({ isAdmin }) => {
pb={theme.spacing(12)} pb={theme.spacing(12)}
> >
<PieChart audits={audits} /> <PieChart audits={audits} />
<Typography variant="body1" mt="auto"> <Typography
variant="body1"
mt="auto"
>
Values are estimated and may vary.{" "} Values are estimated and may vary.{" "}
<Typography <Typography
component="span" component="span"
@@ -309,8 +331,16 @@ const PageSpeedDetails = ({ isAdmin }) => {
</Typography> </Typography>
</Typography> </Typography>
</Stack> </Stack>
<Box px={theme.spacing(20)} py={theme.spacing(8)} height="100%"> <Box
<Stack direction="row" alignItems="center" gap={theme.spacing(6)}> px={theme.spacing(20)}
py={theme.spacing(8)}
height="100%"
>
<Stack
direction="row"
alignItems="center"
gap={theme.spacing(6)}
>
<IconBox> <IconBox>
<SpedometerIcon /> <SpedometerIcon />
</IconBox> </IconBox>
@@ -336,9 +366,7 @@ const PageSpeedDetails = ({ isAdmin }) => {
: theme.palette.unresolved.main; : theme.palette.unresolved.main;
// 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(/(\d+\.?\d*)\s*([a-zA-Z]+)/);
/(\d+\.?\d*)\s*([a-zA-Z]+)/
);
let value; let value;
let unit; let unit;
if (match) { if (match) {
@@ -376,12 +404,20 @@ const PageSpeedDetails = ({ isAdmin }) => {
color={theme.palette.text.primary} color={theme.palette.text.primary}
> >
{value} {value}
<Typography component="span" variant="body2" ml={2}> <Typography
component="span"
variant="body2"
ml={2}
>
{unit} {unit}
</Typography> </Typography>
</Typography> </Typography>
</Box> </Box>
<Box width={4} backgroundColor={bg} borderRadius={4} /> <Box
width={4}
backgroundColor={bg}
borderRadius={4}
/>
</Stack> </Stack>
); );
})} })}
+62 -12
View File
@@ -8,12 +8,31 @@ import { Box, Skeleton, Stack } from "@mui/material";
const SkeletonLayout = () => { const SkeletonLayout = () => {
return ( return (
<> <>
<Skeleton variant="rounded" width="15%" height={34} /> <Skeleton
<Stack direction="row" gap={4}> variant="rounded"
<Skeleton variant="circular" style={{ minWidth: 24, minHeight: 24 }} /> width="15%"
height={34}
/>
<Stack
direction="row"
gap={4}
>
<Skeleton
variant="circular"
style={{ minWidth: 24, minHeight: 24 }}
/>
<Box width="85%"> <Box width="85%">
<Skeleton variant="rounded" width="50%" height={24} /> <Skeleton
<Skeleton variant="rounded" width="50%" height={18} sx={{ mt: 4 }} /> variant="rounded"
width="50%"
height={24}
/>
<Skeleton
variant="rounded"
width="50%"
height={18}
sx={{ mt: 4 }}
/>
</Box> </Box>
<Skeleton <Skeleton
variant="rounded" variant="rounded"
@@ -28,14 +47,45 @@ const SkeletonLayout = () => {
gap={20} gap={20}
flexWrap="wrap" flexWrap="wrap"
> >
<Skeleton variant="rounded" width="30%" height={90} sx={{ flex: 1 }} /> <Skeleton
<Skeleton variant="rounded" width="30%" height={90} sx={{ flex: 1 }} /> variant="rounded"
<Skeleton variant="rounded" width="30%" height={90} sx={{ flex: 1 }} /> width="30%"
height={90}
sx={{ flex: 1 }}
/>
<Skeleton
variant="rounded"
width="30%"
height={90}
sx={{ flex: 1 }}
/>
<Skeleton
variant="rounded"
width="30%"
height={90}
sx={{ flex: 1 }}
/>
</Stack> </Stack>
<Skeleton variant="rounded" width="25%" height={24} /> <Skeleton
<Skeleton variant="rounded" width="100%" height={300} /> variant="rounded"
<Skeleton variant="rounded" width="25%" height={24} /> width="25%"
<Skeleton variant="rounded" width="100%" height={300} /> height={24}
/>
<Skeleton
variant="rounded"
width="100%"
height={300}
/>
<Skeleton
variant="rounded"
width="25%"
height={24}
/>
<Skeleton
variant="rounded"
width="100%"
height={300}
/>
</> </>
); );
}; };
+20 -16
View File
@@ -5,13 +5,7 @@ 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 { IconBox } from "./Details/styled";
import { import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip } from "recharts";
Area,
AreaChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
} from "recharts";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { formatDateWithTz, formatDurationSplit } from "../../Utils/timeUtils"; import { formatDateWithTz, formatDurationSplit } from "../../Utils/timeUtils";
import useUtils from "../Monitors/utils"; import useUtils from "../Monitors/utils";
@@ -99,11 +93,7 @@ const processData = (data) => {
const calculateScore = (entry) => { const calculateScore = (entry) => {
return ( return (
(entry.accessibility + (entry.accessibility + entry.bestPractices + entry.performance + entry.seo) / 4
entry.bestPractices +
entry.performance +
entry.seo) /
4
); );
}; };
@@ -130,7 +120,11 @@ const PagespeedAreaChart = ({ data, status }) => {
const formattedData = processData(data); const formattedData = processData(data);
return ( return (
<ResponsiveContainer width="100%" minWidth={25} height={85}> <ResponsiveContainer
width="100%"
minWidth={25}
height={85}
>
<AreaChart <AreaChart
width="100%" width="100%"
height="100%" height="100%"
@@ -212,7 +206,11 @@ const Card = ({ monitor }) => {
const monitorState = determineState(monitor); const monitorState = determineState(monitor);
return ( return (
<Grid item lg={6} flexGrow={1}> <Grid
item
lg={6}
flexGrow={1}
>
<Box <Box
position="relative" position="relative"
p={theme.spacing(8)} p={theme.spacing(8)}
@@ -269,7 +267,10 @@ const Card = ({ monitor }) => {
mb={theme.spacing(-8)} mb={theme.spacing(-8)}
sx={{ gridColumnStart: 1, gridColumnEnd: 4 }} sx={{ gridColumnStart: 1, gridColumnEnd: 4 }}
> >
<PagespeedAreaChart data={monitor.checks} status={monitorState} /> <PagespeedAreaChart
data={monitor.checks}
status={monitorState}
/>
</Box> </Box>
<Box <Box
position="absolute" position="absolute"
@@ -287,7 +288,10 @@ const Card = ({ monitor }) => {
borderBottomLeftRadius: 4, borderBottomLeftRadius: 4,
}} }}
> >
<Typography fontSize={11} color={theme.palette.text.accent}> <Typography
fontSize={11}
color={theme.palette.text.accent}
>
Checking every{" "} Checking every{" "}
{(() => { {(() => {
const { time, format } = formatDurationSplit(monitor?.interval); const { time, format } = formatDurationSplit(monitor?.interval);
+5 -5
View File
@@ -59,7 +59,6 @@ const PageSpeed = ({ isAdmin }) => {
// 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 && monitors?.length === 0; let isActuallyLoading = isLoading && monitors?.length === 0;
console.log({ isActuallyLoading });
return ( return (
<Box <Box
className="page-speed" className="page-speed"
@@ -75,6 +74,10 @@ const PageSpeed = ({ isAdmin }) => {
}, },
}} }}
> >
{isActuallyLoading ? (
<SkeletonLayout />
) : monitors?.length !== 0 ? (
<Box>
<Box mb={theme.spacing(12)}> <Box mb={theme.spacing(12)}>
<Breadcrumbs list={[{ name: `pagespeed`, path: "/pagespeed" }]} /> <Breadcrumbs list={[{ name: `pagespeed`, path: "/pagespeed" }]} />
<Stack <Stack
@@ -82,7 +85,6 @@ const PageSpeed = ({ isAdmin }) => {
justifyContent="space-between" justifyContent="space-between"
alignItems="center" alignItems="center"
mt={theme.spacing(5)} mt={theme.spacing(5)}
gap={theme.spacing(6)}
> >
<Greeting type="pagespeed" /> <Greeting type="pagespeed" />
{isAdmin && ( {isAdmin && (
@@ -97,9 +99,6 @@ const PageSpeed = ({ isAdmin }) => {
)} )}
</Stack> </Stack>
</Box> </Box>
{isActuallyLoading ? (
<SkeletonLayout />
) : monitors?.length !== 0 ? (
<Grid <Grid
container container
spacing={theme.spacing(12)} spacing={theme.spacing(12)}
@@ -111,6 +110,7 @@ const PageSpeed = ({ isAdmin }) => {
/> />
))} ))}
</Grid> </Grid>
</Box>
) : ( ) : (
<Fallback <Fallback
title="pagespeed monitor" title="pagespeed monitor"
+10 -2
View File
@@ -17,7 +17,11 @@ const SkeletonLayout = () => {
mb={theme.spacing(12)} mb={theme.spacing(12)}
> >
<Box width="80%"> <Box width="80%">
<Skeleton variant="rounded" width="25%" height={24} /> <Skeleton
variant="rounded"
width="25%"
height={24}
/>
<Skeleton <Skeleton
variant="rounded" variant="rounded"
width="50%" width="50%"
@@ -32,7 +36,11 @@ const SkeletonLayout = () => {
sx={{ alignSelf: "flex-end" }} sx={{ alignSelf: "flex-end" }}
/> />
</Stack> </Stack>
<Stack direction="row" flexWrap="wrap" gap={theme.spacing(12)}> <Stack
direction="row"
flexWrap="wrap"
gap={theme.spacing(12)}
>
<Skeleton <Skeleton
variant="rounded" variant="rounded"
width="100%" width="100%"
+56 -19
View File
@@ -22,6 +22,7 @@ import { ConfigBox } from "./styled";
import { networkService } from "../../main"; import { networkService } from "../../main";
import { settingsValidation } from "../../Validation/validation"; import { settingsValidation } from "../../Validation/validation";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
import Dialog from "../../Components/Dialog";
const SECONDS_PER_DAY = 86400; const SECONDS_PER_DAY = 86400;
@@ -39,6 +40,8 @@ const Settings = ({ isAdmin }) => {
}); });
const [version, setVersion] = useState("unknown"); const [version, setVersion] = useState("unknown");
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const deleteStatsMonitorsInitState = { deleteMonitors: false, deleteStats: false };
const [isOpen, setIsOpen] = useState(deleteStatsMonitorsInitState);
const dispatch = useDispatch(); const dispatch = useDispatch();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -97,9 +100,7 @@ const Settings = ({ isAdmin }) => {
ttl: form.ttl, ttl: form.ttl,
}); });
const updatedUser = { ...user, checkTTL: form.ttl }; const updatedUser = { ...user, checkTTL: form.ttl };
const action = await dispatch( const action = await dispatch(update({ authToken, localData: updatedUser }));
update({ authToken, localData: updatedUser })
);
if (action.payload.success) { if (action.payload.success) {
createToast({ createToast({
body: "Settings saved successfully", body: "Settings saved successfully",
@@ -139,6 +140,8 @@ const Settings = ({ isAdmin }) => {
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
createToast({ body: "Failed to clear stats" }); createToast({ body: "Failed to clear stats" });
} finally {
setIsOpen(deleteStatsMonitorsInitState);
} }
}; };
@@ -167,6 +170,8 @@ const Settings = ({ isAdmin }) => {
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
createToast({ Body: "Failed to delete all monitors" }); createToast({ Body: "Failed to delete all monitors" });
} finally {
setIsOpen(deleteStatsMonitorsInitState);
} }
}; };
@@ -187,8 +192,8 @@ const Settings = ({ isAdmin }) => {
<Box> <Box>
<Typography component="h1">General settings</Typography> <Typography component="h1">General settings</Typography>
<Typography sx={{ mt: theme.spacing(2), mb: theme.spacing(2) }}> <Typography sx={{ mt: theme.spacing(2), mb: theme.spacing(2) }}>
<Typography component="span">Display timezone</Typography>- The <Typography component="span">Display timezone</Typography>- The timezone of
timezone of the dashboard you publicly display. the dashboard you publicly display.
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
@@ -218,9 +223,11 @@ const Settings = ({ isAdmin }) => {
onChange={(e) => { onChange={(e) => {
dispatch(setMode(e.target.value)); dispatch(setMode(e.target.value));
}} }}
items={[{_id:'light', name:'Light'},{_id:'dark', name:'Dark'}]} items={[
> { _id: "light", name: "Light" },
</Select> { _id: "dark", name: "Dark" },
]}
></Select>
</Stack> </Stack>
</ConfigBox> </ConfigBox>
{isAdmin && ( {isAdmin && (
@@ -228,8 +235,8 @@ const Settings = ({ isAdmin }) => {
<Box> <Box>
<Typography component="h1">History and monitoring</Typography> <Typography component="h1">History and monitoring</Typography>
<Typography sx={{ mt: theme.spacing(2) }}> <Typography sx={{ mt: theme.spacing(2) }}>
Define here for how long you want to keep the data. You can also Define here for how long you want to keep the data. You can also remove
remove all past data. all past data.
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
@@ -243,17 +250,31 @@ const Settings = ({ isAdmin }) => {
/> />
<Box> <Box>
<Typography>Clear all stats. This is irreversible.</Typography> <Typography>Clear all stats. This is irreversible.</Typography>
<LoadingButton <Button
variant="contained" variant="contained"
color="error" color="error"
loading={isLoading || authIsLoading || checksIsLoading} onClick={() =>
onClick={handleClearStats} setIsOpen({ ...deleteStatsMonitorsInitState, deleteStats: true })
}
sx={{ mt: theme.spacing(4) }} sx={{ mt: theme.spacing(4) }}
> >
Clear all stats Clear all stats
</LoadingButton> </Button>
</Box> </Box>
</Stack> </Stack>
<Dialog
modelTitle="model-clear-stats"
modelDescription="clear-stats-confirmation"
open={isOpen.deleteStats}
onClose={() => setIsOpen(deleteStatsMonitorsInitState)}
title="Do you want to clear all stats?"
confirmationBtnLbl="Yes, clear all stats"
confirmationBtnOnClick={handleClearStats}
cancelBtnLbl="Cancel"
cancelBtnOnClick={() => setIsOpen(deleteStatsMonitorsInitState)}
theme={theme}
isLoading={isLoading || authIsLoading || checksIsLoading}
></Dialog>
</ConfigBox> </ConfigBox>
)} )}
{isAdmin && ( {isAdmin && (
@@ -283,13 +304,28 @@ const Settings = ({ isAdmin }) => {
variant="contained" variant="contained"
color="error" color="error"
loading={isLoading || authIsLoading || checksIsLoading} loading={isLoading || authIsLoading || checksIsLoading}
onClick={handleDeleteAllMonitors} onClick={() =>
setIsOpen({ ...deleteStatsMonitorsInitState, deleteMonitors: true })
}
sx={{ mt: theme.spacing(4) }} sx={{ mt: theme.spacing(4) }}
> >
Remove all monitors Remove all monitors
</LoadingButton> </LoadingButton>
</Box> </Box>
</Stack> </Stack>
<Dialog
modelTitle="model-delete-all-monitors"
modelDescription="delete-all-monitors-confirmation"
open={isOpen.deleteMonitors}
onClose={() => setIsOpen(deleteStatsMonitorsInitState)}
title="Do you want to remove all monitors?"
confirmationBtnLbl="Yes, clear all monitors"
confirmationBtnOnClick={handleDeleteAllMonitors}
cancelBtnLbl="Cancel"
cancelBtnOnClick={() => setIsOpen(deleteStatsMonitorsInitState)}
theme={theme}
isLoading={isLoading || authIsLoading || checksIsLoading}
></Dialog>
</ConfigBox> </ConfigBox>
)} )}
{isAdmin && ( {isAdmin && (
@@ -320,9 +356,7 @@ const Settings = ({ isAdmin }) => {
</Box> </Box>
<Box> <Box>
<Typography component="h2">BlueWave Uptime {version}</Typography> <Typography component="h2">BlueWave Uptime {version}</Typography>
<Typography <Typography sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }}>
sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }}
>
Developed by Bluewave Labs. Developed by Bluewave Labs.
</Typography> </Typography>
<Link <Link
@@ -332,7 +366,10 @@ const Settings = ({ isAdmin }) => {
/> />
</Box> </Box>
</ConfigBox> </ConfigBox>
<Stack direction="row" justifyContent="flex-end"> <Stack
direction="row"
justifyContent="flex-end"
>
<LoadingButton <LoadingButton
loading={isLoading || authIsLoading || checksIsLoading} loading={isLoading || authIsLoading || checksIsLoading}
disabled={Object.keys(errors).length > 0} disabled={Object.keys(errors).length > 0}
+19 -44
View File
@@ -175,15 +175,12 @@ class NetworkService {
if (field) params.append("field", field); if (field) params.append("field", field);
if (order) params.append("order", order); if (order) params.append("order", order);
return this.axiosInstance.get( return this.axiosInstance.get(`/monitors/team/${teamId}?${params.toString()}`, {
`/monitors/team/${teamId}?${params.toString()}`,
{
headers: { headers: {
Authorization: `Bearer ${authToken}`, Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
} });
);
} }
/** /**
@@ -233,16 +230,12 @@ class NetworkService {
* @returns {Promise<AxiosResponse>} The response from the axios PUT request. * @returns {Promise<AxiosResponse>} The response from the axios PUT request.
*/ */
async updateMonitor(config) { async updateMonitor(config) {
return this.axiosInstance.put( return this.axiosInstance.put(`/monitors/${config.monitorId}`, config.updatedFields, {
`/monitors/${config.monitorId}`,
config.updatedFields,
{
headers: { headers: {
Authorization: `Bearer ${config.authToken}`, Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
} });
);
} }
/** /**
@@ -582,12 +575,9 @@ class NetworkService {
if (config.page) params.append("page", config.page); if (config.page) params.append("page", config.page);
if (config.rowsPerPage) params.append("rowsPerPage", config.rowsPerPage); if (config.rowsPerPage) params.append("rowsPerPage", config.rowsPerPage);
return this.axiosInstance.get( return this.axiosInstance.get(`/checks/${config.monitorId}?${params.toString()}`, {
`/checks/${config.monitorId}?${params.toString()}`,
{
headers: { Authorization: `Bearer ${config.authToken}` }, headers: { Authorization: `Bearer ${config.authToken}` },
} });
);
} }
/** /**
@@ -616,12 +606,9 @@ class NetworkService {
if (config.filter) params.append("filter", config.filter); if (config.filter) params.append("filter", config.filter);
if (config.page) params.append("page", config.page); if (config.page) params.append("page", config.page);
if (config.rowsPerPage) params.append("rowsPerPage", config.rowsPerPage); if (config.rowsPerPage) params.append("rowsPerPage", config.rowsPerPage);
return this.axiosInstance.get( return this.axiosInstance.get(`/checks/team/${config.teamId}?${params.toString()}`, {
`/checks/team/${config.teamId}?${params.toString()}`,
{
headers: { Authorization: `Bearer ${config.authToken}` }, headers: { Authorization: `Bearer ${config.authToken}` },
} });
);
} }
/** /**
@@ -705,16 +692,12 @@ class NetworkService {
*/ */
async createMaintenanceWindow(config) { async createMaintenanceWindow(config) {
return this.axiosInstance.post( return this.axiosInstance.post(`/maintenance-window`, config.maintenanceWindow, {
`/maintenance-window`,
config.maintenanceWindow,
{
headers: { headers: {
Authorization: `Bearer ${config.authToken}`, Authorization: `Bearer ${config.authToken}`,
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
} });
);
} }
/** /**
@@ -759,15 +742,12 @@ class NetworkService {
async getMaintenanceWindowById(config) { async getMaintenanceWindowById(config) {
const { authToken, maintenanceWindowId } = config; const { authToken, maintenanceWindowId } = config;
return this.axiosInstance.get( return this.axiosInstance.get(`/maintenance-window/${maintenanceWindowId}`, {
`/maintenance-window/${maintenanceWindowId}`,
{
headers: { headers: {
Authorization: `Bearer ${authToken}`, Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
} });
);
} }
/** /**
@@ -797,15 +777,12 @@ class NetworkService {
if (field) params.append("field", field); if (field) params.append("field", field);
if (order) params.append("order", order); if (order) params.append("order", order);
return this.axiosInstance.get( return this.axiosInstance.get(`/maintenance-window/team?${params.toString()}`, {
`/maintenance-window/team?${params.toString()}`,
{
headers: { headers: {
Authorization: `Bearer ${authToken}`, Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
} });
);
} }
/** /**
* ************************************ * ************************************
@@ -822,15 +799,12 @@ class NetworkService {
async deleteMaintenanceWindow(config) { async deleteMaintenanceWindow(config) {
const { authToken, maintenanceWindowId } = config; const { authToken, maintenanceWindowId } = config;
return this.axiosInstance.delete( return this.axiosInstance.delete(`/maintenance-window/${maintenanceWindowId}`, {
`/maintenance-window/${maintenanceWindowId}`,
{
headers: { headers: {
Authorization: `Bearer ${authToken}`, Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
} });
);
} }
/** /**
@@ -843,9 +817,10 @@ class NetworkService {
* *
*/ */
async fetchGithubLatestRelease() { async fetchGithubLatestRelease() {
return this.axiosInstance.get('https://api.github.com/repos/bluewave-labs/bluewave-uptime/releases/latest'); return this.axiosInstance.get(
"https://api.github.com/repos/bluewave-labs/bluewave-uptime/releases/latest"
);
} }
} }
export default NetworkService; export default NetworkService;
+1 -2
View File
@@ -110,8 +110,7 @@ const darkTheme = createTheme({
}, },
}, },
{ {
props: (props) => props: (props) => props.variant === "group" && props.filled === "true",
props.variant === "group" && props.filled === "true",
style: { style: {
backgroundColor: theme.palette.secondary.main, backgroundColor: theme.palette.secondary.main,
}, },
+1 -2
View File
@@ -107,8 +107,7 @@ const lightTheme = createTheme({
}, },
}, },
{ {
props: (props) => props: (props) => props.variant === "group" && props.filled === "true",
props.variant === "group" && props.filled === "true",
style: { style: {
backgroundColor: theme.palette.secondary.main, backgroundColor: theme.palette.secondary.main,
}, },
+14 -3
View File
@@ -155,8 +155,15 @@ const Greeting = ({ type = "" }) => {
return ( return (
<Box> <Box>
<Typography component="h1" variant="h1" mb={theme.spacing(1)}> <Typography
<Typography component="span" fontSize="inherit"> component="h1"
variant="h1"
mb={theme.spacing(1)}
>
<Typography
component="span"
fontSize="inherit"
>
{prepend},{" "} {prepend},{" "}
</Typography> </Typography>
<Typography <Typography
@@ -168,7 +175,11 @@ const Greeting = ({ type = "" }) => {
{firstName} {emoji} {firstName} {emoji}
</Typography> </Typography>
</Typography> </Typography>
<Typography variant="h2" lineHeight={1} color={theme.palette.text.accent}> <Typography
variant="h2"
lineHeight={1}
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>
+4 -13
View File
@@ -22,22 +22,16 @@ const passwordSchema = joi
}) })
.custom((value, helpers) => { .custom((value, helpers) => {
if (!/[A-Z]/.test(value)) { if (!/[A-Z]/.test(value)) {
return helpers.message( return helpers.message("Password must contain at least one uppercase letter");
"Password must contain at least one uppercase letter"
);
} }
if (!/[a-z]/.test(value)) { if (!/[a-z]/.test(value)) {
return helpers.message( return helpers.message("Password must contain at least one lowercase letter");
"Password must contain at least one lowercase letter"
);
} }
if (!/\d/.test(value)) { if (!/\d/.test(value)) {
return helpers.message("Password must contain at least one number"); return helpers.message("Password must contain at least one number");
} }
if (!/[!@#$%^&*]/.test(value)) { if (!/[!@#$%^&*]/.test(value)) {
return helpers.message( return helpers.message("Password must contain at least one special character");
"Password must contain at least one special character"
);
} }
return value; return value;
@@ -89,10 +83,7 @@ const monitorValidation = joi.object({
name: joi.string().trim().max(50).allow("").messages({ name: joi.string().trim().max(50).allow("").messages({
"string.max": "This field should not exceed the 50 characters limit.", "string.max": "This field should not exceed the 50 characters limit.",
}), }),
type: joi type: joi.string().trim().messages({ "string.empty": "This field is required." }),
.string()
.trim()
.messages({ "string.empty": "This field is required." }),
interval: joi.number().messages({ interval: joi.number().messages({
"number.base": "Frequency must be a number.", "number.base": "Frequency must be a number.",
"any.required": "Frequency is required.", "any.required": "Frequency is required.",
+4 -1
View File
@@ -11,7 +11,10 @@ export { networkService };
ReactDOM.createRoot(document.getElementById("root")).render( ReactDOM.createRoot(document.getElementById("root")).render(
<Provider store={store}> <Provider store={store}>
<PersistGate loading={null} persistor={persistor}> <PersistGate
loading={null}
persistor={persistor}
>
<Router> <Router>
<NetworkServiceProvider> <NetworkServiceProvider>
<App /> <App />
+1 -5
View File
@@ -41,11 +41,7 @@ export const store = configureStore({
middleware: (getDefaultMiddleware) => middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({ getDefaultMiddleware({
serializableCheck: { serializableCheck: {
ignoredActions: [ ignoredActions: ["persist/PERSIST", "persist/REHYDRATE", "persist/REGISTER"],
"persist/PERSIST",
"persist/REHYDRATE",
"persist/REGISTER",
],
}, },
}), }),
}); });
+5 -5
View File
@@ -1,11 +1,11 @@
import { defineConfig } from 'vite' import { defineConfig } from "vite";
import react from '@vitejs/plugin-react' import react from "@vitejs/plugin-react";
import svgr from 'vite-plugin-svgr'; import svgr from "vite-plugin-svgr";
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig({ export default defineConfig({
plugins: [svgr(), react()], plugins: [svgr(), react()],
optimizeDeps: { optimizeDeps: {
include: ['@mui/material/Tooltip', '@emotion/styled'], include: ["@mui/material/Tooltip", "@emotion/styled"],
}, },
}) });
+8
View File
@@ -0,0 +1,8 @@
module.exports = {
require: ["esm", "chai/register-expect.js"], // Include Chai's "expect" interface globally
spec: "tests/**/*.test.js", // Specify test files
timeout: 5000, // Set test-case timeout in milliseconds
recursive: true, // Include subdirectories
reporter: "spec", // Use the "spec" reporter
exit: true, // Force Mocha to quit after tests complete
};
-8
View File
@@ -1,8 +0,0 @@
module.exports = {
require: ["chai/register-expect.js"], // Include Chai's "expect" interface globally
spec: "tests/**/*.test.js", // Specify test files
timeout: 5000, // Set test-case timeout in milliseconds
recursive: true, // Include subdirectories
reporter: "spec", // Use the "spec" reporter
exit: true, // Force Mocha to quit after tests complete
};
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"all": true, "all": true,
"include": ["controllers/*.js"], "include": ["controllers/*.js", "utils/*.js", "service/*.js"],
"exclude": ["**/*.test.js"], "exclude": ["**/*.test.js"],
"reporter": ["html", "text", "lcov"], "reporter": ["html", "text", "lcov"],
"sourceMap": false, "sourceMap": false,
+1 -1
View File
@@ -12,4 +12,4 @@ const connectDbAndRunServer = async (app, db) => {
} }
}; };
module.exports = { connectDbAndRunServer }; export { connectDbAndRunServer };
+27 -22
View File
@@ -1,4 +1,4 @@
const { import {
registrationBodyValidation, registrationBodyValidation,
loginValidation, loginValidation,
editUserParamValidation, editUserParamValidation,
@@ -6,15 +6,16 @@ const {
recoveryValidation, recoveryValidation,
recoveryTokenValidation, recoveryTokenValidation,
newPasswordValidation, newPasswordValidation,
} = require("../validation/joi"); } from "../validation/joi.js";
const logger = require("../utils/logger"); import logger from "../utils/logger.js";
require("dotenv").config(); import dotenv from "dotenv";
const { errorMessages, successMessages } = require("../utils/messages"); import { errorMessages, successMessages } from "../utils/messages.js";
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
const SERVICE_NAME = "AuthController"; import { getTokenFromHeaders, tokenType } from "../utils/utils.js";
const { getTokenFromHeaders, tokenType } = require("../utils/utils"); import crypto from "crypto";
const crypto = require("crypto"); import { handleValidationError, handleError } from "./controllerUtils.js";
const { handleValidationError, handleError } = require("./controllerUtils"); const SERVICE_NAME = "authController";
dotenv.config();
/** /**
* Creates and returns JWT token with an arbitrary payload * Creates and returns JWT token with an arbitrary payload
@@ -27,9 +28,15 @@ const { handleValidationError, handleError } = require("./controllerUtils");
*/ */
const issueToken = (payload, typeOfToken, appSettings) => { const issueToken = (payload, typeOfToken, appSettings) => {
try { try {
const tokenTTL = (typeOfToken === tokenType.REFRESH_TOKEN) ? (appSettings?.refreshTokenTTL?? "7d") : (appSettings?.jwtTTL?? "2h"); const tokenTTL =
const tokenSecret = (typeOfToken === tokenType.REFRESH_TOKEN) ? appSettings?.refreshTokenSecret : appSettings?.jwtSecret; typeOfToken === tokenType.REFRESH_TOKEN
const payloadData = (typeOfToken === tokenType.REFRESH_TOKEN) ? {} : payload; ? (appSettings?.refreshTokenTTL ?? "7d")
: (appSettings?.jwtTTL ?? "2h");
const tokenSecret =
typeOfToken === tokenType.REFRESH_TOKEN
? appSettings?.refreshTokenSecret
: appSettings?.jwtSecret;
const payloadData = typeOfToken === tokenType.REFRESH_TOKEN ? {} : payload;
return jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL }); return jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
} catch (error) { } catch (error) {
@@ -107,7 +114,6 @@ const registerUser = async (req, res, next) => {
data: { user: newUser, token: token, refreshToken: refreshToken }, data: { user: newUser, token: token, refreshToken: refreshToken },
}); });
} catch (error) { } catch (error) {
console.log("ERROR", error);
next(handleError(error, SERVICE_NAME, "registerController")); next(handleError(error, SERVICE_NAME, "registerController"));
} }
}; };
@@ -134,6 +140,7 @@ const loginUser = async (req, res, next) => {
} }
try { try {
const { email, password } = req.body; const { email, password } = req.body;
// Check if user exists // Check if user exists
const user = await req.db.getUserByEmail(email); const user = await req.db.getUserByEmail(email);
@@ -162,7 +169,7 @@ const loginUser = async (req, res, next) => {
data: { user: userWithoutPassword, token: token, refreshToken: refreshToken }, data: { user: userWithoutPassword, token: token, refreshToken: refreshToken },
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "loginController")); next(handleError(error, SERVICE_NAME, "loginUser"));
} }
}; };
@@ -244,7 +251,7 @@ const editUser = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message indicating the existence of a superadmin, and a boolean indicating the existence of a superadmin. * @returns {Object} The response object with a success status, a message indicating the existence of a superadmin, and a boolean indicating the existence of a superadmin.
* @throws {Error} If there is an error during the process. * @throws {Error} If there is an error during the process.
*/ */
const checkSuperAdminExists = async (req, res, next) => { const checkSuperadminExists = async (req, res, next) => {
try { try {
const superAdminExists = await req.db.checkSuperadmin(req, res); const superAdminExists = await req.db.checkSuperadmin(req, res);
return res.status(200).json({ return res.status(200).json({
@@ -435,23 +442,21 @@ const deleteUser = async (req, res, next) => {
} }
}; };
const getAllUsers = async (req, res) => { const getAllUsers = async (req, res, next) => {
try { try {
const allUsers = await req.db.getAllUsers(req, res); const allUsers = await req.db.getAllUsers(req, res);
res res.status(200).json({ success: true, msg: "Got all users", data: allUsers });
.status(200)
.json({ success: true, msg: "Got all users", data: allUsers });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getAllUsersController")); next(handleError(error, SERVICE_NAME, "getAllUsersController"));
} }
}; };
module.exports = { export {
issueToken, issueToken,
registerUser, registerUser,
loginUser, loginUser,
editUser, editUser,
checkSuperadminExists: checkSuperAdminExists, checkSuperadminExists,
requestRecovery, requestRecovery,
validateRecovery, validateRecovery,
resetPassword, resetPassword,
+8 -7
View File
@@ -1,4 +1,4 @@
const { import {
createCheckParamValidation, createCheckParamValidation,
createCheckBodyValidation, createCheckBodyValidation,
getChecksParamValidation, getChecksParamValidation,
@@ -8,12 +8,13 @@ const {
deleteChecksParamValidation, deleteChecksParamValidation,
deleteChecksByTeamIdParamValidation, deleteChecksByTeamIdParamValidation,
updateChecksTTLBodyValidation, updateChecksTTLBodyValidation,
} = require("../validation/joi"); } from "../validation/joi.js";
const { successMessages } = require("../utils/messages"); import { successMessages } from "../utils/messages.js";
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
const { getTokenFromHeaders } = require("../utils/utils"); import { getTokenFromHeaders } from "../utils/utils.js";
import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "checkController"; const SERVICE_NAME = "checkController";
const { handleValidationError, handleError } = require("./controllerUtils");
const createCheck = async (req, res, next) => { const createCheck = async (req, res, next) => {
try { try {
@@ -143,7 +144,7 @@ const updateChecksTTL = async (req, res, next) => {
} }
}; };
module.exports = { export {
createCheck, createCheck,
getChecks, getChecks,
getTeamChecks, getTeamChecks,
+12 -5
View File
@@ -1,8 +1,7 @@
const handleValidationError = (error, serviceName) => { const handleValidationError = (error, serviceName) => {
error.status = 422; error.status = 422;
error.service = serviceName; error.service = serviceName;
error.message = error.message = error.details?.[0]?.message || error.message || "Validation Error";
error.details?.[0]?.message || error.message || "Validation Error";
return error; return error;
}; };
@@ -13,7 +12,15 @@ const handleError = (error, serviceName, method, status = 500) => {
return error; return error;
}; };
module.exports = { const fetchMonitorCertificate = async (sslChecker, monitor) => {
handleValidationError, try {
handleError, const monitorUrl = new URL(monitor.url);
const hostname = monitorUrl.hostname;
const cert = await sslChecker(hostname);
return cert;
} catch (error) {
throw error;
}
}; };
export { handleValidationError, handleError, fetchMonitorCertificate };
+13 -17
View File
@@ -1,14 +1,17 @@
const { import {
inviteRoleValidation, inviteRoleValidation,
inviteBodyValidation, inviteBodyValidation,
inviteVerificationBodyValidation, inviteVerificationBodyValidation,
} = require("../validation/joi"); } from "../validation/joi.js";
const logger = require("../utils/logger"); import logger from "../utils/logger.js";
require("dotenv").config(); import dotenv from "dotenv";
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
const { handleError, handleValidationError } = require("./controllerUtils"); import { handleError, handleValidationError } from "./controllerUtils.js";
import { getTokenFromHeaders } from "../utils/utils.js";
dotenv.config();
const SERVICE_NAME = "inviteController"; const SERVICE_NAME = "inviteController";
const { getTokenFromHeaders } = require("../utils/utils");
/** /**
* Issues an invitation to a new user. Only admins can invite new users. An invitation token is created and sent via email. * Issues an invitation to a new user. Only admins can invite new users. An invitation token is created and sent via email.
@@ -56,9 +59,7 @@ const issueInvitation = async (req, res, next) => {
}); });
}); });
return res return res.status(200).json({ success: true, msg: "Invite sent", data: inviteToken });
.status(200)
.json({ success: true, msg: "Invite sent", data: inviteToken });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "inviteController")); next(handleError(error, SERVICE_NAME, "inviteController"));
} }
@@ -74,15 +75,10 @@ const inviteVerifyController = async (req, res, next) => {
try { try {
const invite = await req.db.getInviteToken(req.body.token); const invite = await req.db.getInviteToken(req.body.token);
res res.status(200).json({ status: "success", msg: "Invite verified", data: invite });
.status(200)
.json({ status: "success", msg: "Invite verified", data: invite });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "inviteVerifyController")); next(handleError(error, SERVICE_NAME, "inviteVerifyController"));
} }
}; };
module.exports = { export { issueInvitation, inviteVerifyController };
issueInvitation,
inviteVerifyController,
};
@@ -1,4 +1,4 @@
const { import {
createMaintenanceWindowBodyValidation, createMaintenanceWindowBodyValidation,
editMaintenanceWindowByIdParamValidation, editMaintenanceWindowByIdParamValidation,
editMaintenanceByIdWindowBodyValidation, editMaintenanceByIdWindowBodyValidation,
@@ -6,11 +6,12 @@ const {
getMaintenanceWindowsByMonitorIdParamValidation, getMaintenanceWindowsByMonitorIdParamValidation,
getMaintenanceWindowsByTeamIdQueryValidation, getMaintenanceWindowsByTeamIdQueryValidation,
deleteMaintenanceWindowByIdParamValidation, deleteMaintenanceWindowByIdParamValidation,
} = require("../validation/joi"); } from "../validation/joi.js";
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
const { getTokenFromHeaders } = require("../utils/utils"); import { getTokenFromHeaders } from "../utils/utils.js";
const { successMessages } = require("../utils/messages"); import { successMessages } from "../utils/messages.js";
const { handleValidationError, handleError } = require("./controllerUtils"); import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "maintenanceWindowController"; const SERVICE_NAME = "maintenanceWindowController";
const createMaintenanceWindows = async (req, res, next) => { const createMaintenanceWindows = async (req, res, next) => {
@@ -54,9 +55,7 @@ const getMaintenanceWindowById = async (req, res, next) => {
return; return;
} }
try { try {
const maintenanceWindow = await req.db.getMaintenanceWindowById( const maintenanceWindow = await req.db.getMaintenanceWindowById(req.params.id);
req.params.id
);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID, msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID,
@@ -96,9 +95,7 @@ const getMaintenanceWindowsByTeamId = async (req, res, next) => {
const getMaintenanceWindowsByMonitorId = async (req, res, next) => { const getMaintenanceWindowsByMonitorId = async (req, res, next) => {
try { try {
await getMaintenanceWindowsByMonitorIdParamValidation.validateAsync( await getMaintenanceWindowsByMonitorIdParamValidation.validateAsync(req.params);
req.params
);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
@@ -160,7 +157,7 @@ const editMaintenanceWindow = async (req, res, next) => {
} }
}; };
module.exports = { export {
createMaintenanceWindows, createMaintenanceWindows,
getMaintenanceWindowById, getMaintenanceWindowById,
getMaintenanceWindowsByTeamId, getMaintenanceWindowsByTeamId,
+15 -23
View File
@@ -1,4 +1,4 @@
const { import {
getMonitorByIdParamValidation, getMonitorByIdParamValidation,
getMonitorByIdQueryValidation, getMonitorByIdQueryValidation,
getMonitorsByTeamIdValidation, getMonitorsByTeamIdValidation,
@@ -11,15 +11,15 @@ const {
getMonitorStatsByIdParamValidation, getMonitorStatsByIdParamValidation,
getMonitorStatsByIdQueryValidation, getMonitorStatsByIdQueryValidation,
getCertificateParamValidation, getCertificateParamValidation,
} = require("../validation/joi"); } from "../validation/joi.js";
import sslChecker from "ssl-checker";
const sslChecker = require("ssl-checker");
const SERVICE_NAME = "monitorController"; const SERVICE_NAME = "monitorController";
const { errorMessages, successMessages } = require("../utils/messages"); import { errorMessages, successMessages } from "../utils/messages.js";
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
const { getTokenFromHeaders } = require("../utils/utils"); import { getTokenFromHeaders } from "../utils/utils.js";
const logger = require("../utils/logger"); import logger from "../utils/logger.js";
const { handleError, handleValidationError } = require("./controllerUtils"); import { handleError, handleValidationError } from "./controllerUtils.js";
/** /**
* Returns all monitors * Returns all monitors
@@ -73,7 +73,7 @@ const getMonitorStatsById = async (req, res, next) => {
} }
}; };
const getMonitorCertificate = async (req, res, next) => { const getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) => {
try { try {
await getCertificateParamValidation.validateAsync(req.params); await getCertificateParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
@@ -83,14 +83,13 @@ const getMonitorCertificate = async (req, res, next) => {
try { try {
const { monitorId } = req.params; const { monitorId } = req.params;
const monitor = await req.db.getMonitorById(monitorId); const monitor = await req.db.getMonitorById(monitorId);
const monitorUrl = new URL(monitor.url); const certificate = await fetchMonitorCertificate(sslChecker, monitor);
const certificate = await sslChecker(monitorUrl.hostname);
if (certificate && certificate.validTo) { if (certificate && certificate.validTo) {
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_CERTIFICATE, msg: successMessages.MONITOR_CERTIFICATE,
data: { data: {
certificateDate: new Date(certificate.validTo).toLocaleDateString(), certificateDate: new Date(certificate.validTo),
}, },
}); });
} else { } else {
@@ -158,9 +157,7 @@ const getMonitorById = async (req, res, next) => {
*/ */
const getMonitorsAndSummaryByTeamId = async (req, res, next) => { const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
try { try {
await getMonitorsAndSummaryByTeamIdParamValidation.validateAsync( await getMonitorsAndSummaryByTeamIdParamValidation.validateAsync(req.params);
req.params
);
await getMonitorsAndSummaryByTeamIdQueryValidation.validateAsync(req.query); await getMonitorsAndSummaryByTeamIdQueryValidation.validateAsync(req.query);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
@@ -170,10 +167,7 @@ const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
try { try {
const { teamId } = req.params; const { teamId } = req.params;
const { type } = req.query; const { type } = req.query;
const monitorsSummary = await req.db.getMonitorsAndSummaryByTeamId( const monitorsSummary = await req.db.getMonitorsAndSummaryByTeamId(teamId, type);
teamId,
type
);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_GET_BY_USER_ID(teamId), msg: successMessages.MONITOR_GET_BY_USER_ID(teamId),
@@ -300,9 +294,7 @@ const deleteMonitor = async (req, res, next) => {
} }
); );
} }
return res return res.status(200).json({ success: true, msg: successMessages.MONITOR_DELETE });
.status(200)
.json({ success: true, msg: successMessages.MONITOR_DELETE });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "deleteMonitor")); next(handleError(error, SERVICE_NAME, "deleteMonitor"));
} }
@@ -477,7 +469,7 @@ const addDemoMonitors = async (req, res, next) => {
} }
}; };
module.exports = { export {
getAllMonitors, getAllMonitors,
getMonitorStatsById, getMonitorStatsById,
getMonitorCertificate, getMonitorCertificate,
+5 -11
View File
@@ -1,5 +1,6 @@
const { handleError } = require("./controllerUtils"); import { handleError } from "./controllerUtils.js";
const { errorMessages, successMessages } = require("../utils/messages"); import { errorMessages, successMessages } from "../utils/messages.js";
const SERVICE_NAME = "JobQueueController"; const SERVICE_NAME = "JobQueueController";
const getMetrics = async (req, res, next) => { const getMetrics = async (req, res, next) => {
@@ -46,18 +47,11 @@ const addJob = async (req, res, next) => {
const obliterateQueue = async (req, res, next) => { const obliterateQueue = async (req, res, next) => {
try { try {
await req.jobQueue.obliterate(); await req.jobQueue.obliterate();
return res return res.status(200).json({ success: true, msg: successMessages.QUEUE_OBLITERATE });
.status(200)
.json({ success: true, msg: successMessages.QUEUE_OBLITERATE });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "obliterateQueue")); next(handleError(error, SERVICE_NAME, "obliterateQueue"));
return; return;
} }
}; };
module.exports = { export { getMetrics, getJobs, addJob, obliterateQueue };
getMetrics,
getJobs,
addJob,
obliterateQueue,
};
+4 -7
View File
@@ -1,7 +1,7 @@
const { successMessages } = require("../utils/messages"); import { successMessages } from "../utils/messages.js";
import { updateAppSettingsBodyValidation } from "../validation/joi.js";
import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "SettingsController"; const SERVICE_NAME = "SettingsController";
const { updateAppSettingsBodyValidation } = require("../validation/joi");
const { handleValidationError, handleError } = require("./controllerUtils");
const getAppSettings = async (req, res, next) => { const getAppSettings = async (req, res, next) => {
try { try {
@@ -39,7 +39,4 @@ const updateAppSettings = async (req, res, next) => {
} }
}; };
module.exports = { export { getAppSettings, updateAppSettings };
getAppSettings,
updateAppSettings,
};
+2 -2
View File
@@ -1,4 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const AppSettingsSchema = mongoose.Schema( const AppSettingsSchema = mongoose.Schema(
{ {
@@ -88,4 +88,4 @@ const AppSettingsSchema = mongoose.Schema(
} }
); );
module.exports = mongoose.model("AppSettings", AppSettingsSchema); export default mongoose.model("AppSettings", AppSettingsSchema);
+4 -5
View File
@@ -1,6 +1,6 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const EmailService = require("../../service/emailService"); import EmailService from "../../service/emailService.js";
const Notification = require("./Notification"); import Notification from "./Notification.js";
/** /**
* Check Schema for MongoDB collection. * Check Schema for MongoDB collection.
@@ -73,5 +73,4 @@ const CheckSchema = mongoose.Schema(
); );
CheckSchema.index({ createdAt: 1 }); CheckSchema.index({ createdAt: 1 });
export default mongoose.model("Check", CheckSchema);
module.exports = mongoose.model("Check", CheckSchema);
+2 -3
View File
@@ -1,5 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const InviteTokenSchema = mongoose.Schema( const InviteTokenSchema = mongoose.Schema(
{ {
email: { email: {
@@ -32,4 +31,4 @@ const InviteTokenSchema = mongoose.Schema(
} }
); );
module.exports = mongoose.model("InviteToken", InviteTokenSchema); export default mongoose.model("InviteToken", InviteTokenSchema);
+2 -3
View File
@@ -1,5 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
/** /**
* MaintenanceWindow Schema * MaintenanceWindow Schema
* @module MaintenanceWindow * @module MaintenanceWindow
@@ -66,4 +65,4 @@ const MaintenanceWindow = mongoose.Schema(
} }
); );
module.exports = mongoose.model("MaintenanceWindow", MaintenanceWindow); export default mongoose.model("MaintenanceWindow", MaintenanceWindow);
+3 -3
View File
@@ -1,5 +1,5 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const Notification = require("./Notification"); import Notification from "./Notification.js";
const MonitorSchema = mongoose.Schema( const MonitorSchema = mongoose.Schema(
{ {
@@ -60,4 +60,4 @@ const MonitorSchema = mongoose.Schema(
} }
); );
module.exports = mongoose.model("Monitor", MonitorSchema); export default mongoose.model("Monitor", MonitorSchema);
+2 -4
View File
@@ -1,5 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const NotificationSchema = mongoose.Schema( const NotificationSchema = mongoose.Schema(
{ {
monitorId: { monitorId: {
@@ -22,5 +21,4 @@ const NotificationSchema = mongoose.Schema(
timestamps: true, timestamps: true,
} }
); );
export default mongoose.model("Notification", NotificationSchema);
module.exports = mongoose.model("Notification", NotificationSchema);
+2 -3
View File
@@ -1,5 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const AuditSchema = mongoose.Schema({ const AuditSchema = mongoose.Schema({
id: { type: String, required: true }, id: { type: String, required: true },
title: { type: String, required: true }, title: { type: String, required: true },
@@ -109,4 +108,4 @@ PageSpeedCheck.pre("save", async function (next) {
} }
}); });
module.exports = mongoose.model("PageSpeedCheck", PageSpeedCheck); export default mongoose.model("PageSpeedCheck", PageSpeedCheck);
+2 -2
View File
@@ -1,4 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const RecoveryTokenSchema = mongoose.Schema( const RecoveryTokenSchema = mongoose.Schema(
{ {
@@ -22,4 +22,4 @@ const RecoveryTokenSchema = mongoose.Schema(
} }
); );
module.exports = mongoose.model("RecoveryToken", RecoveryTokenSchema); export default mongoose.model("RecoveryToken", RecoveryTokenSchema);
+2 -4
View File
@@ -1,5 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const TeamSchema = mongoose.Schema( const TeamSchema = mongoose.Schema(
{ {
email: { email: {
@@ -12,5 +11,4 @@ const TeamSchema = mongoose.Schema(
timestamps: true, timestamps: true,
} }
); );
export default mongoose.model("Team", TeamSchema);
module.exports = mongoose.model("Team", TeamSchema);
+4 -4
View File
@@ -1,5 +1,5 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const bcrypt = require("bcrypt"); import bcrypt from "bcrypt";
const UserSchema = mongoose.Schema( const UserSchema = mongoose.Schema(
{ {
@@ -74,7 +74,7 @@ UserSchema.pre("findOneAndUpdate", async function (next) {
}); });
UserSchema.methods.comparePassword = async function (submittedPassword) { UserSchema.methods.comparePassword = async function (submittedPassword) {
res = await bcrypt.compare(submittedPassword, this.password); const res = await bcrypt.compare(submittedPassword, this.password);
return res; return res;
}; };
@@ -84,4 +84,4 @@ User.init().then(() => {
console.log("User model initialized"); console.log("User model initialized");
}); });
module.exports = mongoose.model("User", UserSchema); export default mongoose.model("User", UserSchema);
+21 -24
View File
@@ -1,6 +1,6 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const UserModel = require("../models/User"); import UserModel from "../models/User.js";
const AppSettings = require("../models/AppSettings"); import AppSettings from "../models/AppSettings.js";
//**************************************** //****************************************
// DB Connection // DB Connection
@@ -41,7 +41,7 @@ const checkSuperadmin = async (req, res) => {
// User Operations // User Operations
//**************************************** //****************************************
const { import {
insertUser, insertUser,
getUserByEmail, getUserByEmail,
updateUser, updateUser,
@@ -50,32 +50,32 @@ const {
deleteAllOtherUsers, deleteAllOtherUsers,
getAllUsers, getAllUsers,
logoutUser, logoutUser,
} = require("./modules/userModule"); } from "./modules/userModule.js";
//**************************************** //****************************************
// Invite Token Operations // Invite Token Operations
//**************************************** //****************************************
const { import {
requestInviteToken, requestInviteToken,
getInviteToken, getInviteToken,
getInviteTokenAndDelete, getInviteTokenAndDelete,
} = require("./modules/inviteModule"); } from "./modules/inviteModule.js";
//**************************************** //****************************************
// Recovery Operations // Recovery Operations
//**************************************** //****************************************
const { import {
requestRecoveryToken, requestRecoveryToken,
validateRecoveryToken, validateRecoveryToken,
resetPassword, resetPassword,
} = require("./modules/recoveryModule"); } from "./modules/recoveryModule.js";
//**************************************** //****************************************
// Monitors // Monitors
//**************************************** //****************************************
const { import {
getAllMonitors, getAllMonitors,
getMonitorStatsById, getMonitorStatsById,
getMonitorById, getMonitorById,
@@ -87,23 +87,23 @@ const {
deleteMonitorsByUserId, deleteMonitorsByUserId,
editMonitor, editMonitor,
addDemoMonitors, addDemoMonitors,
} = require("./modules/monitorModule"); } from "./modules/monitorModule.js";
//**************************************** //****************************************
// Page Speed Checks // Page Speed Checks
//**************************************** //****************************************
const { import {
createPageSpeedCheck, createPageSpeedCheck,
getPageSpeedChecks, getPageSpeedChecks,
deletePageSpeedChecksByMonitorId, deletePageSpeedChecksByMonitorId,
} = require("./modules/pageSpeedCheckModule"); } from "./modules/pageSpeedCheckModule.js";
//**************************************** //****************************************
// Checks // Checks
//**************************************** //****************************************
const { import {
createCheck, createCheck,
getChecksCount, getChecksCount,
getChecks, getChecks,
@@ -111,12 +111,12 @@ const {
deleteChecks, deleteChecks,
deleteChecksByTeamId, deleteChecksByTeamId,
updateChecksTTL, updateChecksTTL,
} = require("./modules/checkModule"); } from "./modules/checkModule.js";
//**************************************** //****************************************
// Maintenance Window // Maintenance Window
//**************************************** //****************************************
const { import {
createMaintenanceWindow, createMaintenanceWindow,
getMaintenanceWindowById, getMaintenanceWindowById,
getMaintenanceWindowsByTeamId, getMaintenanceWindowsByTeamId,
@@ -125,26 +125,23 @@ const {
deleteMaintenanceWindowByMonitorId, deleteMaintenanceWindowByMonitorId,
deleteMaintenanceWindowByUserId, deleteMaintenanceWindowByUserId,
editMaintenanceWindowById, editMaintenanceWindowById,
} = require("./modules/maintenanceWindowModule"); } from "./modules/maintenanceWindowModule.js";
//**************************************** //****************************************
// Notifications // Notifications
//**************************************** //****************************************
const { import {
createNotification, createNotification,
getNotificationsByMonitorId, getNotificationsByMonitorId,
deleteNotificationsByMonitorId, deleteNotificationsByMonitorId,
} = require("./modules/notificationModule"); } from "./modules/notificationModule.js";
//**************************************** //****************************************
// AppSettings // AppSettings
//**************************************** //****************************************
const { import { getAppSettings, updateAppSettings } from "./modules/settingsModule.js";
getAppSettings,
updateAppSettings,
} = require("./modules/settingsModule");
module.exports = { export default {
connect, connect,
insertUser, insertUser,
getUserByEmail, getUserByEmail,
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff. Show more