Compare commits
272
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
08e4b0c39e | ||
|
|
a46e282633 | ||
|
|
8b7fd826b3 | ||
|
|
264e6f7d1f | ||
|
|
fafd581f06 | ||
|
|
d69cec9730 | ||
|
|
1552018796 | ||
|
|
3fc4160b88 | ||
|
|
9ca79ea793 | ||
|
|
2e3b32462f | ||
|
|
7e527b8eb2 | ||
|
|
021b4e8ae5 | ||
|
|
b6004241e7 | ||
|
|
af4c9d8f91 | ||
|
|
f2b740a8f9 | ||
|
|
b26d135a4f | ||
|
|
4f4203dbb3 | ||
|
|
4945b29334 | ||
|
|
1808db5cd7 | ||
|
|
31cc9cd294 | ||
|
|
19b370d89b | ||
|
|
8555e7c122 | ||
|
|
734ec41ca0 | ||
|
|
5152336591 | ||
|
|
78b920aaf6 | ||
|
|
2d84fae470 | ||
|
|
97e4b105a2 | ||
|
|
a053386f4a | ||
|
|
e0991e28e5 | ||
|
|
0f26648855 | ||
|
|
6a0f3426b3 | ||
|
|
16e8035299 | ||
|
|
31b09c316a | ||
|
|
8f2072e497 | ||
|
|
514570da78 | ||
|
|
ea68e660fc | ||
|
|
527543d79f | ||
|
|
1c390a8baf | ||
|
|
43ac5b57cf | ||
|
|
1558b27497 | ||
|
|
9caa6c830f | ||
|
|
ea115ede53 | ||
|
|
8470631162 | ||
|
|
597732e109 | ||
|
|
9974fa4010 | ||
|
|
b0686c0576 | ||
|
|
a148f56b22 | ||
|
|
3b25b37c22 | ||
|
|
1e04345aa0 | ||
|
|
174c3cd47a | ||
|
|
0e149fa477 | ||
|
|
5b4a99af3d | ||
|
|
2ecdc2096e | ||
|
|
6e66a18535 | ||
|
|
bd6aa0fa3a | ||
|
|
4e678a4ce7 | ||
|
|
5999315791 | ||
|
|
0c8b8a9358 | ||
|
|
dfe62bd301 | ||
|
|
747ff824cc | ||
|
|
f12c544751 | ||
|
|
278ced2a6c | ||
|
|
88d539b2a4 | ||
|
|
f0b152fc8f | ||
|
|
dc0e198a8e | ||
|
|
0a5067ef46 | ||
|
|
4f0017c031 | ||
|
|
f0b2292f0a | ||
|
|
d74d79c332 | ||
|
|
1a096b66f7 | ||
|
|
7cb866ce4a | ||
|
|
c54582ca70 | ||
|
|
362034ba26 | ||
|
|
b536099d03 | ||
|
|
04fef2ef75 | ||
|
|
a89e5ed565 | ||
|
|
ca153b65a9 | ||
|
|
cc188b2ba3 | ||
|
|
18018ceef1 | ||
|
|
189f309631 | ||
|
|
97dd3ec9cb | ||
|
|
b4c929963f | ||
|
|
4ecc737438 | ||
|
|
bc58f6e08e | ||
|
|
4f3bcd4624 | ||
|
|
d469590ef3 | ||
|
|
35eba6897a | ||
|
|
667dc55fc8 | ||
|
|
f2d2687d2a | ||
|
|
4e3e580179 | ||
|
|
4080ac8c2c | ||
|
|
0a408f8cfd | ||
|
|
e3921beac4 | ||
|
|
4c284493ba | ||
|
|
0fcceeb7a6 | ||
|
|
f799d46025 | ||
|
|
a80df60fc1 | ||
|
|
cbec0fa065 | ||
|
|
40e5550e0f | ||
|
|
90fd9930db | ||
|
|
f10f7385b0 | ||
|
|
2d85abf030 | ||
|
|
3c0c470ca3 | ||
|
|
4c5cae8722 | ||
|
|
8650f30d12 | ||
|
|
09e37f4356 | ||
|
|
6bc8a521c9 | ||
|
|
a1e6eaa9d0 | ||
|
|
bbb61a6f88 | ||
|
|
c1d2041482 | ||
|
|
7aa05c7f85 | ||
|
|
539866e119 | ||
|
|
6f0ff1583e | ||
|
|
12b61d17f2 | ||
|
|
7426418629 | ||
|
|
3566da7515 | ||
|
|
b451489bd8 | ||
|
|
d4a0489275 | ||
|
|
080c91284d | ||
|
|
dadc74373c | ||
|
|
6fdea04416 | ||
|
|
67963823d9 | ||
|
|
ab12a9bd3a | ||
|
|
3b25c50247 | ||
|
|
63e42b7276 | ||
|
|
090d002578 | ||
|
|
ae7524f507 | ||
|
|
54d71bef61 | ||
|
|
a77c74b17c | ||
|
|
f2363a7a09 | ||
|
|
69f95723f1 | ||
|
|
1fefb038f0 | ||
|
|
85190992c7 | ||
|
|
efe87b599f | ||
|
|
ed1bcf97da | ||
|
|
56ead03416 | ||
|
|
a912a5ebb8 | ||
|
|
0fd4173816 | ||
|
|
75d3644b36 | ||
|
|
853e21623e | ||
|
|
57c3bf3240 | ||
|
|
6be1eb0a3e | ||
|
|
9d70623e0f | ||
|
|
43fe66022b | ||
|
|
294fb13005 | ||
|
|
8028cab487 | ||
|
|
8160ab4a3c | ||
|
|
6063532c79 | ||
|
|
83b628c8f9 | ||
|
|
88a91022c3 | ||
|
|
5822a363a9 | ||
|
|
464b16ec9d | ||
|
|
d54c90d511 | ||
|
|
3a5783fe91 | ||
|
|
479f22ac69 | ||
|
|
30202b2249 | ||
|
|
888910abb2 | ||
|
|
874d1b277a | ||
|
|
f34520cdbf | ||
|
|
f420044b64 | ||
|
|
53d5ae2251 | ||
|
|
bcc57c7135 | ||
|
|
6b67f4977f | ||
|
|
87255071f4 | ||
|
|
cbf1f97591 | ||
|
|
7a881fda03 | ||
|
|
50fd66ef56 | ||
|
|
f9b677b1ad | ||
|
|
b7a6d50c73 | ||
|
|
04bd7f0e2e | ||
|
|
2e7aba788d | ||
|
|
e1665b29af | ||
|
|
17450e2537 | ||
|
|
270293a2b5 | ||
|
|
a7c5b0c7fb | ||
|
|
e804c35c3a | ||
|
|
5c4133097d | ||
|
|
85f93cd6d2 | ||
|
|
d4db32e392 | ||
|
|
791b9fc7a2 | ||
|
|
206c5577a6 | ||
|
|
cbd0530d85 | ||
|
|
45ef2438de | ||
|
|
ec818eaacb | ||
|
|
91bb60f2ff | ||
|
|
443ad46fa7 | ||
|
|
f685c9cd5d | ||
|
|
0263c17618 | ||
|
|
5a12e36c7e | ||
|
|
67da6c61cf | ||
|
|
f538f61464 | ||
|
|
f6971ede69 | ||
|
|
e69283e3ed | ||
|
|
084eed85bf | ||
|
|
9a42fb031f | ||
|
|
943e88c54d | ||
|
|
24ce64b439 | ||
|
|
841d25ce3e | ||
|
|
84e4ea7b64 | ||
|
|
4b92dbd19b | ||
|
|
5eb1d54d65 | ||
|
|
a0aee182de | ||
|
|
2dca5ccb67 | ||
|
|
348eea5475 | ||
|
|
2a3683c74a | ||
|
|
806d7ae456 | ||
|
|
cac502573f | ||
|
|
830318edc3 | ||
|
|
86a55e3cfe | ||
|
|
796960aeb2 | ||
|
|
a25ff03b71 | ||
|
|
22ae6b4be6 | ||
|
|
0b5e28c296 | ||
|
|
c5c91e28f8 | ||
|
|
3ba3e4b865 | ||
|
|
77fa394004 | ||
|
|
c0ba278e47 | ||
|
|
73f41906b0 | ||
|
|
cb5af2741d | ||
|
|
af4ef87966 | ||
|
|
a154ad11b5 | ||
|
|
1bfd1c9119 | ||
|
|
fc98192bcf | ||
|
|
b1db74d96f | ||
|
|
c1258d3cdf | ||
|
|
6ffa5ac648 | ||
|
|
6395e8a10e | ||
|
|
2852d2cdce | ||
|
|
363baef7b1 | ||
|
|
a1973a6d2b | ||
|
|
12f02d6eea | ||
|
|
a6c291c8ef | ||
|
|
227dc9e7e8 | ||
|
|
38ef9ccad3 | ||
|
|
353b97e7d3 | ||
|
|
9b871ffb52 | ||
|
|
cb392eaaba | ||
|
|
dcf5a77923 | ||
|
|
ec03addba6 | ||
|
|
eefdb8d253 | ||
|
|
e539f40612 | ||
|
|
c18159afd3 | ||
|
|
5596e45ff3 | ||
|
|
bde13f4fa7 | ||
|
|
7f1c996632 | ||
|
|
396d5b369b | ||
|
|
bb8cc8b464 | ||
|
|
66efa25e2b | ||
|
|
7bef6dc0e6 | ||
|
|
1c341a4e3d | ||
|
|
f41f2322cf | ||
|
|
b653f26c96 | ||
|
|
ece1dadb78 | ||
|
|
1f003c4d48 | ||
|
|
5a468d717a | ||
|
|
975d134dd8 | ||
|
|
7a66b5310b | ||
|
|
fcfad945a0 | ||
|
|
6b4032ecfe | ||
|
|
41d6c092d4 | ||
|
|
f9e366e181 | ||
|
|
07705e9823 | ||
|
|
c48049e0af | ||
|
|
f3ba8c9815 | ||
|
|
f88e4ee6f4 | ||
|
|
300b1b2238 | ||
|
|
04cf47544a | ||
|
|
e1dfd98840 | ||
|
|
4ce4a124d6 | ||
|
|
f564636cb4 | ||
|
|
14a08a303b | ||
|
|
4645bde025 |
No files matched your search
@@ -3,3 +3,4 @@
|
||||
.VSCodeCounter
|
||||
*.sh
|
||||
mongo
|
||||
node_modules/
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
echo "Running lint-staged..."
|
||||
cd client && npx lint-staged && cd ..
|
||||
cd server && npx lint-staged && cd ..
|
||||
@@ -79,9 +79,8 @@ You can see the memory footprint of MongoDB and Redis on the same server (398Mb
|
||||
|
||||
If you have any questions, suggestions or comments, you have several options:
|
||||
|
||||
- [Discord channel](https://discord.gg/NAb6H3UTjK)
|
||||
- [GitHub Discussions](https://github.com/bluewave-labs/bluewave-uptime/discussions)
|
||||
- [Reddit group](https://www.reddit.com/r/CheckmateMonitoring/)
|
||||
- [Discord channel](https://discord.gg/NAb6H3UTjK) (preferred)
|
||||
- [GitHub Discussions](https://github.com/bluewave-labs/bluewave-uptime/discussions) (we check here from time to time)
|
||||
|
||||
Feel free to ask questions or share your ideas - we'd love to hear from you!
|
||||
|
||||
|
||||
Generated
+1133
-1722
File diff suppressed because it is too large.
Load diff
+12
-7
@@ -12,15 +12,18 @@
|
||||
"format": "prettier --write .",
|
||||
"format-check": "prettier --check ."
|
||||
},
|
||||
"lint-staged": {
|
||||
"**/*": "npm run format"
|
||||
},
|
||||
"dependencies": {
|
||||
"@emotion/react": "^11.13.3",
|
||||
"@emotion/styled": "^11.13.0",
|
||||
"@hello-pangea/dnd": "^18.0.0",
|
||||
"@hookform/resolvers": "5.2.2",
|
||||
"@mui/lab": "6.0.0-dev.240424162023-9968b4889d",
|
||||
"@mui/material": "6.4.11",
|
||||
"@mui/x-charts": "^7.5.1",
|
||||
"@mui/x-date-pickers": "7.29.0",
|
||||
"@mui/lab": "7.0.0",
|
||||
"@mui/material": "7.3.7",
|
||||
"@mui/x-charts": "7.29.1",
|
||||
"@mui/x-date-pickers": "7.29.4",
|
||||
"@reduxjs/toolkit": "2.7.0",
|
||||
"axios": "^1.7.4",
|
||||
"dayjs": "1.11.13",
|
||||
@@ -30,11 +33,12 @@
|
||||
"i18next": "25.4.2",
|
||||
"joi": "17.13.3",
|
||||
"lucide-react": "^0.562.0",
|
||||
"mui-color-input": "^6.0.0",
|
||||
"mui-color-input": "^7.0.0",
|
||||
"pretty-bytes": "^7.1.0",
|
||||
"pretty-ms": "^9.3.0",
|
||||
"react": "18.3.1",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-hook-form": "7.63.0",
|
||||
"react-hook-form": "^7.63.0",
|
||||
"react-i18next": "^15.4.0",
|
||||
"react-icons": "5.5.0",
|
||||
"react-redux": "9.2.0",
|
||||
@@ -45,7 +49,7 @@
|
||||
"redux-persist": "6.0.0",
|
||||
"swr": "^2.3.6",
|
||||
"vite-plugin-svgr": "^4.2.0",
|
||||
"zod": "4.1.11"
|
||||
"zod": "^4.1.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "24.5.2",
|
||||
@@ -56,6 +60,7 @@
|
||||
"eslint-plugin-react": "^7.34.1",
|
||||
"eslint-plugin-react-hooks": "^5.0.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.6",
|
||||
"lint-staged": "^16.2.7",
|
||||
"prettier": "^3.3.3",
|
||||
"typescript": "5.9.3",
|
||||
"vite": "6.3.6"
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
import { Checkbox, FormControl, ListItemText, MenuItem, Select } from "@mui/material";
|
||||
import { useTheme } from "@emotion/react";
|
||||
import PropTypes from "prop-types";
|
||||
import Icon from "../Icon";
|
||||
|
||||
/**
|
||||
* A reusable filter header component that displays a dropdown menu with selectable options.
|
||||
*
|
||||
* @component
|
||||
* @param {Object} props - The component props.
|
||||
* @param {string} props.header - The header text to display when no options are selected.
|
||||
* @param {Array} props.options - An array of options to display in the dropdown menu. Each option should have a `value` and `label`.
|
||||
* @param {Array} [props.value] - The currently selected values.
|
||||
* @param {Function} props.onChange - The callback function to handle changes in the selected values.
|
||||
* @param {boolean} [props.multiple=true] - Whether multiple options can be selected.
|
||||
* @returns {JSX.Element} The rendered FilterHeader component.
|
||||
*/
|
||||
|
||||
const FilterHeader = ({ header, options, value, onChange, multiple = true }) => {
|
||||
const theme = useTheme();
|
||||
|
||||
const controlledValue = value === undefined ? [] : value; // Ensure value is always treated as an array for controlled component purposes
|
||||
|
||||
return (
|
||||
<FormControl
|
||||
sx={{ minWidth: "10%" }}
|
||||
size="small"
|
||||
>
|
||||
<Select
|
||||
multiple={multiple}
|
||||
IconComponent={(props) => (
|
||||
<Icon
|
||||
{...props}
|
||||
name="PlusCircle"
|
||||
size={18}
|
||||
/>
|
||||
)}
|
||||
displayEmpty
|
||||
value={controlledValue}
|
||||
onChange={onChange}
|
||||
renderValue={(selected) => {
|
||||
if (!selected?.length) {
|
||||
return header;
|
||||
}
|
||||
|
||||
return (
|
||||
header +
|
||||
" | " +
|
||||
selected
|
||||
.map((value) => options.find((option) => option.value === value)?.label)
|
||||
.filter(Boolean)
|
||||
.join(", ")
|
||||
);
|
||||
}}
|
||||
MenuProps={{
|
||||
anchorOrigin: {
|
||||
vertical: "bottom",
|
||||
horizontal: "left",
|
||||
},
|
||||
transformOrigin: {
|
||||
vertical: "top",
|
||||
horizontal: "left",
|
||||
},
|
||||
}}
|
||||
>
|
||||
{options.map((option) => (
|
||||
<MenuItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
sx={{
|
||||
height: theme.spacing(17),
|
||||
padding: 0,
|
||||
}}
|
||||
>
|
||||
<Checkbox
|
||||
checked={controlledValue.includes(option.value)}
|
||||
size="small"
|
||||
/>
|
||||
<ListItemText primary={option.label} />
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
);
|
||||
};
|
||||
|
||||
FilterHeader.propTypes = {
|
||||
header: PropTypes.string.isRequired,
|
||||
options: PropTypes.arrayOf(
|
||||
PropTypes.shape({
|
||||
value: PropTypes.string.isRequired,
|
||||
label: PropTypes.string.isRequired,
|
||||
})
|
||||
).isRequired,
|
||||
value: PropTypes.arrayOf(PropTypes.string),
|
||||
onChange: PropTypes.func.isRequired,
|
||||
multiple: PropTypes.bool,
|
||||
};
|
||||
|
||||
export default FilterHeader;
|
||||
@@ -1,119 +0,0 @@
|
||||
import * as React from "react";
|
||||
import Button from "@mui/material/Button";
|
||||
import ButtonGroup from "@mui/material/ButtonGroup";
|
||||
import Icon from "../Icon";
|
||||
import ClickAwayListener from "@mui/material/ClickAwayListener";
|
||||
import Grow from "@mui/material/Grow";
|
||||
import Paper from "@mui/material/Paper";
|
||||
import Popper from "@mui/material/Popper";
|
||||
import MenuItem from "@mui/material/MenuItem";
|
||||
import MenuList from "@mui/material/MenuList";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { createToast } from "../../../Utils/toastUtils.jsx";
|
||||
import { useExportMonitors } from "../../../Hooks/monitorHooks.js";
|
||||
|
||||
const MonitorActions = ({ isLoading }) => {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const anchorRef = React.useRef(null);
|
||||
const [selectedIndex, setSelectedIndex] = React.useState(0);
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation();
|
||||
const [exportMonitors, isExporting] = useExportMonitors();
|
||||
|
||||
const options = [t("monitorActions.import"), t("monitorActions.export")];
|
||||
|
||||
const handleClick = async () => {
|
||||
if (selectedIndex === 0) {
|
||||
// Import
|
||||
navigate("/uptime/bulk-import");
|
||||
} else {
|
||||
// Export
|
||||
const [success, error] = await exportMonitors();
|
||||
if (!success) {
|
||||
createToast({ body: error || t("export.failed") });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleMenuItemClick = (event, index) => {
|
||||
setSelectedIndex(index);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleToggle = () => {
|
||||
setOpen((prevOpen) => !prevOpen);
|
||||
};
|
||||
|
||||
const handleClose = (event) => {
|
||||
if (anchorRef.current && anchorRef.current.contains(event.target)) {
|
||||
return;
|
||||
}
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<React.Fragment>
|
||||
<ButtonGroup
|
||||
variant="contained"
|
||||
color="accent"
|
||||
ref={anchorRef}
|
||||
aria-label="Monitor actions"
|
||||
disabled={isLoading || isExporting}
|
||||
>
|
||||
<Button onClick={handleClick}>{options[selectedIndex]}</Button>
|
||||
<Button
|
||||
size="small"
|
||||
aria-controls={open ? "split-button-menu" : undefined}
|
||||
aria-expanded={open ? "true" : undefined}
|
||||
aria-label="select monitor action"
|
||||
aria-haspopup="menu"
|
||||
onClick={handleToggle}
|
||||
>
|
||||
<Icon
|
||||
name="ChevronDown"
|
||||
size={20}
|
||||
/>
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
<Popper
|
||||
sx={{ zIndex: 1 }}
|
||||
open={open}
|
||||
anchorEl={anchorRef.current}
|
||||
role={undefined}
|
||||
transition
|
||||
disablePortal
|
||||
>
|
||||
{({ TransitionProps, placement }) => (
|
||||
<Grow
|
||||
{...TransitionProps}
|
||||
style={{
|
||||
transformOrigin: placement === "bottom" ? "center top" : "center bottom",
|
||||
}}
|
||||
>
|
||||
<Paper>
|
||||
<ClickAwayListener onClickAway={handleClose}>
|
||||
<MenuList
|
||||
id="split-button-menu"
|
||||
autoFocusItem
|
||||
>
|
||||
{options.map((option, index) => (
|
||||
<MenuItem
|
||||
key={option}
|
||||
selected={index === selectedIndex}
|
||||
onClick={(event) => handleMenuItemClick(event, index)}
|
||||
>
|
||||
{option}
|
||||
</MenuItem>
|
||||
))}
|
||||
</MenuList>
|
||||
</ClickAwayListener>
|
||||
</Paper>
|
||||
</Grow>
|
||||
)}
|
||||
</Popper>
|
||||
</React.Fragment>
|
||||
);
|
||||
};
|
||||
|
||||
export default MonitorActions;
|
||||
@@ -1,52 +0,0 @@
|
||||
import { Stack, Typography } from "@mui/material";
|
||||
import PropTypes from "prop-types";
|
||||
import { useTheme } from "@emotion/react";
|
||||
import SkeletonLayout from "./skeleton.jsx";
|
||||
|
||||
const MonitorCountHeader = ({
|
||||
isLoading = false,
|
||||
monitorCount,
|
||||
heading = "monitors",
|
||||
sx,
|
||||
children,
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
if (isLoading) return <SkeletonLayout />;
|
||||
|
||||
if (monitorCount === 1) {
|
||||
heading = "monitor";
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack
|
||||
direction="row"
|
||||
alignItems="center"
|
||||
display="flex"
|
||||
width="fit-content"
|
||||
height={theme.spacing(18)}
|
||||
gap={theme.spacing(2)}
|
||||
mt={theme.spacing(2)}
|
||||
px={theme.spacing(4)}
|
||||
pt={theme.spacing(2)}
|
||||
pb={theme.spacing(3)}
|
||||
borderRadius={theme.spacing(1)}
|
||||
sx={{
|
||||
...sx,
|
||||
backgroundColor: theme.palette.secondary.main,
|
||||
}}
|
||||
>
|
||||
{monitorCount} <Typography component="h2">{heading}</Typography>
|
||||
{children}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
MonitorCountHeader.propTypes = {
|
||||
isLoading: PropTypes.bool,
|
||||
monitorCount: PropTypes.number,
|
||||
heading: PropTypes.string,
|
||||
children: PropTypes.node,
|
||||
sx: PropTypes.object,
|
||||
};
|
||||
|
||||
export default MonitorCountHeader;
|
||||
@@ -1,26 +0,0 @@
|
||||
import { Stack, Skeleton } from "@mui/material";
|
||||
import { useTheme } from "@emotion/react";
|
||||
|
||||
const SkeletonLayout = () => {
|
||||
const theme = useTheme();
|
||||
return (
|
||||
<Stack
|
||||
direction="row"
|
||||
alignItems="center"
|
||||
gap={theme.spacing(2)}
|
||||
>
|
||||
<Skeleton
|
||||
variant="text"
|
||||
width={100}
|
||||
height={32}
|
||||
/>
|
||||
<Skeleton
|
||||
variant="circular"
|
||||
width={40}
|
||||
height={40}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export default SkeletonLayout;
|
||||
@@ -3,7 +3,6 @@ import { useNavigate } from "react-router-dom";
|
||||
import PropTypes from "prop-types";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useTheme } from "@emotion/react";
|
||||
import MonitorActions from "../MonitorActions/index.jsx";
|
||||
|
||||
const CreateMonitorHeader = ({ isAdmin, label, isLoading = true, path, bulkPath }) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
@@ -1,158 +0,0 @@
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Status from "./status.jsx";
|
||||
import Skeleton from "./skeleton.jsx";
|
||||
import Button from "@mui/material/Button";
|
||||
import { Tooltip } from "@mui/material";
|
||||
import Icon from "../Icon";
|
||||
|
||||
// Utils
|
||||
import PropTypes from "prop-types";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import { usePauseMonitor } from "../../../Hooks/monitorHooks.js";
|
||||
import { useSendTestEmail } from "../../../Hooks/useSendTestEmail.js";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useTestAllNotifications } from "../../../Hooks/useNotifications.js";
|
||||
/**
|
||||
* MonitorDetailsControlHeader component displays the control header for monitor details.
|
||||
* It includes status display, pause/resume button, and a configure button for admins.
|
||||
*
|
||||
* @component
|
||||
* @param {Object} props - Component props
|
||||
* @param {string} props.path - The base path for navigation
|
||||
* @param {boolean} [props.isLoading=false] - Flag indicating if the data is loading
|
||||
* @param {boolean} [props.isAdmin=false] - Flag indicating if the user is an admin
|
||||
* @param {Object} props.monitor - The monitor object containing details
|
||||
* @param {Function} props.triggerUpdate - Function to trigger an update
|
||||
* @returns {JSX.Element} The rendered component
|
||||
*/
|
||||
const MonitorDetailsControlHeader = ({
|
||||
path,
|
||||
isLoading = false,
|
||||
isAdmin = false,
|
||||
monitor,
|
||||
triggerUpdate,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const [pauseMonitor, isPausing, error] = usePauseMonitor();
|
||||
|
||||
const isTestNotificationsDisabled = monitor?.notifications?.length === 0;
|
||||
|
||||
const tooltipTitle = isTestNotificationsDisabled ? t("testNotificationsDisabled") : "";
|
||||
|
||||
// const [isSending, emailError, sendTestEmail] = useSendTestEmail();
|
||||
|
||||
const [testAllNotifications, isSending, errorAllNotifications] =
|
||||
useTestAllNotifications();
|
||||
|
||||
if (isLoading) {
|
||||
return <Skeleton />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack
|
||||
direction="row"
|
||||
justifyContent="space-between"
|
||||
>
|
||||
<Status monitor={monitor} />
|
||||
|
||||
<Stack
|
||||
direction="row"
|
||||
gap={theme.spacing(2)}
|
||||
>
|
||||
<Tooltip
|
||||
key={monitor?.id}
|
||||
placement="bottom"
|
||||
title={tooltipTitle}
|
||||
>
|
||||
<span>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="secondary"
|
||||
loading={isSending}
|
||||
startIcon={
|
||||
<Icon
|
||||
name="Mail"
|
||||
size={18}
|
||||
/>
|
||||
}
|
||||
disabled={isTestNotificationsDisabled}
|
||||
onClick={() => {
|
||||
testAllNotifications({ monitorId: monitor?.id });
|
||||
}}
|
||||
sx={{
|
||||
whiteSpace: "nowrap",
|
||||
}}
|
||||
>
|
||||
{t("sendTestNotifications")}
|
||||
</Button>
|
||||
</span>
|
||||
</Tooltip>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="secondary"
|
||||
onClick={(e) => {
|
||||
navigate(`/incidents/${monitor?.id}`);
|
||||
}}
|
||||
>
|
||||
{t("menu.incidents")}
|
||||
</Button>
|
||||
{isAdmin && (
|
||||
<Button
|
||||
variant="contained"
|
||||
color="secondary"
|
||||
loading={isPausing}
|
||||
startIcon={
|
||||
monitor?.isActive ? (
|
||||
<Icon
|
||||
name="Pause"
|
||||
size={18}
|
||||
/>
|
||||
) : (
|
||||
<Icon
|
||||
name="Play"
|
||||
size={18}
|
||||
/>
|
||||
)
|
||||
}
|
||||
onClick={() => {
|
||||
pauseMonitor({
|
||||
monitorId: monitor?.id,
|
||||
triggerUpdate,
|
||||
});
|
||||
}}
|
||||
>
|
||||
{monitor?.isActive ? t("pause") : t("resume")}
|
||||
</Button>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<Button
|
||||
variant="contained"
|
||||
color="secondary"
|
||||
startIcon={
|
||||
<Icon
|
||||
name="Settings"
|
||||
size={18}
|
||||
/>
|
||||
}
|
||||
onClick={() => navigate(`/${path}/configure/${monitor.id}`)}
|
||||
>
|
||||
Configure
|
||||
</Button>
|
||||
)}
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
MonitorDetailsControlHeader.propTypes = {
|
||||
path: PropTypes.string,
|
||||
isLoading: PropTypes.bool,
|
||||
isAdmin: PropTypes.bool,
|
||||
monitor: PropTypes.object,
|
||||
triggerUpdate: PropTypes.func,
|
||||
};
|
||||
|
||||
export default MonitorDetailsControlHeader;
|
||||
@@ -1,23 +0,0 @@
|
||||
import { Stack, Skeleton } from "@mui/material";
|
||||
|
||||
const SkeletonLayout = () => {
|
||||
return (
|
||||
<Stack
|
||||
direction="row"
|
||||
justifyContent="space-between"
|
||||
>
|
||||
<Skeleton
|
||||
height={40}
|
||||
variant="rounded"
|
||||
width="15%"
|
||||
/>
|
||||
<Skeleton
|
||||
height={40}
|
||||
variant="rounded"
|
||||
width="15%"
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export default SkeletonLayout;
|
||||
@@ -1,51 +0,0 @@
|
||||
// Components
|
||||
import Stack from "@mui/material/Stack";
|
||||
import PulseDot from "../Animated/PulseDot.jsx";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import Dot from "../Dot/index.jsx";
|
||||
// Utils
|
||||
import { formatDurationRounded } from "../../../Utils/timeUtilsLegacy.js";
|
||||
import PropTypes from "prop-types";
|
||||
import { useTheme } from "@emotion/react";
|
||||
import { useMonitorUtils } from "../../../Hooks/useMonitorUtils.js";
|
||||
import { formatMonitorUrl } from "../../../Utils/utils.js";
|
||||
/**
|
||||
* Status component displays the status information of a monitor.
|
||||
* It includes the monitor's name, URL, and check interval.
|
||||
*
|
||||
* @component
|
||||
* @param {Object} props - Component props
|
||||
* @param {Object} props.monitor - The monitor object containing details
|
||||
* @param {string} props.monitor.name - The name of the monitor
|
||||
* @param {string} props.monitor.url - The URL of the monitor
|
||||
* @param {number} props.monitor.interval - The interval at which the monitor checks
|
||||
* @returns {JSX.Element} The rendered component
|
||||
*/
|
||||
const Status = ({ monitor }) => {
|
||||
const theme = useTheme();
|
||||
const { statusColor, determineState } = useMonitorUtils();
|
||||
|
||||
return (
|
||||
<Stack>
|
||||
<Typography variant="monitorName">{monitor?.name}</Typography>
|
||||
<Stack
|
||||
direction="row"
|
||||
alignItems={"center"}
|
||||
gap={theme.spacing(4)}
|
||||
>
|
||||
<PulseDot color={statusColor[determineState(monitor)]} />
|
||||
<Typography variant="monitorUrl">{formatMonitorUrl(monitor?.url)}</Typography>
|
||||
<Dot />
|
||||
<Typography>
|
||||
Checking every {formatDurationRounded(monitor?.interval)}.
|
||||
</Typography>
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
Status.propTypes = {
|
||||
monitor: PropTypes.object,
|
||||
};
|
||||
|
||||
export default Status;
|
||||
@@ -1,127 +0,0 @@
|
||||
// Components
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import Divider from "@mui/material/Divider";
|
||||
import Icon from "../Icon";
|
||||
import Search from "../Inputs/Search/index.jsx";
|
||||
|
||||
// Utils
|
||||
import { useState, useEffect } from "react";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import PropTypes from "prop-types";
|
||||
|
||||
const NotificationConfig = ({
|
||||
notifications,
|
||||
setMonitor,
|
||||
setNotifications,
|
||||
//FieldWrapper's props
|
||||
gap,
|
||||
labelMb,
|
||||
labelFontWeight,
|
||||
labelVariant,
|
||||
labelSx = {},
|
||||
sx = {},
|
||||
}) => {
|
||||
// Local state
|
||||
const [notificationsSearch, setNotificationsSearch] = useState("");
|
||||
const [selectedNotifications, setSelectedNotifications] = useState([]);
|
||||
|
||||
const handleSearch = (value) => {
|
||||
setSelectedNotifications(value);
|
||||
setMonitor((prev) => {
|
||||
return {
|
||||
...prev,
|
||||
notifications: value.map((notification) => notification.id),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
// Handlers
|
||||
const handleDelete = (id) => {
|
||||
const updatedNotifications = selectedNotifications.filter(
|
||||
(notification) => notification.id !== id
|
||||
);
|
||||
|
||||
setSelectedNotifications(updatedNotifications);
|
||||
setMonitor((prev) => {
|
||||
return {
|
||||
...prev,
|
||||
notifications: updatedNotifications.map((notification) => notification.id),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
// Setup
|
||||
const theme = useTheme();
|
||||
|
||||
useEffect(() => {
|
||||
if (setNotifications) {
|
||||
const toSet = setNotifications.map((notification) => {
|
||||
return notifications.find((n) => n.id === notification);
|
||||
});
|
||||
setSelectedNotifications(toSet);
|
||||
}
|
||||
}, [setNotifications, notifications]);
|
||||
|
||||
return (
|
||||
<Stack gap={theme.spacing(6)}>
|
||||
<Search
|
||||
type="notifications"
|
||||
label="Notifications"
|
||||
options={notifications}
|
||||
filteredBy="notificationName"
|
||||
multiple={true}
|
||||
value={selectedNotifications}
|
||||
inputValue={notificationsSearch}
|
||||
handleInputChange={setNotificationsSearch}
|
||||
handleChange={(value) => {
|
||||
handleSearch(value);
|
||||
}}
|
||||
labelMb={labelMb}
|
||||
labelVariant={labelVariant}
|
||||
labelFontWeight={labelFontWeight}
|
||||
labelSx={labelSx}
|
||||
gap={gap}
|
||||
sx={{
|
||||
...sx,
|
||||
}}
|
||||
/>
|
||||
<Stack
|
||||
flex={1}
|
||||
width="100%"
|
||||
>
|
||||
{selectedNotifications.map((notification, index) => (
|
||||
<Stack
|
||||
direction="row"
|
||||
alignItems="center"
|
||||
key={notification.id}
|
||||
width="100%"
|
||||
>
|
||||
<Typography
|
||||
flexGrow={1} // <-- This will take up all available horizontal space
|
||||
>
|
||||
{notification.notificationName}
|
||||
</Typography>
|
||||
<Icon
|
||||
name="Trash2"
|
||||
size={20}
|
||||
onClick={() => {
|
||||
handleDelete(notification.id);
|
||||
}}
|
||||
style={{ cursor: "pointer" }}
|
||||
/>
|
||||
{index < selectedNotifications.length - 1 && <Divider />}
|
||||
</Stack>
|
||||
))}
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
NotificationConfig.propTypes = {
|
||||
notifications: PropTypes.array,
|
||||
setMonitor: PropTypes.func,
|
||||
setNotifications: PropTypes.array,
|
||||
};
|
||||
|
||||
export default NotificationConfig;
|
||||
-419
@@ -1,419 +0,0 @@
|
||||
import { useState, useMemo, useEffect, useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import PropTypes from "prop-types";
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogActions,
|
||||
Button,
|
||||
Typography,
|
||||
Box,
|
||||
Tabs,
|
||||
Tab,
|
||||
Stack,
|
||||
} from "@mui/material";
|
||||
import { useTheme } from "@emotion/react";
|
||||
import TabPanel from "./TabPanel.jsx";
|
||||
import TabComponent from "./TabComponent.jsx";
|
||||
import useNotifications from "../Hooks/useNotification.js";
|
||||
|
||||
// Define constants for notification types to avoid magic values
|
||||
const NOTIFICATION_TYPES = {
|
||||
SLACK: "slack",
|
||||
DISCORD: "discord",
|
||||
TELEGRAM: "telegram",
|
||||
WEBHOOK: "webhook",
|
||||
};
|
||||
|
||||
// Define constants for field IDs
|
||||
const FIELD_IDS = {
|
||||
WEBHOOK: "webhook",
|
||||
TOKEN: "token",
|
||||
CHAT_ID: "chatId",
|
||||
URL: "url",
|
||||
};
|
||||
|
||||
const NotificationIntegrationModal = ({
|
||||
open,
|
||||
onClose,
|
||||
monitor,
|
||||
setMonitor,
|
||||
// Optional prop to configure available notification types
|
||||
notificationTypes = null,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const theme = useTheme();
|
||||
const [tabValue, setTabValue] = useState(0);
|
||||
|
||||
const [loading, _, sendTestNotification] = useNotifications();
|
||||
|
||||
// Helper to get the field state key with error handling
|
||||
const getFieldKey = useCallback(
|
||||
(typeId, fieldId) => {
|
||||
if (typeof typeId !== "string" || typeId === "") {
|
||||
throw new Error(t("errorInvalidTypeId"));
|
||||
}
|
||||
|
||||
if (typeof fieldId !== "string" || fieldId === "") {
|
||||
throw new Error(t("errorInvalidFieldId"));
|
||||
}
|
||||
|
||||
return `${typeId}${fieldId.charAt(0).toUpperCase() + fieldId.slice(1)}`;
|
||||
},
|
||||
[t]
|
||||
);
|
||||
|
||||
// Define notification types
|
||||
const DEFAULT_NOTIFICATION_TYPES = [
|
||||
{
|
||||
id: NOTIFICATION_TYPES.SLACK,
|
||||
label: t("notifications.slack.label"),
|
||||
description: t("notifications.slack.description"),
|
||||
fields: [
|
||||
{
|
||||
id: FIELD_IDS.WEBHOOK,
|
||||
label: t("notifications.slack.webhookLabel"),
|
||||
placeholder: t("notifications.slack.webhookPlaceholder"),
|
||||
type: "text",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: NOTIFICATION_TYPES.DISCORD,
|
||||
label: t("notifications.discord.label"),
|
||||
description: t("notifications.discord.description"),
|
||||
fields: [
|
||||
{
|
||||
id: FIELD_IDS.WEBHOOK,
|
||||
label: t("notifications.discord.webhookLabel"),
|
||||
placeholder: t("notifications.discord.webhookPlaceholder"),
|
||||
type: "text",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: NOTIFICATION_TYPES.TELEGRAM,
|
||||
label: t("notifications.telegram.label"),
|
||||
description: t("notifications.telegram.description"),
|
||||
fields: [
|
||||
{
|
||||
id: FIELD_IDS.TOKEN,
|
||||
label: t("notifications.telegram.tokenLabel"),
|
||||
placeholder: t("notifications.telegram.tokenPlaceholder"),
|
||||
type: "text",
|
||||
},
|
||||
{
|
||||
id: FIELD_IDS.CHAT_ID,
|
||||
label: t("notifications.telegram.chatIdLabel"),
|
||||
placeholder: t("notifications.telegram.chatIdPlaceholder"),
|
||||
type: "text",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: NOTIFICATION_TYPES.WEBHOOK,
|
||||
label: t("notifications.webhook.label"),
|
||||
description: t("notifications.webhook.description"),
|
||||
fields: [
|
||||
{
|
||||
id: FIELD_IDS.URL,
|
||||
label: t("notifications.webhook.urlLabel"),
|
||||
placeholder: t("notifications.webhook.urlPlaceholder"),
|
||||
type: "text",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
// Use provided notification types or default to our translated ones
|
||||
const activeNotificationTypes = notificationTypes || DEFAULT_NOTIFICATION_TYPES;
|
||||
|
||||
// Memoized function to initialize integrations state
|
||||
const initialIntegrationsState = useMemo(() => {
|
||||
const state = {};
|
||||
|
||||
activeNotificationTypes.forEach((type) => {
|
||||
// Add enabled flag for each notification type
|
||||
state[type.id] = false;
|
||||
|
||||
// Add state for each field in the notification type
|
||||
type.fields.forEach((field) => {
|
||||
const fieldKey = getFieldKey(type.id, field.id);
|
||||
state[fieldKey] = "";
|
||||
});
|
||||
});
|
||||
|
||||
return state;
|
||||
}, [activeNotificationTypes, getFieldKey]); // Only recompute when these dependencies change
|
||||
|
||||
const [integrations, setIntegrations] = useState(initialIntegrationsState);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
const extractNotificationValues = () => {
|
||||
const values = {};
|
||||
|
||||
if (!monitor?.notifications || !Array.isArray(monitor.notifications)) {
|
||||
return values;
|
||||
}
|
||||
|
||||
monitor.notifications.forEach((notification) => {
|
||||
// Handle notification based on its structure
|
||||
if (notification.type === "webhook" && notification.platform) {
|
||||
if (typeof notification.config === "undefined") return;
|
||||
const platform = notification.platform;
|
||||
values[platform] = true; // Set platform as enabled
|
||||
|
||||
// Extract configuration based on platform
|
||||
switch (platform) {
|
||||
case NOTIFICATION_TYPES.SLACK:
|
||||
case NOTIFICATION_TYPES.DISCORD:
|
||||
if (notification.config.webhookUrl) {
|
||||
values[getFieldKey(platform, FIELD_IDS.WEBHOOK)] =
|
||||
notification.config.webhookUrl;
|
||||
}
|
||||
break;
|
||||
case NOTIFICATION_TYPES.TELEGRAM:
|
||||
if (notification.config.botToken) {
|
||||
values[getFieldKey(platform, FIELD_IDS.TOKEN)] =
|
||||
notification.config.botToken;
|
||||
}
|
||||
if (notification.config.chatId) {
|
||||
values[getFieldKey(platform, FIELD_IDS.CHAT_ID)] =
|
||||
notification.config.chatId;
|
||||
}
|
||||
break;
|
||||
case NOTIFICATION_TYPES.WEBHOOK:
|
||||
if (notification.config.webhookUrl) {
|
||||
values[getFieldKey(platform, FIELD_IDS.URL)] =
|
||||
notification.config.webhookUrl;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return values;
|
||||
};
|
||||
|
||||
const extractedValues = extractNotificationValues();
|
||||
setIntegrations((prev) => ({
|
||||
...prev,
|
||||
...extractedValues,
|
||||
}));
|
||||
}
|
||||
}, [open, monitor, getFieldKey]);
|
||||
|
||||
const handleChangeTab = (event, newValue) => {
|
||||
setTabValue(newValue);
|
||||
};
|
||||
|
||||
const handleIntegrationChange = (type, checked) => {
|
||||
setIntegrations((prev) => ({
|
||||
...prev,
|
||||
[type]: checked,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleInputChange = (type, value) => {
|
||||
setIntegrations((prev) => ({
|
||||
...prev,
|
||||
[type]: value,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleTestNotification = async (type) => {
|
||||
// Get the notification type details
|
||||
const notificationType = activeNotificationTypes.find((t) => t.id === type);
|
||||
|
||||
if (typeof notificationType === "undefined") {
|
||||
return;
|
||||
}
|
||||
|
||||
// Prepare config object based on notification type
|
||||
const config = {};
|
||||
|
||||
// Add each field value to the config object
|
||||
notificationType.fields.forEach((field) => {
|
||||
const fieldKey = getFieldKey(type, field.id);
|
||||
config[field.id] = integrations[fieldKey];
|
||||
});
|
||||
|
||||
await sendTestNotification(type, config);
|
||||
};
|
||||
|
||||
// In NotificationIntegrationModal.jsx, update the handleSave function:
|
||||
|
||||
const handleSave = () => {
|
||||
// Get existing notifications
|
||||
const notifications = [...(monitor?.notifications || [])];
|
||||
|
||||
// Get all notification types IDs
|
||||
const existingTypes = activeNotificationTypes.map((type) => type.id);
|
||||
|
||||
// Filter out notifications that are configurable in this modal
|
||||
const filteredNotifications = notifications.filter((notification) => {
|
||||
if (notification.platform) {
|
||||
return !existingTypes.includes(notification.platform);
|
||||
}
|
||||
|
||||
return !existingTypes.includes(notification.type);
|
||||
});
|
||||
|
||||
// Add each enabled notification with its configured fields
|
||||
activeNotificationTypes.forEach((type) => {
|
||||
if (integrations[type.id]) {
|
||||
let notificationObject = {
|
||||
type: "webhook",
|
||||
platform: type.id, // Set platform to identify the specific service
|
||||
config: {},
|
||||
};
|
||||
|
||||
// Configure based on notification type
|
||||
switch (type.id) {
|
||||
case "slack":
|
||||
case "discord":
|
||||
notificationObject.config.webhookUrl =
|
||||
integrations[getFieldKey(type.id, "webhook")];
|
||||
break;
|
||||
case "telegram":
|
||||
notificationObject.config.botToken =
|
||||
integrations[getFieldKey(type.id, "token")];
|
||||
notificationObject.config.chatId =
|
||||
integrations[getFieldKey(type.id, "chatId")];
|
||||
break;
|
||||
case "webhook":
|
||||
notificationObject.config.webhookUrl =
|
||||
integrations[getFieldKey(type.id, "url")];
|
||||
break;
|
||||
}
|
||||
|
||||
filteredNotifications.push(notificationObject);
|
||||
}
|
||||
});
|
||||
|
||||
// Update monitor with new notifications
|
||||
setMonitor((prev) => ({
|
||||
...prev,
|
||||
notifications: filteredNotifications,
|
||||
}));
|
||||
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
fullWidth
|
||||
maxWidth="md"
|
||||
sx={{
|
||||
"& .MuiDialog-paper": {
|
||||
width: `calc(80% - ${theme.spacing(40)})`,
|
||||
maxWidth: `${theme.breakpoints.values.md - 70}px`,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<Stack
|
||||
direction="row"
|
||||
sx={{
|
||||
height: `calc(30vh - ${theme.spacing(20)})`,
|
||||
}}
|
||||
>
|
||||
{/* Left sidebar with tabs */}
|
||||
<Box
|
||||
sx={{
|
||||
borderRight: 1,
|
||||
borderColor: theme.palette.primary.lowContrast,
|
||||
width: "30%",
|
||||
maxWidth: theme.spacing(120),
|
||||
pr: theme.spacing(10),
|
||||
}}
|
||||
>
|
||||
<Typography variant="h2">
|
||||
{t("notifications.addOrEditNotifications")}
|
||||
</Typography>
|
||||
|
||||
<Tabs
|
||||
orientation="vertical"
|
||||
variant="scrollable"
|
||||
value={tabValue}
|
||||
onChange={handleChangeTab}
|
||||
aria-label="Notification tabs"
|
||||
>
|
||||
{activeNotificationTypes.map((type) => (
|
||||
<Tab
|
||||
key={type.id}
|
||||
label={type.label}
|
||||
orientation="vertical"
|
||||
disableRipple
|
||||
/>
|
||||
))}
|
||||
</Tabs>
|
||||
</Box>
|
||||
|
||||
{/* Right side content */}
|
||||
<Box
|
||||
sx={{
|
||||
flex: 1,
|
||||
pl: theme.spacing(7.5),
|
||||
overflowY: "auto",
|
||||
}}
|
||||
>
|
||||
{activeNotificationTypes.map((type, index) => (
|
||||
<TabPanel
|
||||
key={type.id}
|
||||
value={tabValue}
|
||||
index={index}
|
||||
>
|
||||
<TabComponent
|
||||
type={type}
|
||||
integrations={integrations}
|
||||
handleIntegrationChange={handleIntegrationChange}
|
||||
handleInputChange={handleInputChange}
|
||||
handleTestNotification={handleTestNotification}
|
||||
isLoading={loading}
|
||||
/>
|
||||
</TabPanel>
|
||||
))}
|
||||
</Box>
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions
|
||||
sx={{
|
||||
p: theme.spacing(4),
|
||||
display: "flex",
|
||||
justifyContent: "flex-end",
|
||||
mb: theme.spacing(5),
|
||||
mr: theme.spacing(5),
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="accent"
|
||||
onClick={handleSave}
|
||||
loading={loading}
|
||||
sx={{
|
||||
width: "auto",
|
||||
minWidth: theme.spacing(60),
|
||||
px: theme.spacing(8),
|
||||
}}
|
||||
>
|
||||
{t("commonSave")}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
NotificationIntegrationModal.propTypes = {
|
||||
open: PropTypes.bool.isRequired,
|
||||
onClose: PropTypes.func.isRequired,
|
||||
monitor: PropTypes.object.isRequired,
|
||||
setMonitor: PropTypes.func.isRequired,
|
||||
notificationTypes: PropTypes.array,
|
||||
};
|
||||
|
||||
export default NotificationIntegrationModal;
|
||||
@@ -1,115 +0,0 @@
|
||||
import React from "react";
|
||||
import { Typography, Box, Button, CircularProgress } from "@mui/material";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useTheme } from "@emotion/react";
|
||||
import TextInput from "../../Inputs/TextInput/index.jsx";
|
||||
import Checkbox from "../../Inputs/Checkbox/index.jsx";
|
||||
|
||||
const TabComponent = ({
|
||||
type,
|
||||
integrations,
|
||||
handleIntegrationChange,
|
||||
handleInputChange,
|
||||
handleTestNotification,
|
||||
isLoading,
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
|
||||
// Helper to get the field state key (e.g., slackWebhook, telegramToken)
|
||||
const getFieldKey = (typeId, fieldId) => {
|
||||
return `${typeId}${fieldId.charAt(0).toUpperCase() + fieldId.slice(1)}`;
|
||||
};
|
||||
|
||||
// Check if all fields have values to enable test button
|
||||
const areAllFieldsFilled = () => {
|
||||
return type.fields.every((field) => {
|
||||
const fieldKey = getFieldKey(type.id, field.id);
|
||||
return integrations[fieldKey];
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Typography
|
||||
variant="subtitle1"
|
||||
component="h4"
|
||||
sx={{
|
||||
fontWeight: "bold",
|
||||
color: theme.palette.primary.contrastTextSecondary,
|
||||
}}
|
||||
>
|
||||
{type.label}
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
sx={{
|
||||
mt: theme.spacing(0.5),
|
||||
mb: theme.spacing(1.5),
|
||||
color: theme.palette.primary.contrastTextTertiary,
|
||||
}}
|
||||
>
|
||||
{type.description}
|
||||
</Typography>
|
||||
|
||||
<Box sx={{ pl: theme.spacing(1.5) }}>
|
||||
<Checkbox
|
||||
id={`enable-${type.id}`}
|
||||
label={t("notifications.enableNotifications", { platform: type.label })}
|
||||
isChecked={integrations[type.id]}
|
||||
onChange={(e) => handleIntegrationChange(type.id, e.target.checked)}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
{type.fields.map((field) => {
|
||||
const fieldKey = getFieldKey(type.id, field.id);
|
||||
|
||||
return (
|
||||
<Box
|
||||
key={field.id}
|
||||
sx={{ mt: theme.spacing(1) }}
|
||||
>
|
||||
<Typography
|
||||
sx={{
|
||||
mb: theme.spacing(2),
|
||||
fontWeight: "bold",
|
||||
color: theme.palette.primary.contrastTextSecondary,
|
||||
}}
|
||||
>
|
||||
{field.label}
|
||||
</Typography>
|
||||
|
||||
<TextInput
|
||||
id={`${type.id}-${field.id}`}
|
||||
type={field.type}
|
||||
placeholder={field.placeholder}
|
||||
value={integrations[fieldKey]}
|
||||
onChange={(e) => handleInputChange(fieldKey, e.target.value)}
|
||||
disabled={!integrations[type.id] || isLoading}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
|
||||
<Box sx={{ mt: theme.spacing(1) }}>
|
||||
<Button
|
||||
variant="text"
|
||||
color="info"
|
||||
onClick={() => handleTestNotification(type.id)}
|
||||
disabled={!integrations[type.id] || !areAllFieldsFilled() || isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<CircularProgress
|
||||
size={theme.spacing(8)}
|
||||
sx={{ mr: theme.spacing(1), color: theme.palette.accent.main }}
|
||||
/>
|
||||
) : null}
|
||||
{t("notifications.testNotification")}
|
||||
</Button>
|
||||
</Box>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default TabComponent;
|
||||
@@ -1,41 +0,0 @@
|
||||
import React from "react";
|
||||
import PropTypes from "prop-types";
|
||||
import { Box } from "@mui/material";
|
||||
import { useTheme } from "@emotion/react";
|
||||
|
||||
/**
|
||||
* TabPanel component that displays content for the selected tab.
|
||||
*
|
||||
* @component
|
||||
* @param {Object} props - The component props.
|
||||
* @param {React.ReactNode} props.children - The content to be displayed when this tab panel is selected.
|
||||
* @param {number} props.value - The currently selected tab value.
|
||||
* @param {number} props.index - The index of this specific tab panel.
|
||||
* @param {Object} props.other - Any additional props to be spread to the root element.
|
||||
* @returns {React.ReactElement|null} The rendered tab panel or null if not selected.
|
||||
*/
|
||||
function TabPanel({ children, value, index, ...other }) {
|
||||
const theme = useTheme();
|
||||
|
||||
return (
|
||||
<div
|
||||
role="tabpanel"
|
||||
hidden={value !== index}
|
||||
id={`notification-tabpanel-${index}`}
|
||||
aria-labelledby={`notification-tab-${index}`}
|
||||
{...other}
|
||||
>
|
||||
{value === index && <Box sx={{ pt: theme.spacing(3) }}>{children}</Box>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
TabPanel.propTypes = {
|
||||
children: PropTypes.node,
|
||||
|
||||
index: PropTypes.number.isRequired,
|
||||
|
||||
value: PropTypes.number.isRequired,
|
||||
};
|
||||
|
||||
export default TabPanel;
|
||||
@@ -1,129 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { networkService } from "../../../../Utils/NetworkService.js";
|
||||
import { createToast } from "../../../../Utils/toastUtils.jsx";
|
||||
|
||||
// Define constants for notification types to avoid magic values
|
||||
const NOTIFICATION_TYPES = {
|
||||
SLACK: "slack",
|
||||
DISCORD: "discord",
|
||||
TELEGRAM: "telegram",
|
||||
WEBHOOK: "webhook",
|
||||
};
|
||||
|
||||
// Define constants for field IDs
|
||||
const FIELD_IDS = {
|
||||
WEBHOOK: "webhook",
|
||||
TOKEN: "token",
|
||||
CHAT_ID: "chatId",
|
||||
URL: "url",
|
||||
};
|
||||
|
||||
/**
|
||||
* Custom hook for notification-related operations
|
||||
*/
|
||||
const useNotifications = () => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState(undefined);
|
||||
const { t } = useTranslation();
|
||||
|
||||
/**
|
||||
* Send a test notification
|
||||
* @param {string} type - The notification type (slack, discord, telegram, webhook)
|
||||
* @param {object} config - Configuration object with necessary params
|
||||
*/
|
||||
const sendTestNotification = async (type, config) => {
|
||||
setLoading(true);
|
||||
setError(undefined);
|
||||
|
||||
// Validation based on notification type
|
||||
let payload = { platform: type };
|
||||
let isValid = true;
|
||||
let errorMessage = "";
|
||||
|
||||
switch (type) {
|
||||
case NOTIFICATION_TYPES.SLACK:
|
||||
payload.webhookUrl = config.webhook;
|
||||
if (typeof payload.webhookUrl === "undefined" || payload.webhookUrl === "") {
|
||||
isValid = false;
|
||||
errorMessage = t("notifications.slack.webhookRequired");
|
||||
}
|
||||
break;
|
||||
|
||||
case NOTIFICATION_TYPES.DISCORD:
|
||||
payload.webhookUrl = config.webhook;
|
||||
if (typeof payload.webhookUrl === "undefined" || payload.webhookUrl === "") {
|
||||
isValid = false;
|
||||
errorMessage = t("notifications.discord.webhookRequired");
|
||||
}
|
||||
break;
|
||||
|
||||
case NOTIFICATION_TYPES.TELEGRAM:
|
||||
payload.botToken = config.token;
|
||||
payload.chatId = config.chatId;
|
||||
if (
|
||||
typeof payload.botToken === "undefined" ||
|
||||
payload.botToken === "" ||
|
||||
typeof payload.chatId === "undefined" ||
|
||||
payload.chatId === ""
|
||||
) {
|
||||
isValid = false;
|
||||
errorMessage = t("notifications.telegram.fieldsRequired");
|
||||
}
|
||||
break;
|
||||
|
||||
case NOTIFICATION_TYPES.WEBHOOK:
|
||||
payload.webhookUrl = config.url;
|
||||
payload.platform = NOTIFICATION_TYPES.SLACK;
|
||||
if (typeof payload.webhookUrl === "undefined" || payload.webhookUrl === "") {
|
||||
isValid = false;
|
||||
errorMessage = t("notifications.webhook.urlRequired");
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
isValid = false;
|
||||
errorMessage = t("notifications.unsupportedType");
|
||||
}
|
||||
|
||||
// If validation fails, show error and return
|
||||
if (isValid === false) {
|
||||
createToast({
|
||||
body: errorMessage,
|
||||
variant: "error",
|
||||
});
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await networkService.testNotification({
|
||||
platform: type,
|
||||
payload: payload,
|
||||
});
|
||||
|
||||
if (response.data.success === true) {
|
||||
createToast({
|
||||
body: t("notifications.testSuccess"),
|
||||
variant: "info",
|
||||
});
|
||||
} else {
|
||||
throw new Error(response.data.msg || t("notifications.testFailed"));
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMsg =
|
||||
error.response?.data?.msg || error.message || t("notifications.networkError");
|
||||
createToast({
|
||||
body: `${t("notifications.testFailed")}: ${errorMsg}`,
|
||||
variant: "error",
|
||||
});
|
||||
setError(errorMsg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return [loading, error, sendTestNotification];
|
||||
};
|
||||
|
||||
export default useNotifications;
|
||||
@@ -5,7 +5,7 @@ import PropTypes from "prop-types";
|
||||
import { useTheme } from "@emotion/react";
|
||||
import { Link as RouterLink } from "react-router-dom";
|
||||
|
||||
const TextLink = ({ text, linkText, href, target = "_self" }) => {
|
||||
const TextLink = ({ text, linkText, href, state, target = "_self" }) => {
|
||||
const theme = useTheme();
|
||||
|
||||
return (
|
||||
@@ -19,6 +19,7 @@ const TextLink = ({ text, linkText, href, target = "_self" }) => {
|
||||
to={href}
|
||||
component={RouterLink}
|
||||
target={target}
|
||||
state={state}
|
||||
>
|
||||
{linkText}
|
||||
</Link>
|
||||
@@ -30,6 +31,7 @@ TextLink.propTypes = {
|
||||
text: PropTypes.string,
|
||||
linkText: PropTypes.string,
|
||||
href: PropTypes.string,
|
||||
state: PropTypes.object,
|
||||
target: PropTypes.string,
|
||||
};
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useTheme } from "@mui/material/styles";
|
||||
import { useSelector } from "react-redux";
|
||||
import type { RootState } from "@/Types/state";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
type HeatmapCheck =
|
||||
| CheckSnapshot
|
||||
| { status: "placeholder"; responseTime: 0; createdAt: "" };
|
||||
@@ -55,12 +56,9 @@ export const HeatmapResponseTimeTooltip = ({
|
||||
<Typography>
|
||||
{formatDateWithTz(check?.createdAt, "ddd, MMMM D, YYYY, HH:mm A", uiTimezone)}
|
||||
</Typography>
|
||||
{check?.responseTime && (
|
||||
<Typography>
|
||||
{t("common.labels.responseTime")}: {check.responseTime.toFixed()} ms
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<Typography>
|
||||
{t("common.labels.responseTime")}: {check.originalResponseTime.toFixed()} ms
|
||||
</Typography>
|
||||
<Typography textTransform={"capitalize"}>
|
||||
Status:{" "}
|
||||
<span style={{ color: getColor(check?.status) }}>
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import { ToggleButtonGroup, ToggleButton } from "@/Components/v2/inputs";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import CircularProgress from "@mui/material/CircularProgress";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useMediaQuery } from "@mui/material";
|
||||
|
||||
interface MonitorTimeFrameHeaderProps {
|
||||
isLoading?: boolean;
|
||||
@@ -17,7 +21,8 @@ export const HeaderTimeRange = ({
|
||||
setDateRange,
|
||||
}: MonitorTimeFrameHeaderProps) => {
|
||||
const theme = useTheme();
|
||||
|
||||
const { t } = useTranslation();
|
||||
const isSmallScreen = useMediaQuery(theme.breakpoints.down("md"));
|
||||
const handleChange = (
|
||||
_event: React.MouseEvent<HTMLElement>,
|
||||
newValue: string | null
|
||||
@@ -32,34 +37,24 @@ export const HeaderTimeRange = ({
|
||||
if (hasDateRange) {
|
||||
timeFramePicker = (
|
||||
<ToggleButtonGroup
|
||||
orientation={isSmallScreen ? "vertical" : "horizontal"}
|
||||
value={dateRange}
|
||||
exclusive
|
||||
onChange={handleChange}
|
||||
size="small"
|
||||
fullWidth={isSmallScreen}
|
||||
>
|
||||
<ToggleButton
|
||||
disabled={isLoading}
|
||||
value="recent"
|
||||
>
|
||||
Recent
|
||||
<ToggleButton value="recent">
|
||||
{t("components.headerTimeRange.labels.recent")}
|
||||
</ToggleButton>
|
||||
<ToggleButton
|
||||
disabled={isLoading}
|
||||
value="day"
|
||||
>
|
||||
Day
|
||||
<ToggleButton value="day">
|
||||
{t("components.headerTimeRange.labels.day")}
|
||||
</ToggleButton>
|
||||
<ToggleButton
|
||||
disabled={isLoading}
|
||||
value="week"
|
||||
>
|
||||
Week
|
||||
<ToggleButton value="week">
|
||||
{t("components.headerTimeRange.labels.week")}
|
||||
</ToggleButton>
|
||||
<ToggleButton
|
||||
disabled={isLoading}
|
||||
value="month"
|
||||
>
|
||||
Month
|
||||
<ToggleButton value="month">
|
||||
{t("components.headerTimeRange.labels.month")}
|
||||
</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
);
|
||||
@@ -67,21 +62,19 @@ export const HeaderTimeRange = ({
|
||||
|
||||
return (
|
||||
<Stack
|
||||
direction="row"
|
||||
direction={{ xs: "column", md: "row" }}
|
||||
justifyContent="flex-end"
|
||||
alignItems="center"
|
||||
gap={theme.spacing(4)}
|
||||
>
|
||||
<Box
|
||||
width={16}
|
||||
height={16}
|
||||
>
|
||||
{isLoading && <CircularProgress size={16} />}
|
||||
</Box>
|
||||
<Typography variant="body2">
|
||||
Showing statistics for past{" "}
|
||||
{dateRange === "recent"
|
||||
? "2 hours"
|
||||
: dateRange === "day"
|
||||
? "24 hours"
|
||||
: dateRange === "week"
|
||||
? "7 days"
|
||||
: "30 days"}
|
||||
.
|
||||
{t(`components.headerTimeRange.description.${dateRange}`)}
|
||||
</Typography>
|
||||
{timeFramePicker}
|
||||
</Stack>
|
||||
|
||||
@@ -2,5 +2,4 @@ export * from "../common/charts/HistogramResponseTime";
|
||||
export * from "../common/charts/HeatmapResponseTime";
|
||||
export * from "../common/charts/HeatmapResponseTimeTooltip";
|
||||
export * from "../common/controls/HeaderCreate";
|
||||
export * from "../common/controls/HeaderMonitorControls";
|
||||
export * from "../common/controls/HeaderTimeRange";
|
||||
@@ -1,4 +1,6 @@
|
||||
import Logo from "@/assets/icons/checkmate-icon.svg?react";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Box from "@mui/material/Box";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import Link from "@mui/material/Link";
|
||||
import {
|
||||
@@ -9,6 +11,7 @@ import {
|
||||
} from "@/Components/v2/design-elements/Fallback";
|
||||
import { Breadcrumb } from "@/Components/v2/design-elements/Breadcrumb";
|
||||
import CircularProgress from "@mui/material/CircularProgress";
|
||||
import { HeaderAuthControls } from "@/Pages/Auth/components/HeaderAuthControls";
|
||||
|
||||
import type { StackProps } from "@mui/material/Stack";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
@@ -91,7 +94,7 @@ export const BasePage = ({
|
||||
spacing={theme.spacing(10)}
|
||||
{...props}
|
||||
>
|
||||
<Breadcrumb />
|
||||
<Breadcrumb breadcrumbOverride={breadcrumbOverride} />
|
||||
{children}
|
||||
</Stack>
|
||||
);
|
||||
@@ -100,7 +103,7 @@ export const BasePage = ({
|
||||
interface BasePageWithStatesProps extends StackProps {
|
||||
loading: boolean;
|
||||
error: any;
|
||||
items: any[];
|
||||
totalCount: number;
|
||||
bullets: string[] | unknown;
|
||||
page: string;
|
||||
actionButtonText: string;
|
||||
@@ -111,7 +114,7 @@ interface BasePageWithStatesProps extends StackProps {
|
||||
export const BasePageWithStates = ({
|
||||
loading,
|
||||
error,
|
||||
items,
|
||||
totalCount,
|
||||
page,
|
||||
bullets,
|
||||
actionButtonText,
|
||||
@@ -119,9 +122,9 @@ export const BasePageWithStates = ({
|
||||
children,
|
||||
...props
|
||||
}: BasePageWithStatesProps) => {
|
||||
const showLoading = loading && (!items || items.length === 0);
|
||||
const showLoading = loading && totalCount === 0;
|
||||
|
||||
if (isEmpty(items)) {
|
||||
if (!loading && totalCount === 0) {
|
||||
return (
|
||||
<EmptyFallback
|
||||
bullets={bullets}
|
||||
@@ -146,23 +149,17 @@ export const BasePageWithStates = ({
|
||||
interface MonitorBasePageWithStatesProps extends StackProps {
|
||||
loading: boolean;
|
||||
error: any;
|
||||
items: any[];
|
||||
totalCount: number;
|
||||
page: string;
|
||||
actionLink?: string;
|
||||
children: React.ReactNode;
|
||||
priorityFallback?: React.ReactNode;
|
||||
}
|
||||
|
||||
const isEmpty = (items: any[]) => {
|
||||
if (!items) return true;
|
||||
if (Array.isArray(items) && items.length === 0) return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
export const MonitorBasePageWithStates = ({
|
||||
loading,
|
||||
error,
|
||||
items,
|
||||
totalCount,
|
||||
page,
|
||||
actionLink,
|
||||
children,
|
||||
@@ -171,7 +168,7 @@ export const MonitorBasePageWithStates = ({
|
||||
}: MonitorBasePageWithStatesProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const showLoading = loading && (!items || items.length === 0);
|
||||
const showLoading = loading && totalCount === 0;
|
||||
|
||||
if (priorityFallback) {
|
||||
return (
|
||||
@@ -185,7 +182,7 @@ export const MonitorBasePageWithStates = ({
|
||||
);
|
||||
}
|
||||
|
||||
if (!loading && isEmpty(items)) {
|
||||
if (!loading && totalCount === 0) {
|
||||
return (
|
||||
<EmptyMonitorFallback
|
||||
page={page}
|
||||
@@ -207,3 +204,61 @@ export const MonitorBasePageWithStates = ({
|
||||
</BasePage>
|
||||
);
|
||||
};
|
||||
|
||||
interface BaseAuthPageProps extends React.PropsWithChildren, StackProps {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
}
|
||||
|
||||
export const BaseAuthPage = ({
|
||||
title,
|
||||
subtitle,
|
||||
children,
|
||||
...props
|
||||
}: BaseAuthPageProps) => {
|
||||
const theme = useTheme();
|
||||
return (
|
||||
<BasePage
|
||||
breadcrumbOverride={[]}
|
||||
gap={theme.spacing(8)}
|
||||
alignItems={"center"}
|
||||
justifyContent={"center"}
|
||||
minHeight="100vh"
|
||||
position={"relative"}
|
||||
{...props}
|
||||
>
|
||||
<HeaderAuthControls
|
||||
hideLogo
|
||||
py={theme.spacing(4)}
|
||||
position={"absolute"}
|
||||
top={0}
|
||||
left={0}
|
||||
/>
|
||||
<Box width={{ xs: 60, sm: 70, md: 80 }}>
|
||||
<Logo
|
||||
width={"100%"}
|
||||
height={"100%"}
|
||||
/>
|
||||
</Box>
|
||||
<Stack alignItems={"center"}>
|
||||
<Typography
|
||||
variant="h1"
|
||||
mb={theme.spacing(2)}
|
||||
>
|
||||
{title}
|
||||
</Typography>
|
||||
<Typography variant="h2">{subtitle}</Typography>
|
||||
</Stack>
|
||||
<Stack
|
||||
gap={theme.spacing(8)}
|
||||
width={{
|
||||
xs: "80%",
|
||||
md: "25%",
|
||||
lg: "15%",
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Stack>
|
||||
</BasePage>
|
||||
);
|
||||
};
|
||||
@@ -3,21 +3,17 @@ import Typography from "@mui/material/Typography";
|
||||
import { Link, useLocation } from "react-router-dom";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import { ChevronRight } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
const isId = (segment: string): boolean => {
|
||||
return segment.length === 24 || /^[a-f0-9-]{36}$/.test(segment);
|
||||
};
|
||||
|
||||
export const Breadcrumb = () => {
|
||||
const actionSegments = ["create", "configure"];
|
||||
|
||||
const BreadcrumbWrapper = ({ children }: { children: ReactNode }) => {
|
||||
const theme = useTheme();
|
||||
const location = useLocation();
|
||||
|
||||
const segments = location.pathname.split("/").filter((x) => x);
|
||||
|
||||
// Build simplified breadcrumb: "uptime" or "uptime / details"
|
||||
const basePage = segments[0] || "home";
|
||||
const hasDetailsPage = segments.length > 1 && isId(segments[1]);
|
||||
|
||||
return (
|
||||
<MuiBreadcrumbs
|
||||
separator={
|
||||
@@ -34,7 +30,73 @@ export const Breadcrumb = () => {
|
||||
},
|
||||
}}
|
||||
>
|
||||
{hasDetailsPage ? (
|
||||
{children}
|
||||
</MuiBreadcrumbs>
|
||||
);
|
||||
};
|
||||
|
||||
export const Breadcrumb = ({
|
||||
breadcrumbOverride,
|
||||
}: {
|
||||
breadcrumbOverride?: string[] | undefined;
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const theme = useTheme();
|
||||
const location = useLocation();
|
||||
|
||||
// If override is an empty array, hide entirely
|
||||
if (breadcrumbOverride !== undefined && breadcrumbOverride.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// If override has items, render them directly
|
||||
if (breadcrumbOverride !== undefined && breadcrumbOverride.length > 0) {
|
||||
return (
|
||||
<BreadcrumbWrapper>
|
||||
{breadcrumbOverride.map((item, index) => {
|
||||
const isLast = index === breadcrumbOverride.length - 1;
|
||||
return (
|
||||
<Typography
|
||||
key={index}
|
||||
sx={{
|
||||
fontSize: "14px",
|
||||
fontWeight: isLast ? 600 : 400,
|
||||
color: isLast ? theme.palette.primary.main : theme.palette.text.secondary,
|
||||
}}
|
||||
>
|
||||
{item}
|
||||
</Typography>
|
||||
);
|
||||
})}
|
||||
</BreadcrumbWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
// Default behavior: use location pathname
|
||||
const segments = location.pathname.split("/").filter((x) => x);
|
||||
|
||||
if (segments.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Build simplified breadcrumb: "uptime" or "uptime / details" or "uptime / create"
|
||||
const basePage = segments[0] || t("common.breadcrumbs.home");
|
||||
|
||||
const secondSegment = segments[1];
|
||||
const isActionPage = secondSegment && actionSegments.includes(secondSegment);
|
||||
const isDetailsPage = secondSegment && isId(secondSegment);
|
||||
const hasSubPage = isActionPage || isDetailsPage;
|
||||
|
||||
const getSubPageLabel = (): string => {
|
||||
if (isActionPage) {
|
||||
return secondSegment.charAt(0).toUpperCase() + secondSegment.slice(1);
|
||||
}
|
||||
return t("common.breadcrumbs.details");
|
||||
};
|
||||
|
||||
return (
|
||||
<BreadcrumbWrapper>
|
||||
{hasSubPage ? (
|
||||
<Link
|
||||
to={`/${basePage}`}
|
||||
style={{ textDecoration: "none" }}
|
||||
@@ -62,7 +124,7 @@ export const Breadcrumb = () => {
|
||||
{basePage.charAt(0).toUpperCase() + basePage.slice(1)}
|
||||
</Typography>
|
||||
)}
|
||||
{hasDetailsPage && (
|
||||
{hasSubPage && (
|
||||
<Typography
|
||||
sx={{
|
||||
fontSize: "14px",
|
||||
@@ -70,9 +132,9 @@ export const Breadcrumb = () => {
|
||||
color: theme.palette.primary.main,
|
||||
}}
|
||||
>
|
||||
Details
|
||||
{getSubPageLabel()}
|
||||
</Typography>
|
||||
)}
|
||||
</MuiBreadcrumbs>
|
||||
</BreadcrumbWrapper>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,155 @@
|
||||
import { BaseChart } from "@/Components/v2/design-elements";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import { useMemo, useState, useEffect } from "react";
|
||||
import { getInfraGaugeColor } from "@/Utils/MonitorUtils";
|
||||
|
||||
const MINIMUM_VALUE = 0;
|
||||
const MAXIMUM_VALUE = 100;
|
||||
|
||||
export const Gauge = ({
|
||||
isLoading = false,
|
||||
progress = 0,
|
||||
radius = 70,
|
||||
strokeWidth = 15,
|
||||
precision = 1,
|
||||
unit = "%",
|
||||
}: {
|
||||
isLoading?: boolean;
|
||||
progress?: number;
|
||||
radius?: number;
|
||||
strokeWidth?: number;
|
||||
precision?: number;
|
||||
unit?: string;
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
const progressWithinRange = Math.max(MINIMUM_VALUE, Math.min(progress, MAXIMUM_VALUE));
|
||||
|
||||
// Calculate the length of the stroke for the circle
|
||||
const { circumference, totalSize, strokeLength } = useMemo(
|
||||
() => ({
|
||||
circumference: 2 * Math.PI * radius,
|
||||
totalSize: radius * 2 + strokeWidth * 2,
|
||||
strokeLength: (progress / 100) * (2 * Math.PI * radius),
|
||||
}),
|
||||
[radius, strokeWidth, progress]
|
||||
);
|
||||
|
||||
const [offset, setOffset] = useState(circumference);
|
||||
useEffect(() => {
|
||||
setOffset(circumference);
|
||||
const timer = setTimeout(() => {
|
||||
setOffset(circumference - strokeLength);
|
||||
}, 100);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [progress, circumference, strokeLength]);
|
||||
|
||||
const fillColor = getInfraGaugeColor(progressWithinRange, theme);
|
||||
|
||||
if (isLoading) {
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box
|
||||
display={"inline-block"}
|
||||
position={"relative"}
|
||||
width={radius}
|
||||
height={radius}
|
||||
bgcolor={theme.palette.background.paper}
|
||||
borderRadius={"50%"}
|
||||
>
|
||||
<svg
|
||||
viewBox={`0 0 ${totalSize} ${totalSize}`}
|
||||
width={radius}
|
||||
height={radius}
|
||||
>
|
||||
<circle
|
||||
stroke={theme.palette.secondary.main}
|
||||
strokeWidth={strokeWidth}
|
||||
fill="none"
|
||||
cx={totalSize / 2}
|
||||
cy={totalSize / 2}
|
||||
r={radius}
|
||||
/>
|
||||
<circle
|
||||
stroke={fillColor}
|
||||
strokeWidth={strokeWidth}
|
||||
strokeDasharray={`${circumference} ${circumference}`}
|
||||
strokeDashoffset={offset}
|
||||
fill="none"
|
||||
cx={totalSize / 2}
|
||||
cy={totalSize / 2}
|
||||
r={radius}
|
||||
style={{
|
||||
transform: "rotate(-90deg)",
|
||||
transformOrigin: "center",
|
||||
transition: "stroke-dashoffset 1.5s ease-in-out",
|
||||
}}
|
||||
/>
|
||||
</svg>
|
||||
|
||||
<Typography
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: "50%",
|
||||
left: "50%",
|
||||
transform: "translate(-50%, -50%)",
|
||||
}}
|
||||
>
|
||||
{`${progressWithinRange.toFixed(precision)}${unit}`}
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export const DetailGauge = ({
|
||||
title,
|
||||
progress,
|
||||
upperLabel,
|
||||
upperValue,
|
||||
lowerLabel,
|
||||
lowerValue,
|
||||
}: {
|
||||
title: string;
|
||||
progress: number;
|
||||
upperLabel?: string;
|
||||
upperValue?: string | number;
|
||||
lowerLabel?: string;
|
||||
lowerValue?: string | number;
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
return (
|
||||
<BaseChart
|
||||
icon={null}
|
||||
title={title}
|
||||
maxWidth={225}
|
||||
>
|
||||
<Stack
|
||||
alignItems={"center"}
|
||||
mb={theme.spacing(4)}
|
||||
gap={theme.spacing(4)}
|
||||
>
|
||||
<Gauge progress={progress} />
|
||||
</Stack>
|
||||
<Stack
|
||||
direction={"row"}
|
||||
justifyContent={"space-between"}
|
||||
>
|
||||
<Typography>{upperLabel}</Typography>
|
||||
<Typography>{upperValue}</Typography>
|
||||
</Stack>
|
||||
<Stack
|
||||
direction={"row"}
|
||||
justifyContent={"space-between"}
|
||||
>
|
||||
<Typography>{lowerLabel}</Typography>
|
||||
<Typography>{lowerValue}</Typography>
|
||||
</Stack>
|
||||
</BaseChart>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,78 @@
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import useMediaQuery from "@mui/material/useMediaQuery";
|
||||
export const SplitBox = ({
|
||||
left,
|
||||
right,
|
||||
}: {
|
||||
left: React.ReactNode;
|
||||
right: React.ReactNode;
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
|
||||
return (
|
||||
<Stack
|
||||
direction={isSmall ? "column" : "row"}
|
||||
bgcolor={theme.palette.background.paper}
|
||||
border={1}
|
||||
borderColor={theme.palette.divider}
|
||||
borderRadius={theme.spacing(2)}
|
||||
>
|
||||
<Box
|
||||
padding={theme.spacing(15)}
|
||||
borderRight={isSmall ? 0 : 1}
|
||||
borderBottom={isSmall ? 1 : 0}
|
||||
borderColor={theme.palette.divider}
|
||||
flex={0.7}
|
||||
sx={{
|
||||
background:
|
||||
theme.palette.mode === "dark"
|
||||
? "linear-gradient(135deg, rgba(255, 255, 255, 0.01) 0%, rgba(255, 255, 255, 0.02) 100%)"
|
||||
: "linear-gradient(135deg, rgba(0, 0, 0, 0.01) 0%, rgba(0, 0, 0, 0.02) 100%)",
|
||||
}}
|
||||
>
|
||||
{left}
|
||||
</Box>
|
||||
<Box
|
||||
flex={1}
|
||||
padding={theme.spacing(15)}
|
||||
>
|
||||
{right}
|
||||
</Box>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export const ConfigBox = ({
|
||||
title,
|
||||
subtitle,
|
||||
leftContent,
|
||||
rightContent,
|
||||
}: {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
leftContent?: React.ReactNode;
|
||||
rightContent: React.ReactNode;
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
return (
|
||||
<SplitBox
|
||||
left={
|
||||
<Stack spacing={theme.spacing(4)}>
|
||||
<Typography
|
||||
textTransform={"capitalize"}
|
||||
component="h2"
|
||||
variant="h2"
|
||||
>
|
||||
{title}
|
||||
</Typography>
|
||||
<Typography component="p">{subtitle}</Typography>
|
||||
{leftContent}
|
||||
</Stack>
|
||||
}
|
||||
right={rightContent}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -4,12 +4,16 @@ import Box from "@mui/material/Box";
|
||||
import { BaseBox } from "@/Components/v2/design-elements";
|
||||
import Background from "@/assets/Images/background-grid.svg?react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { SxProps } from "@mui/material";
|
||||
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
|
||||
type StatusBoxProps = React.PropsWithChildren<{ children: React.ReactNode }>;
|
||||
type StatusBoxProps = React.PropsWithChildren<{
|
||||
children: React.ReactNode;
|
||||
sx?: SxProps;
|
||||
}>;
|
||||
|
||||
export const BGBox = ({ children }: StatusBoxProps) => {
|
||||
export const BGBox = ({ children, sx }: StatusBoxProps) => {
|
||||
const theme = useTheme();
|
||||
return (
|
||||
<BaseBox
|
||||
@@ -18,6 +22,7 @@ export const BGBox = ({ children }: StatusBoxProps) => {
|
||||
position: "relative",
|
||||
flex: 1,
|
||||
padding: theme.spacing(4),
|
||||
...sx,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
@@ -36,14 +41,16 @@ const StatusBox = ({
|
||||
label,
|
||||
n,
|
||||
color,
|
||||
sx,
|
||||
}: {
|
||||
label: string;
|
||||
n: number;
|
||||
color: string | undefined;
|
||||
sx?: SxProps;
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
return (
|
||||
<BGBox>
|
||||
<BGBox sx={sx}>
|
||||
<Stack spacing={theme.spacing(4)}>
|
||||
<Typography
|
||||
variant={"h2"}
|
||||
@@ -98,6 +105,39 @@ export const PausedStatusBox = ({ n }: { n: number }) => {
|
||||
/>
|
||||
);
|
||||
};
|
||||
export const TotalChecksBox = ({ n }: { n: number }) => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<StatusBox
|
||||
label={t("pages.common.monitors.status.total")}
|
||||
n={n}
|
||||
color={theme.palette.primary.light}
|
||||
/>
|
||||
);
|
||||
};
|
||||
export const DownChecksBox = ({ n }: { n: number }) => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<StatusBox
|
||||
label={t("pages.common.monitors.status.down")}
|
||||
n={n}
|
||||
color={theme.palette.error.light}
|
||||
/>
|
||||
);
|
||||
};
|
||||
export const UpChecksBox = ({ n }: { n: number }) => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<StatusBox
|
||||
label={t("pages.common.monitors.status.up")}
|
||||
n={n}
|
||||
color={theme.palette.success.light}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export const InitializingStatusBox = ({ n }: { n: number }) => {
|
||||
const theme = useTheme();
|
||||
|
||||
@@ -98,7 +98,7 @@ export const ValueLabel = ({ value, text }: { value: ValueType; text: string })
|
||||
borderRadius="50%"
|
||||
marginRight="5px"
|
||||
/>
|
||||
{transformedText}
|
||||
<Typography>{transformedText}</Typography>
|
||||
</BaseBox>
|
||||
);
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Grid2 from "@mui/material/Grid2";
|
||||
import Grid2 from "@mui/material/Grid";
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import Paper from "@mui/material/Paper";
|
||||
@@ -27,8 +27,9 @@ import TablePagination from "@mui/material/TablePagination";
|
||||
import type { TablePaginationOwnProps } from "@mui/material/TablePagination";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useState, Fragment } from "react";
|
||||
import { useState, Fragment, useEffect } from "react";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import type { SxProps, Theme } from "@mui/material/styles";
|
||||
import useMediaQuery from "@mui/material/useMediaQuery";
|
||||
|
||||
export type Header<T> = {
|
||||
@@ -47,6 +48,7 @@ type DataTableProps<T extends { id?: string | number; _id?: string | number }> =
|
||||
renderExpandedContent?: (row: T) => React.ReactNode;
|
||||
emptyViewText?: string;
|
||||
emptyViewPositive?: boolean;
|
||||
getRowSx?: (row: T) => SxProps<Theme>;
|
||||
};
|
||||
|
||||
export function DataTable<
|
||||
@@ -64,6 +66,7 @@ export function DataTable<
|
||||
renderExpandedContent,
|
||||
emptyViewText,
|
||||
emptyViewPositive,
|
||||
getRowSx,
|
||||
}: DataTableProps<T>) {
|
||||
const theme = useTheme();
|
||||
const [expanded, setExpanded] = useState<(string | number) | null>(null);
|
||||
@@ -204,6 +207,7 @@ export function DataTable<
|
||||
<TableRow
|
||||
sx={{
|
||||
cursor: onRowClick ? "pointer" : "default",
|
||||
...(getRowSx?.(row) as object),
|
||||
}}
|
||||
onClick={() => {
|
||||
if (expandableRows) handleExpand(row);
|
||||
@@ -454,12 +458,26 @@ function HasMoreTablePaginationActions(props: HasMoreTablePaginationActionsProps
|
||||
interface PaginationProps extends TablePaginationOwnProps {
|
||||
component?: React.ElementType;
|
||||
hasMore?: boolean;
|
||||
itemsOnPage?: number;
|
||||
}
|
||||
|
||||
export const Pagination = ({ ...props }: PaginationProps) => {
|
||||
const { hasMore, ...rest } = props;
|
||||
const { hasMore, itemsOnPage, ...rest } = props;
|
||||
const isSmall = useMediaQuery((theme: any) => theme.breakpoints.down("sm"));
|
||||
const theme = useTheme();
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
typeof itemsOnPage === "number" &&
|
||||
itemsOnPage === 0 &&
|
||||
rest.count > 0 &&
|
||||
rest.page > 0 &&
|
||||
rest.onPageChange
|
||||
) {
|
||||
rest.onPageChange(null, rest.page - 1);
|
||||
}
|
||||
}, [itemsOnPage, rest.count, rest.page, rest.onPageChange]);
|
||||
|
||||
const labelDisplayedRows = ({
|
||||
from,
|
||||
to,
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import MuiTabs from "@mui/material/Tabs";
|
||||
import type { TabsProps } from "@mui/material/Tabs";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
interface CustomTabsProps extends TabsProps {}
|
||||
|
||||
export const Tabs = (props: CustomTabsProps) => {
|
||||
const theme = useTheme();
|
||||
return (
|
||||
<MuiTabs
|
||||
sx={{
|
||||
minHeight: 34,
|
||||
borderBottom: `1px solid ${theme.palette.divider}`,
|
||||
"& .MuiTabs-indicator": {
|
||||
backgroundColor: theme.palette.primary.main,
|
||||
height: 2,
|
||||
bottom: 0,
|
||||
},
|
||||
"& .MuiTabs-flexContainer": {
|
||||
gap: theme.spacing(16),
|
||||
},
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
{props.children}
|
||||
</MuiTabs>
|
||||
);
|
||||
};
|
||||
|
||||
import MuiTab from "@mui/material/Tab";
|
||||
import type { TabProps } from "@mui/material/Tab";
|
||||
interface CustomTabProps extends TabProps {}
|
||||
|
||||
export const Tab = (props: CustomTabProps) => {
|
||||
const theme = useTheme();
|
||||
return (
|
||||
<MuiTab
|
||||
disableRipple
|
||||
iconPosition="start"
|
||||
sx={{
|
||||
textTransform: "none",
|
||||
fontSize: 14,
|
||||
fontWeight: 500,
|
||||
minHeight: 34,
|
||||
padding: theme.spacing(1, 0),
|
||||
paddingBottom: 0,
|
||||
minWidth: "auto",
|
||||
alignItems: "flex-start",
|
||||
color: theme.palette.text.secondary,
|
||||
"&.Mui-selected": {
|
||||
color: theme.palette.primary.main,
|
||||
fontWeight: 600,
|
||||
},
|
||||
"&:hover": {
|
||||
color: theme.palette.text.secondary,
|
||||
},
|
||||
"& .MuiTab-iconWrapper": {
|
||||
marginRight: theme.spacing(2),
|
||||
marginBottom: 0,
|
||||
},
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
import Typography from "@mui/material/Typography";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import type { StackProps } from "@mui/material/Stack";
|
||||
import Link from "@mui/material/Link";
|
||||
import { Link as RouterLink } from "react-router-dom";
|
||||
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
|
||||
interface TextLinkProps extends StackProps {
|
||||
text: string;
|
||||
linkText: string;
|
||||
href: string;
|
||||
target?: string;
|
||||
}
|
||||
|
||||
export const TextLink = ({
|
||||
text,
|
||||
linkText,
|
||||
href,
|
||||
target = "_self",
|
||||
...props
|
||||
}: TextLinkProps) => {
|
||||
const theme = useTheme();
|
||||
|
||||
return (
|
||||
<Stack
|
||||
direction="row"
|
||||
gap={theme.spacing(4)}
|
||||
{...props}
|
||||
>
|
||||
<Typography>{text}</Typography>
|
||||
<Link
|
||||
color="primary"
|
||||
to={href}
|
||||
component={RouterLink}
|
||||
target={target}
|
||||
>
|
||||
{linkText}
|
||||
</Link>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -15,3 +15,7 @@ export { default as Icon } from "./Icon";
|
||||
export * from "./Tooltip";
|
||||
export * from "./StatBox";
|
||||
export * from "./BaseChart";
|
||||
export * from "./Gauge";
|
||||
export * from "./Tabs";
|
||||
export * from "./SplitBox";
|
||||
export * from "./TextLink";
|
||||
@@ -0,0 +1,48 @@
|
||||
import { MuiColorInput } from "mui-color-input";
|
||||
import type { MuiColorInputProps } from "mui-color-input";
|
||||
import { typographyLevels } from "@/Utils/Theme/v2Palette";
|
||||
import { useTheme } from "@mui/material";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import { FieldLabel } from "@/Components/v2/inputs/FieldLabel";
|
||||
|
||||
interface ColorPickerProps extends MuiColorInputProps {
|
||||
fieldLabel?: string;
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
export const ColorInput = ({ fieldLabel, required, ...props }: ColorPickerProps) => {
|
||||
const theme = useTheme();
|
||||
const input = (
|
||||
<MuiColorInput
|
||||
{...props}
|
||||
sx={{
|
||||
"& .MuiOutlinedInput-root": {
|
||||
borderRadius: theme.shape.borderRadius,
|
||||
height: 34,
|
||||
fontSize: typographyLevels.base,
|
||||
},
|
||||
"& .MuiOutlinedInput-notchedOutline": {
|
||||
borderColor: theme.palette.divider,
|
||||
},
|
||||
"&:hover .MuiOutlinedInput-notchedOutline": {
|
||||
borderColor: theme.palette.divider,
|
||||
},
|
||||
"& .MuiFormHelperText-root": {
|
||||
marginLeft: 0,
|
||||
marginRight: 0,
|
||||
marginTop: theme.spacing(1),
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
if (fieldLabel) {
|
||||
return (
|
||||
<Stack spacing={theme.spacing(2)}>
|
||||
<FieldLabel required={required}>{fieldLabel}</FieldLabel>
|
||||
{input}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
return input;
|
||||
};
|
||||
@@ -0,0 +1,100 @@
|
||||
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
|
||||
import type { DatePickerProps } from "@mui/x-date-pickers/DatePicker";
|
||||
import type { Dayjs } from "dayjs";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import { FieldLabel } from "./FieldLabel";
|
||||
import { Calendar } from "lucide-react";
|
||||
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
|
||||
import { LocalizationProvider } from "@mui/x-date-pickers";
|
||||
|
||||
interface DatePickerComponentProps extends Omit<DatePickerProps<Dayjs>, "label"> {
|
||||
fieldLabel?: string;
|
||||
required?: boolean;
|
||||
error?: boolean;
|
||||
helperText?: string;
|
||||
}
|
||||
|
||||
export const DatePickerComponent = ({
|
||||
fieldLabel,
|
||||
required,
|
||||
error,
|
||||
helperText,
|
||||
...props
|
||||
}: DatePickerComponentProps) => {
|
||||
const theme = useTheme();
|
||||
|
||||
const picker = (
|
||||
<LocalizationProvider dateAdapter={AdapterDayjs}>
|
||||
<DatePicker
|
||||
{...props}
|
||||
slots={{
|
||||
openPickerIcon: () => (
|
||||
<Calendar
|
||||
size={20}
|
||||
stroke={theme.palette.text.secondary}
|
||||
/>
|
||||
),
|
||||
...props.slots,
|
||||
}}
|
||||
slotProps={{
|
||||
switchViewButton: { sx: { display: "none" } },
|
||||
nextIconButton: { sx: { ml: theme.spacing(2) } },
|
||||
day: {
|
||||
sx: {
|
||||
"&.MuiPickersDay-root.Mui-disabled": {
|
||||
color: theme.palette.text.disabled,
|
||||
},
|
||||
},
|
||||
},
|
||||
field: {
|
||||
sx: {
|
||||
width: "fit-content",
|
||||
"& > .MuiOutlinedInput-root": {
|
||||
flexDirection: "row-reverse",
|
||||
},
|
||||
"& input": {
|
||||
minHeight: 34,
|
||||
p: 0,
|
||||
pl: theme.spacing(3),
|
||||
pr: theme.spacing(5),
|
||||
},
|
||||
"& fieldset": {
|
||||
borderColor: error ? theme.palette.error.main : theme.palette.divider,
|
||||
borderRadius: theme.shape.borderRadius,
|
||||
},
|
||||
"&:not(:has(.Mui-disabled)):not(:has(.Mui-error)) .MuiOutlinedInput-root:not(:has(input:focus)):hover fieldset":
|
||||
{
|
||||
borderColor: error ? theme.palette.error.main : theme.palette.divider,
|
||||
},
|
||||
},
|
||||
},
|
||||
inputAdornment: { sx: { ml: 0 } },
|
||||
openPickerButton: {
|
||||
sx: {
|
||||
py: 0,
|
||||
mr: 0,
|
||||
},
|
||||
},
|
||||
...props.slotProps,
|
||||
}}
|
||||
/>
|
||||
</LocalizationProvider>
|
||||
);
|
||||
|
||||
return (
|
||||
<Stack spacing={theme.spacing(2)}>
|
||||
{fieldLabel && <FieldLabel required={required}>{fieldLabel}</FieldLabel>}
|
||||
{picker}
|
||||
{helperText && (
|
||||
<Typography
|
||||
variant="caption"
|
||||
color={error ? "error" : "text.secondary"}
|
||||
>
|
||||
{helperText}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
import Dialog from "@mui/material/Dialog";
|
||||
import type { DialogProps } from "@mui/material/Dialog";
|
||||
import DialogActions from "@mui/material/DialogActions";
|
||||
import DialogContent from "@mui/material/DialogContent";
|
||||
import DialogContentText from "@mui/material/DialogContentText";
|
||||
@@ -6,6 +7,7 @@ import DialogTitle from "@mui/material/DialogTitle";
|
||||
import { Button } from "@/Components/v2/inputs";
|
||||
import { typographyLevels } from "@/Utils/Theme/v2Palette";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export const DialogInput = ({
|
||||
open,
|
||||
@@ -16,6 +18,12 @@ export const DialogInput = ({
|
||||
confirmColor = "primary",
|
||||
cancelColor = "error",
|
||||
loading = false,
|
||||
cancelText,
|
||||
confirmText,
|
||||
children,
|
||||
maxWidth,
|
||||
fullWidth = false,
|
||||
additionalButtons,
|
||||
}: {
|
||||
open: boolean;
|
||||
title?: string;
|
||||
@@ -25,13 +33,24 @@ export const DialogInput = ({
|
||||
confirmColor?: "error" | "primary";
|
||||
cancelColor?: "error" | "primary";
|
||||
loading?: boolean;
|
||||
cancelText?: string;
|
||||
confirmText?: string;
|
||||
children?: ReactNode;
|
||||
maxWidth?: DialogProps["maxWidth"];
|
||||
fullWidth?: boolean;
|
||||
additionalButtons?: ReactNode;
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Dialog open={open}>
|
||||
<DialogTitle sx={{ fontSize: typographyLevels.l }}>{title}</DialogTitle>
|
||||
<Dialog
|
||||
open={open}
|
||||
maxWidth={maxWidth}
|
||||
fullWidth={fullWidth}
|
||||
>
|
||||
{title && <DialogTitle sx={{ fontSize: typographyLevels.l }}>{title}</DialogTitle>}
|
||||
<DialogContent>
|
||||
<DialogContentText>{content}</DialogContentText>
|
||||
{content && <DialogContentText>{content}</DialogContentText>}
|
||||
{children}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button
|
||||
@@ -40,16 +59,19 @@ export const DialogInput = ({
|
||||
color={cancelColor}
|
||||
onClick={onCancel}
|
||||
>
|
||||
{t("common.buttons.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
loading={loading}
|
||||
variant="contained"
|
||||
color={confirmColor}
|
||||
onClick={onConfirm}
|
||||
>
|
||||
{t("common.buttons.confirm")}
|
||||
{cancelText ?? t("common.buttons.cancel")}
|
||||
</Button>
|
||||
{additionalButtons}
|
||||
{onConfirm && (
|
||||
<Button
|
||||
loading={loading}
|
||||
variant="contained"
|
||||
color={confirmColor}
|
||||
onClick={onConfirm}
|
||||
>
|
||||
{confirmText ?? t("common.buttons.confirm")}
|
||||
</Button>
|
||||
)}
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -9,7 +9,9 @@ interface FieldLabelProps {
|
||||
|
||||
export const FieldLabel = ({ children, required = false, htmlFor }: FieldLabelProps) => {
|
||||
const theme = useTheme();
|
||||
|
||||
if (children === " ") {
|
||||
children = "\u00A0";
|
||||
}
|
||||
return (
|
||||
<Typography
|
||||
component="label"
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { Box, Stack, Typography, IconButton } from "@mui/material";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import { Upload, X } from "lucide-react";
|
||||
import { useState, useRef, useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface FileObject {
|
||||
src: string;
|
||||
name: string;
|
||||
file: File;
|
||||
}
|
||||
|
||||
interface ImageUploadProps {
|
||||
src?: string;
|
||||
onChange?: (file: FileObject | undefined) => void;
|
||||
maxSize?: number;
|
||||
accept?: string[];
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export const ImageUpload = ({
|
||||
src,
|
||||
onChange,
|
||||
maxSize = 3 * 1024 * 1024,
|
||||
accept = ["jpg", "jpeg", "png"],
|
||||
error,
|
||||
}: ImageUploadProps) => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const [localError, setLocalError] = useState<string | null>(null);
|
||||
const [preview, setPreview] = useState<FileObject | null>(null);
|
||||
|
||||
const handleFile = useCallback(
|
||||
(file: File | undefined) => {
|
||||
if (!file) return;
|
||||
const isValidType = accept.some((type) => file.type.includes(type));
|
||||
const isValidSize = file.size <= maxSize;
|
||||
if (!isValidType) {
|
||||
setLocalError(t("common.errors.invalidFileFormat"));
|
||||
return;
|
||||
}
|
||||
if (!isValidSize) {
|
||||
setLocalError(t("common.errors.invalidFileSize"));
|
||||
return;
|
||||
}
|
||||
setLocalError(null);
|
||||
const fileObj: FileObject = {
|
||||
src: URL.createObjectURL(file),
|
||||
name: file.name,
|
||||
file,
|
||||
};
|
||||
setPreview(fileObj);
|
||||
onChange?.(fileObj);
|
||||
},
|
||||
[maxSize, accept, onChange, t]
|
||||
);
|
||||
|
||||
const handleClear = () => {
|
||||
setPreview(null);
|
||||
setLocalError(null);
|
||||
onChange?.(undefined);
|
||||
if (inputRef.current) inputRef.current.value = "";
|
||||
};
|
||||
|
||||
const displaySrc = src || preview?.src;
|
||||
const displayError = localError || error;
|
||||
|
||||
return (
|
||||
<Stack sx={{ width: "100%", maxWidth: 500 }}>
|
||||
{displaySrc ? (
|
||||
<Stack
|
||||
alignItems="center"
|
||||
gap={1}
|
||||
>
|
||||
<Box
|
||||
component="img"
|
||||
src={displaySrc}
|
||||
alt="Preview"
|
||||
sx={{ maxWidth: 250, maxHeight: 250, objectFit: "contain", borderRadius: 1 }}
|
||||
/>
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={handleClear}
|
||||
sx={{ color: theme.palette.error.main }}
|
||||
>
|
||||
<X size={18} />
|
||||
</IconButton>
|
||||
</Stack>
|
||||
) : (
|
||||
<Stack
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(true);
|
||||
}}
|
||||
onDragLeave={() => setIsDragging(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
handleFile(e.dataTransfer.files?.[0]);
|
||||
}}
|
||||
alignItems="center"
|
||||
justifyContent="center"
|
||||
gap={1}
|
||||
sx={{
|
||||
position: "relative",
|
||||
width: "100%",
|
||||
minHeight: 150,
|
||||
border: "2px dashed",
|
||||
borderRadius: 1,
|
||||
borderColor: isDragging ? theme.palette.primary.main : theme.palette.divider,
|
||||
backgroundColor: isDragging ? theme.palette.action.hover : "transparent",
|
||||
transition: "0.2s",
|
||||
cursor: "pointer",
|
||||
"&:hover": {
|
||||
borderColor: theme.palette.primary.main,
|
||||
backgroundColor: theme.palette.action.hover,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept={accept.map((ext) => `.${ext}`).join(",")}
|
||||
onChange={(e) => handleFile(e.target.files?.[0])}
|
||||
style={{ position: "absolute", inset: 0, opacity: 0, cursor: "pointer" }}
|
||||
/>
|
||||
<Upload size={24} />
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
>
|
||||
<Typography
|
||||
component="span"
|
||||
variant="body2"
|
||||
color="primary"
|
||||
fontWeight={500}
|
||||
>
|
||||
{t("common.imageUpload.clickToUpload")}
|
||||
</Typography>{" "}
|
||||
{t("common.imageUpload.orDragAndDrop")}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="caption"
|
||||
color="text.disabled"
|
||||
>
|
||||
{accept.join(", ").toUpperCase()} • {t("common.imageUpload.maxSize")}{" "}
|
||||
{Math.round(maxSize / 1024 / 1024)}MB
|
||||
</Typography>
|
||||
</Stack>
|
||||
)}
|
||||
{displayError && (
|
||||
<Typography
|
||||
variant="caption"
|
||||
color="error"
|
||||
sx={{ mt: 1 }}
|
||||
>
|
||||
{displayError}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,100 @@
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Box from "@mui/material/Box";
|
||||
import MenuItem from "@mui/material/MenuItem";
|
||||
import { Select } from "@/Components/v2/inputs";
|
||||
import "flag-icons/css/flag-icons.min.css";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useTheme } from "@mui/material";
|
||||
import { useSelector } from "react-redux";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { setLanguage } from "@/Features/UI/uiSlice";
|
||||
import type { RootState } from "@/Types/state";
|
||||
|
||||
const langMap: Record<string, string> = {
|
||||
cs: "cz",
|
||||
ja: "jp",
|
||||
uk: "ua",
|
||||
vi: "vn",
|
||||
};
|
||||
|
||||
export const LanguageSelector = () => {
|
||||
const { i18n } = useTranslation();
|
||||
const theme = useTheme();
|
||||
const { language = "en" } = useSelector((state: RootState) => state.ui);
|
||||
const dispatch = useDispatch();
|
||||
const handleChange = (event: any) => {
|
||||
const newLang = event.target.value;
|
||||
dispatch(setLanguage(newLang));
|
||||
};
|
||||
|
||||
const languages = Object.keys(i18n.options.resources || {});
|
||||
|
||||
return (
|
||||
<Select
|
||||
value={language}
|
||||
onChange={handleChange}
|
||||
size="small"
|
||||
// sx={{
|
||||
// minWidth: 80,
|
||||
// "& .MuiSelect-select": {
|
||||
// display: "flex",
|
||||
// alignItems: "center",
|
||||
// justifyContent: "center",
|
||||
// },
|
||||
// "& .MuiSelect-icon": {
|
||||
// alignSelf: "center",
|
||||
// },
|
||||
// }}
|
||||
>
|
||||
{languages.map((lang) => {
|
||||
let parsedLang = lang === "en" ? "gb" : lang;
|
||||
|
||||
if (parsedLang.includes("-")) {
|
||||
parsedLang = parsedLang.split("-")[1].toLowerCase();
|
||||
}
|
||||
|
||||
parsedLang = langMap[parsedLang] || parsedLang;
|
||||
|
||||
const flag = parsedLang ? `fi fi-${parsedLang}` : null;
|
||||
|
||||
return (
|
||||
<MenuItem
|
||||
key={lang}
|
||||
value={lang}
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={theme.spacing(2)}
|
||||
alignItems="center"
|
||||
justifyContent="center"
|
||||
>
|
||||
<Box
|
||||
component="span"
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
{flag && <span className={flag} />}
|
||||
</Box>
|
||||
<Box
|
||||
component="span"
|
||||
sx={{ textTransform: "uppercase" }}
|
||||
>
|
||||
{lang}
|
||||
</Box>
|
||||
</Stack>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
</Select>
|
||||
);
|
||||
};
|
||||
|
||||
export default LanguageSelector;
|
||||
@@ -0,0 +1,88 @@
|
||||
import Radio from "@mui/material/Radio";
|
||||
import type { RadioProps } from "@mui/material/Radio";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import { Circle, CircleDot } from "lucide-react";
|
||||
import FormControlLabel from "@mui/material/FormControlLabel";
|
||||
import Typography from "@mui/material/Typography";
|
||||
|
||||
interface RadioInputProps extends RadioProps {}
|
||||
|
||||
export const RadioInput = ({ ...props }: RadioInputProps) => {
|
||||
const theme = useTheme();
|
||||
return (
|
||||
<Radio
|
||||
{...props}
|
||||
icon={
|
||||
<Circle
|
||||
size={16}
|
||||
strokeWidth={1.5}
|
||||
/>
|
||||
}
|
||||
checkedIcon={
|
||||
<CircleDot
|
||||
size={14}
|
||||
strokeWidth={1.5}
|
||||
/>
|
||||
}
|
||||
sx={{
|
||||
padding: 0,
|
||||
mt: theme.spacing(0.5),
|
||||
color: theme.palette.text.secondary,
|
||||
"&.Mui-checked": {
|
||||
color: theme.palette.primary.main,
|
||||
"& svg circle": {
|
||||
fill: theme.palette.primary.main,
|
||||
},
|
||||
},
|
||||
"& .MuiSvgIcon-root": {
|
||||
fontSize: 16,
|
||||
},
|
||||
"& svg": {
|
||||
stroke: "currentColor",
|
||||
},
|
||||
"& svg path, & svg line, & svg polyline, & svg rect, & svg circle": {
|
||||
stroke: "currentColor",
|
||||
fill: "none",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export const RadioWithDescription = ({
|
||||
label,
|
||||
description,
|
||||
...props
|
||||
}: RadioInputProps & { label: string; description: string }) => {
|
||||
const theme = useTheme();
|
||||
return (
|
||||
<FormControlLabel
|
||||
control={<RadioInput {...props} />}
|
||||
label={
|
||||
<>
|
||||
<Typography component="p">{label}</Typography>
|
||||
<Typography
|
||||
component="h6"
|
||||
color={theme.palette.text.secondary}
|
||||
>
|
||||
{description}
|
||||
</Typography>
|
||||
</>
|
||||
}
|
||||
sx={{
|
||||
alignItems: "flex-start",
|
||||
p: theme.spacing(2.5),
|
||||
m: theme.spacing(-2.5),
|
||||
borderRadius: theme.shape.borderRadius,
|
||||
|
||||
"&:hover": {
|
||||
backgroundColor: theme.palette.background.paper,
|
||||
},
|
||||
"& .MuiButtonBase-root": {
|
||||
p: 0,
|
||||
mr: theme.spacing(6),
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
import Select from "@mui/material/Select";
|
||||
import React from "react";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import type { SelectProps } from "@mui/material/Select";
|
||||
import React, { forwardRef } from "react";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import { FieldLabel } from "./FieldLabel";
|
||||
import { ChevronDown } from "lucide-react";
|
||||
@@ -14,18 +14,15 @@ interface SelectInputProps<T> extends Omit<SelectProps<T>, "label"> {
|
||||
placeholderColor?: string;
|
||||
}
|
||||
|
||||
export const SelectInput = <T,>({
|
||||
fieldLabel,
|
||||
required,
|
||||
placeholder,
|
||||
placeholderColor,
|
||||
...props
|
||||
}: SelectInputProps<T>) => {
|
||||
const SelectInputInner = <T,>(
|
||||
{ fieldLabel, required, placeholder, placeholderColor, ...props }: SelectInputProps<T>,
|
||||
ref: React.ForwardedRef<HTMLDivElement>
|
||||
) => {
|
||||
const theme = useTheme();
|
||||
const emptyPlaceholderColor = placeholderColor || theme.palette.text.disabled;
|
||||
|
||||
const renderValue = (selected: any) => {
|
||||
const isMultiple = Boolean((props as any).multiple);
|
||||
const renderValue = (selected: unknown) => {
|
||||
const isMultiple = Boolean((props as { multiple?: boolean }).multiple);
|
||||
const isEmpty = isMultiple
|
||||
? !Array.isArray(selected) || selected.length === 0
|
||||
: selected === undefined || selected === null || selected === "";
|
||||
@@ -39,7 +36,7 @@ export const SelectInput = <T,>({
|
||||
const capitalized = items.map(
|
||||
(item) => item.charAt(0).toUpperCase() + item.slice(1)
|
||||
);
|
||||
return (<Typography>{capitalized.join(" | ")}</Typography>) as any;
|
||||
return <Typography>{capitalized.join(" | ")}</Typography>;
|
||||
}
|
||||
|
||||
const nodes = React.Children.toArray(props.children as React.ReactNode);
|
||||
@@ -59,6 +56,7 @@ export const SelectInput = <T,>({
|
||||
const select = (
|
||||
<Select<T>
|
||||
{...props}
|
||||
ref={ref}
|
||||
displayEmpty
|
||||
renderValue={renderValue}
|
||||
inputProps={{
|
||||
@@ -74,6 +72,12 @@ export const SelectInput = <T,>({
|
||||
)}
|
||||
sx={{
|
||||
height: "34px",
|
||||
"& .MuiSelect-select": {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
height: "100%",
|
||||
boxSizing: "border-box",
|
||||
},
|
||||
"& .MuiSelect-icon": {
|
||||
right: theme.spacing(3),
|
||||
},
|
||||
@@ -100,3 +104,7 @@ export const SelectInput = <T,>({
|
||||
|
||||
return select;
|
||||
};
|
||||
|
||||
export const SelectInput = forwardRef(SelectInputInner) as <T>(
|
||||
props: SelectInputProps<T> & { ref?: React.ForwardedRef<HTMLDivElement> }
|
||||
) => React.ReactElement;
|
||||
@@ -0,0 +1,89 @@
|
||||
import Typography from "@mui/material/Typography";
|
||||
import { forwardRef } from "react";
|
||||
import Slider from "@mui/material/Slider";
|
||||
import type { SliderProps } from "@mui/material/Slider";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import { FieldLabel } from "./FieldLabel";
|
||||
import Box from "@mui/material/Box";
|
||||
import type { ResponsiveStyleValue } from "@mui/system";
|
||||
|
||||
interface SliderInputProps extends SliderProps {
|
||||
sx?: SliderProps["sx"];
|
||||
showValue?: boolean;
|
||||
}
|
||||
|
||||
export const SliderInput = forwardRef<HTMLSpanElement, SliderInputProps>(
|
||||
({ sx, showValue = false, ...props }, ref) => {
|
||||
const theme = useTheme();
|
||||
const additionalSx = Array.isArray(sx) ? sx : sx ? [sx] : [];
|
||||
|
||||
return (
|
||||
<Stack
|
||||
gap={theme.spacing(8)}
|
||||
direction={"row"}
|
||||
alignItems={"center"}
|
||||
>
|
||||
{showValue && <Typography>{props.value}</Typography>}
|
||||
<Slider
|
||||
{...props}
|
||||
ref={ref}
|
||||
sx={[
|
||||
{
|
||||
"& .MuiSlider-track": {
|
||||
backgroundColor: theme.palette.primary.main,
|
||||
border: "none",
|
||||
},
|
||||
"& .MuiSlider-rail": {
|
||||
backgroundColor: theme.palette.grey[300],
|
||||
opacity: 1,
|
||||
},
|
||||
"& .MuiSlider-thumb": {
|
||||
backgroundColor: "#fff",
|
||||
"&:hover, &.Mui-focusVisible": {
|
||||
boxShadow: `0 0 0 8px ${theme.palette.primary.main}20`,
|
||||
},
|
||||
},
|
||||
"& .MuiSlider-valueLabel": {
|
||||
backgroundColor: theme.palette.primary.main,
|
||||
},
|
||||
},
|
||||
...additionalSx,
|
||||
]}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
interface SliderWithLabelProps extends SliderProps {
|
||||
fieldLabel?: string;
|
||||
required?: boolean;
|
||||
showValue?: boolean;
|
||||
sliderMaxWidth?: ResponsiveStyleValue<number | string>;
|
||||
}
|
||||
|
||||
export const SliderWithLabel = forwardRef<HTMLSpanElement, SliderWithLabelProps>(
|
||||
(
|
||||
{ fieldLabel, required, showValue = true, value, sliderMaxWidth = "100%", ...props },
|
||||
ref
|
||||
) => {
|
||||
const theme = useTheme();
|
||||
|
||||
const labelText = fieldLabel;
|
||||
|
||||
return (
|
||||
<Stack spacing={theme.spacing(2)}>
|
||||
{fieldLabel && <FieldLabel required={required}>{labelText}</FieldLabel>}
|
||||
<Box maxWidth={sliderMaxWidth}>
|
||||
<SliderInput
|
||||
{...props}
|
||||
showValue={showValue}
|
||||
value={value}
|
||||
ref={ref}
|
||||
/>
|
||||
</Box>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,47 @@
|
||||
import { forwardRef } from "react";
|
||||
import Switch from "@mui/material/Switch";
|
||||
import type { SwitchProps } from "@mui/material/Switch";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
|
||||
interface SwitchComponentProps extends SwitchProps {
|
||||
dualOption?: boolean;
|
||||
}
|
||||
|
||||
export const SwitchComponent = forwardRef<HTMLInputElement, SwitchComponentProps>(
|
||||
function SwitchComponent({ sx, dualOption = false, ...props }, ref) {
|
||||
const theme = useTheme();
|
||||
const additionalSx = Array.isArray(sx) ? sx : sx ? [sx] : [];
|
||||
|
||||
return (
|
||||
<Switch
|
||||
{...props}
|
||||
slotProps={{
|
||||
input: {
|
||||
ref: ref,
|
||||
},
|
||||
}}
|
||||
sx={[
|
||||
{
|
||||
"& .MuiSwitch-switchBase": {
|
||||
"&.Mui-checked": {
|
||||
color: "#E0E0E0",
|
||||
"& + .MuiSwitch-track": {
|
||||
backgroundColor: theme.palette.primary.main,
|
||||
opacity: 1,
|
||||
border: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
...(dualOption && {
|
||||
"& .MuiSwitch-track": {
|
||||
backgroundColor: theme.palette.primary.main,
|
||||
opacity: 1,
|
||||
},
|
||||
}),
|
||||
},
|
||||
...additionalSx,
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,48 @@
|
||||
import IconButton from "@mui/material/IconButton";
|
||||
|
||||
import { Moon, Sun } from "lucide-react";
|
||||
|
||||
import { setMode } from "@/Features/UI/uiSlice.js";
|
||||
import { useTheme } from "@mui/material";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import type { RootState } from "@/Types/state";
|
||||
|
||||
export const SwitchTheme = () => {
|
||||
const mode = useSelector((state: RootState) => state.ui.mode);
|
||||
const dispatch = useDispatch();
|
||||
const theme = useTheme();
|
||||
|
||||
const handleChange = () => {
|
||||
dispatch(setMode(mode === "light" ? "dark" : "light"));
|
||||
};
|
||||
return (
|
||||
<IconButton
|
||||
id="theme-toggle"
|
||||
onClick={handleChange}
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
"& svg": {
|
||||
transition: "stroke 0.2s ease",
|
||||
},
|
||||
"&:hover svg path, &:hover svg line, &:hover svg polyline, &:hover svg rect, &:hover svg circle":
|
||||
{
|
||||
stroke: theme.palette.primary.main,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{mode === "light" ? (
|
||||
<Moon
|
||||
size={16}
|
||||
strokeWidth={1.5}
|
||||
/>
|
||||
) : (
|
||||
<Sun
|
||||
size={16}
|
||||
strokeWidth={1.5}
|
||||
/>
|
||||
)}
|
||||
</IconButton>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
import { MobileTimePicker } from "@mui/x-date-pickers/MobileTimePicker";
|
||||
import type { MobileTimePickerProps } from "@mui/x-date-pickers/MobileTimePicker";
|
||||
import type { Dayjs } from "dayjs";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import { FieldLabel } from "./FieldLabel";
|
||||
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
|
||||
import { LocalizationProvider } from "@mui/x-date-pickers";
|
||||
|
||||
interface TimePickerComponentProps extends Omit<MobileTimePickerProps<Dayjs>, "label"> {
|
||||
fieldLabel?: string;
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
export const TimePickerComponent = ({
|
||||
fieldLabel,
|
||||
required,
|
||||
...props
|
||||
}: TimePickerComponentProps) => {
|
||||
const theme = useTheme();
|
||||
|
||||
const picker = (
|
||||
<LocalizationProvider dateAdapter={AdapterDayjs}>
|
||||
<MobileTimePicker
|
||||
{...props}
|
||||
slotProps={{
|
||||
field: {
|
||||
sx: {
|
||||
width: "fit-content",
|
||||
"& input": {
|
||||
minHeight: 34,
|
||||
p: 0,
|
||||
px: theme.spacing(5),
|
||||
},
|
||||
"& fieldset": {
|
||||
borderColor: theme.palette.divider,
|
||||
borderRadius: theme.shape.borderRadius,
|
||||
},
|
||||
"&:not(:has(.Mui-disabled)):not(:has(.Mui-error)) .MuiOutlinedInput-root:not(:has(input:focus)):hover fieldset":
|
||||
{
|
||||
borderColor: theme.palette.divider,
|
||||
},
|
||||
},
|
||||
},
|
||||
...props.slotProps,
|
||||
}}
|
||||
/>
|
||||
</LocalizationProvider>
|
||||
);
|
||||
|
||||
if (fieldLabel) {
|
||||
return (
|
||||
<Stack spacing={theme.spacing(2)}>
|
||||
<FieldLabel required={required}>{fieldLabel}</FieldLabel>
|
||||
{picker}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
return picker;
|
||||
};
|
||||
@@ -9,3 +9,12 @@ export {
|
||||
ToggleButtonGroupInput as ToggleButtonGroup,
|
||||
} from "./ToggleButton";
|
||||
export { DialogInput as Dialog } from "./Dialog";
|
||||
export * from "./Radio";
|
||||
export * from "./Switch";
|
||||
export * from "./Slider";
|
||||
export * from "./ImageUpload";
|
||||
export * from "./ColorPicker";
|
||||
export { DatePickerComponent as DatePicker } from "./DatePicker";
|
||||
export { TimePickerComponent as TimePicker } from "./TimePicker";
|
||||
export * from "./LanguageSelector";
|
||||
export * from "./SwitchTheme";
|
||||
@@ -6,11 +6,12 @@ import useMediaQuery from "@mui/material/useMediaQuery";
|
||||
import type { MonitorType } from "@/Types/Monitor";
|
||||
import { Typography, useTheme } from "@mui/material";
|
||||
|
||||
const types = ["http", "ping", "port", "docker"];
|
||||
const types = ["http", "ping", "port", "docker", "game"];
|
||||
const statuses = ["up", "down"];
|
||||
const states = ["active", "paused"];
|
||||
|
||||
export const ControlsFilter = ({
|
||||
showTypes = true,
|
||||
selectedTypes,
|
||||
setSelectedTypes,
|
||||
selectedStatus,
|
||||
@@ -19,8 +20,9 @@ export const ControlsFilter = ({
|
||||
setSelectedState,
|
||||
onClearFilters,
|
||||
}: {
|
||||
selectedTypes: MonitorType[];
|
||||
setSelectedTypes: React.Dispatch<React.SetStateAction<MonitorType[]>>;
|
||||
showTypes?: boolean;
|
||||
selectedTypes?: MonitorType[];
|
||||
setSelectedTypes?: React.Dispatch<React.SetStateAction<MonitorType[]>>;
|
||||
selectedStatus: string;
|
||||
setSelectedStatus: React.Dispatch<React.SetStateAction<string>>;
|
||||
selectedState: string;
|
||||
@@ -30,27 +32,29 @@ export const ControlsFilter = ({
|
||||
const theme = useTheme();
|
||||
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
|
||||
const isFilterActive =
|
||||
selectedTypes.length > 0 || selectedStatus !== "" || selectedState !== "";
|
||||
(selectedTypes?.length ?? 0) > 0 || selectedStatus !== "" || selectedState !== "";
|
||||
return (
|
||||
<Stack
|
||||
direction={isSmall ? "column" : "row"}
|
||||
gap={theme.spacing(2)}
|
||||
>
|
||||
<Select
|
||||
multiple
|
||||
placeholder="Type"
|
||||
value={selectedTypes}
|
||||
onChange={(e) => setSelectedTypes(e.target.value as MonitorType[])}
|
||||
>
|
||||
{types.map((type) => (
|
||||
<MenuItem
|
||||
key={type}
|
||||
value={type}
|
||||
>
|
||||
<Typography textTransform={"capitalize"}>{type}</Typography>
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
{showTypes && setSelectedTypes && (
|
||||
<Select
|
||||
multiple
|
||||
placeholder="Type"
|
||||
value={selectedTypes ?? []}
|
||||
onChange={(e) => setSelectedTypes(e.target.value as MonitorType[])}
|
||||
>
|
||||
{types.map((type) => (
|
||||
<MenuItem
|
||||
key={type}
|
||||
value={type}
|
||||
>
|
||||
<Typography textTransform={"capitalize"}>{type}</Typography>
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
)}
|
||||
<Select
|
||||
placeholder="Status"
|
||||
value={selectedStatus}
|
||||
|
||||
+87
-13
@@ -1,7 +1,7 @@
|
||||
import Stack from "@mui/material/Stack";
|
||||
import { Icon, MonitorStatus } from "@/Components/v2/design-elements";
|
||||
import { Button } from "@/Components/v2/inputs";
|
||||
import { Settings, Pause, Play, Mail, Bug } from "lucide-react";
|
||||
import { Settings, Pause, Play, Mail, Bug, Trash } from "lucide-react";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
@@ -9,10 +9,28 @@ import { useTheme } from "@mui/material/styles";
|
||||
import { usePost } from "@/Hooks/UseApi";
|
||||
|
||||
import type { Monitor } from "@/Types/Monitor.js";
|
||||
interface BaseHeaderProps {
|
||||
monitor: Monitor;
|
||||
}
|
||||
|
||||
const BaseHeader = ({ monitor, children }: React.PropsWithChildren<BaseHeaderProps>) => {
|
||||
const theme = useTheme();
|
||||
return (
|
||||
<Stack
|
||||
spacing={{ xs: theme.spacing(8), md: 0 }}
|
||||
direction={{ xs: "column", md: "row" }}
|
||||
alignItems={"center"}
|
||||
justifyContent={"space-between"}
|
||||
>
|
||||
<MonitorStatus monitor={monitor} />
|
||||
{children}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
interface HeaderMonitorControlsProps {
|
||||
path: string;
|
||||
monitor?: Monitor;
|
||||
monitor?: Monitor | null;
|
||||
isAdmin: boolean;
|
||||
refetch: Function;
|
||||
}
|
||||
@@ -24,8 +42,8 @@ export const HeaderMonitorControls = ({
|
||||
refetch,
|
||||
}: HeaderMonitorControlsProps) => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const theme = useTheme();
|
||||
const navigate = useNavigate();
|
||||
const {
|
||||
post,
|
||||
loading: isPosting,
|
||||
@@ -36,13 +54,7 @@ export const HeaderMonitorControls = ({
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<Stack
|
||||
spacing={{ xs: theme.spacing(8), md: 0 }}
|
||||
direction={{ xs: "column", md: "row" }}
|
||||
alignItems={"center"}
|
||||
justifyContent={"space-between"}
|
||||
>
|
||||
<MonitorStatus monitor={monitor} />
|
||||
<BaseHeader monitor={monitor}>
|
||||
<Stack
|
||||
width={{ xs: "100%", md: "auto" }}
|
||||
direction={{ xs: "column", md: "row" }}
|
||||
@@ -83,7 +95,7 @@ export const HeaderMonitorControls = ({
|
||||
await refetch();
|
||||
}}
|
||||
>
|
||||
{monitor?.isActive ? t("pause") : t("resume")}
|
||||
{monitor?.isActive ? t("common.buttons.pause") : t("common.buttons.resume")}
|
||||
</Button>
|
||||
)}
|
||||
{isAdmin && (
|
||||
@@ -93,10 +105,72 @@ export const HeaderMonitorControls = ({
|
||||
startIcon={<Icon icon={Settings} />}
|
||||
onClick={() => navigate(`/${path}/configure/${monitor.id}`)}
|
||||
>
|
||||
Configure
|
||||
{t("common.buttons.configure")}
|
||||
</Button>
|
||||
)}
|
||||
</Stack>
|
||||
</Stack>
|
||||
</BaseHeader>
|
||||
);
|
||||
};
|
||||
|
||||
interface HeaderDeleteControlsProps {
|
||||
monitor?: Monitor | null;
|
||||
isAdmin: boolean;
|
||||
refetch: Function;
|
||||
onDelete?: () => void;
|
||||
}
|
||||
|
||||
export const HeaderDeleteControls = ({
|
||||
monitor,
|
||||
isAdmin,
|
||||
refetch,
|
||||
onDelete,
|
||||
}: HeaderDeleteControlsProps) => {
|
||||
const { t } = useTranslation();
|
||||
const theme = useTheme();
|
||||
const {
|
||||
post,
|
||||
loading: isPosting,
|
||||
// error: postError,
|
||||
} = usePost<any, Monitor>();
|
||||
|
||||
if (!monitor) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<BaseHeader monitor={monitor}>
|
||||
<Stack
|
||||
width={{ xs: "100%", md: "auto" }}
|
||||
direction={{ xs: "column", md: "row" }}
|
||||
gap={theme.spacing(2)}
|
||||
>
|
||||
{isAdmin && (
|
||||
<Button
|
||||
variant="contained"
|
||||
color="secondary"
|
||||
loading={isPosting}
|
||||
startIcon={monitor?.isActive ? <Icon icon={Pause} /> : <Icon icon={Play} />}
|
||||
onClick={async () => {
|
||||
await post(`/monitors/pause/${monitor.id}`, {});
|
||||
await refetch();
|
||||
}}
|
||||
>
|
||||
{monitor?.isActive ? t("common.buttons.pause") : t("common.buttons.resume")}
|
||||
</Button>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<Button
|
||||
variant="contained"
|
||||
color="error"
|
||||
startIcon={<Icon icon={Trash} />}
|
||||
onClick={() => {
|
||||
onDelete?.();
|
||||
}}
|
||||
>
|
||||
{t("common.buttons.delete")}
|
||||
</Button>
|
||||
)}
|
||||
</Stack>
|
||||
</BaseHeader>
|
||||
);
|
||||
};
|
||||
@@ -1,9 +1,9 @@
|
||||
import Stack from "@mui/material/Stack";
|
||||
import { StatBox } from "@/Components/v2/design-elements";
|
||||
|
||||
import prettyMilliseconds from "pretty-ms";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import type { MonitorStats, Monitor } from "@/Types/Monitor";
|
||||
import { getHumanReadableDuration } from "@/Utils/timeUtilsLegacy.js";
|
||||
import { getStatusPalette } from "@/Utils/MonitorUtils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -32,11 +32,16 @@ export const MonitorStatBoxes = ({
|
||||
|
||||
// Determine time since last check
|
||||
const timeOfLastCheck = monitorStats?.lastCheckTimestamp || 0;
|
||||
const timeSinceLastCheck = Date.now() - timeOfLastCheck;
|
||||
const timeSinceLastCheck = Date.now() - timeOfLastCheck || 0;
|
||||
|
||||
const streakTime = getHumanReadableDuration(timeSinceLastFailure);
|
||||
const options = {
|
||||
secondsDecimalDigits: 0,
|
||||
millisecondsDecimalDigits: 0,
|
||||
};
|
||||
|
||||
const lastCheckTime = getHumanReadableDuration(timeSinceLastCheck);
|
||||
const streakTime = prettyMilliseconds(timeSinceLastFailure, options);
|
||||
|
||||
const lastCheckTime = prettyMilliseconds(timeSinceLastCheck, options);
|
||||
const palette = getStatusPalette(monitor?.status);
|
||||
|
||||
return (
|
||||
@@ -55,7 +60,7 @@ export const MonitorStatBoxes = ({
|
||||
/>
|
||||
<StatBox
|
||||
title={t("pages.common.monitors.statBoxes.lastResponseTime")}
|
||||
subtitle={monitorStats?.lastResponseTime + " ms"}
|
||||
subtitle={prettyMilliseconds(monitorStats?.lastResponseTime ?? 0)}
|
||||
/>
|
||||
|
||||
{monitor?.type === "http" && (
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import { BaseChart } from "@/Components/v2/design-elements";
|
||||
import {
|
||||
AreaChart,
|
||||
Area,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
ResponsiveContainer,
|
||||
} from "recharts";
|
||||
import { Fragment, useId } from "react";
|
||||
import { XTick } from "@/Components/v2/monitors";
|
||||
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import type { HardwareCheckStats } from "@/Types/Monitor";
|
||||
|
||||
const AREA_COLORS = [
|
||||
// Blues
|
||||
"#3182bd", // Deep blue
|
||||
"#6baed6", // Medium blue
|
||||
"#9ecae1", // Light blue
|
||||
|
||||
// Greens
|
||||
"#74c476", // Soft green
|
||||
"#a1d99b", // Light green
|
||||
"#c7e9c0", // Pale green
|
||||
|
||||
// Oranges
|
||||
"#fdae6b", // Warm orange
|
||||
"#fdd0a2", // Light orange
|
||||
"#feedde", // Pale orange
|
||||
|
||||
// Purples
|
||||
"#9467bd", // Lavender
|
||||
"#a55194", // Deep magenta
|
||||
"#c994c7", // Soft magenta
|
||||
|
||||
// Reds
|
||||
"#ff9896", // Soft red
|
||||
"#de2d26", // Deep red
|
||||
"#fc9272", // Medium red
|
||||
|
||||
// Cyans/Teals
|
||||
"#17becf", // Cyan
|
||||
"#7fcdbb", // Teal
|
||||
"#a1dab4", // Light teal
|
||||
|
||||
// Yellows
|
||||
"#fec44f", // Mustard
|
||||
"#fee391", // Light yellow
|
||||
"#ffffd4", // Pale yellow
|
||||
|
||||
// Additional colors
|
||||
"#e377c2", // Soft pink
|
||||
"#bcbd22", // Olive
|
||||
"#2ca02c", // Vibrant green
|
||||
];
|
||||
|
||||
const createGradient = ({
|
||||
id,
|
||||
startColor,
|
||||
endColor,
|
||||
startOpacity = 0.8,
|
||||
endOpacity = 0,
|
||||
direction = "vertical",
|
||||
}: {
|
||||
id: string;
|
||||
startColor: string;
|
||||
endColor: string;
|
||||
startOpacity?: number;
|
||||
endOpacity?: number;
|
||||
direction?: "vertical" | "horizontal";
|
||||
}) => (
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={id}
|
||||
x1={direction === "vertical" ? "0" : "0"}
|
||||
y1={direction === "vertical" ? "0" : "0"}
|
||||
x2={direction === "vertical" ? "0" : "1"}
|
||||
y2={direction === "vertical" ? "1" : "0"}
|
||||
>
|
||||
<stop
|
||||
offset="0%"
|
||||
stopColor={startColor}
|
||||
stopOpacity={startOpacity}
|
||||
/>
|
||||
<stop
|
||||
offset="100%"
|
||||
stopColor={endColor}
|
||||
stopOpacity={endOpacity}
|
||||
/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
);
|
||||
|
||||
export const HistogramInfrastructure = ({
|
||||
dateRange,
|
||||
title,
|
||||
type,
|
||||
idx: _idx,
|
||||
checks,
|
||||
xKey,
|
||||
yDomain,
|
||||
dataKeys,
|
||||
gradient = false,
|
||||
gradientDirection = "vertical",
|
||||
gradientStartColor,
|
||||
gradientEndColor,
|
||||
strokeColor,
|
||||
fillColor,
|
||||
yAxisFormatter,
|
||||
}: {
|
||||
dateRange: string;
|
||||
title: string;
|
||||
type: string;
|
||||
idx: number | null;
|
||||
checks: HardwareCheckStats[];
|
||||
xKey: string;
|
||||
yDomain?: number[];
|
||||
dataKeys: string[];
|
||||
gradient?: boolean;
|
||||
gradientDirection?: "vertical" | "horizontal";
|
||||
gradientStartColor?: string;
|
||||
gradientEndColor?: string;
|
||||
strokeColor: string;
|
||||
fillColor?: string;
|
||||
yAxisFormatter?: (value: number) => string;
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
const uniqueId = useId();
|
||||
const data = checks;
|
||||
|
||||
let avgTemps: { bucketDate: string; avg_temp: number | null }[] = [];
|
||||
let tempYDomain: number[] = [];
|
||||
if (type === "temp") {
|
||||
avgTemps = data.map((check) => {
|
||||
const temps = check.avgTemperature || [];
|
||||
if (temps.length === 0) return { bucketDate: check.bucketDate, avg_temp: null };
|
||||
const totalTemp = temps.reduce((sum, temp) => sum + (temp || 0), 0);
|
||||
const avgTemp = totalTemp / temps.length;
|
||||
return { bucketDate: check.bucketDate, avg_temp: avgTemp };
|
||||
});
|
||||
|
||||
const maxTemp: number = avgTemps.reduce((max, item) => {
|
||||
return item.avg_temp && item.avg_temp > max ? item.avg_temp : max;
|
||||
}, 0);
|
||||
|
||||
tempYDomain = [0, Math.ceil((maxTemp * 1.3) / 10) * 10];
|
||||
}
|
||||
|
||||
return (
|
||||
<BaseChart
|
||||
icon={null}
|
||||
title={title}
|
||||
>
|
||||
<ResponsiveContainer
|
||||
width="100%"
|
||||
height={200}
|
||||
>
|
||||
<AreaChart data={type === "temp" ? avgTemps : data}>
|
||||
<XAxis
|
||||
dataKey={xKey}
|
||||
tick={(props) => (
|
||||
<XTick
|
||||
{...props}
|
||||
range={dateRange}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<YAxis
|
||||
domain={type === "temp" ? tempYDomain : yDomain}
|
||||
tickFormatter={yAxisFormatter}
|
||||
/>
|
||||
|
||||
<CartesianGrid
|
||||
stroke={theme.palette.divider}
|
||||
strokeWidth={1}
|
||||
strokeOpacity={1}
|
||||
fill="transparent"
|
||||
vertical={false}
|
||||
/>
|
||||
{dataKeys?.map((dataKey, index) => {
|
||||
const gradientId = `gradient-${uniqueId}-${index}`;
|
||||
return (
|
||||
<Fragment key={`${dataKey}-${index}`}>
|
||||
{gradient === true &&
|
||||
createGradient({
|
||||
id: gradientId,
|
||||
startColor: gradientStartColor || AREA_COLORS[index],
|
||||
endColor: gradientEndColor || "transparent",
|
||||
direction: gradientDirection,
|
||||
})}
|
||||
<Area
|
||||
key={dataKey}
|
||||
type="monotone"
|
||||
dataKey={dataKey}
|
||||
stroke={strokeColor || AREA_COLORS[index]}
|
||||
fill={gradient === true ? `url(#${gradientId})` : fillColor}
|
||||
/>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</BaseChart>
|
||||
);
|
||||
};
|
||||
@@ -8,8 +8,9 @@ import type { TooltipProps } from "recharts";
|
||||
import { useSelector } from "react-redux";
|
||||
import type { RootState } from "@/Types/state";
|
||||
|
||||
interface HistogramPageSpeedScoresTooltipProps
|
||||
extends Partial<TooltipProps<number, string>> {
|
||||
interface HistogramPageSpeedScoresTooltipProps extends Partial<
|
||||
TooltipProps<number, string>
|
||||
> {
|
||||
config: Record<string, ConfigItem>;
|
||||
}
|
||||
export const HistogramPageSpeedScoresTooltip = ({
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export * from "./ControlsFilter";
|
||||
export * from "./MonitorStatBoxes";
|
||||
export * from "./HeaderMonitorControls";
|
||||
export * from "./charts/HistogramStatus";
|
||||
export * from "./charts/RadialAvgResponse";
|
||||
export * from "./charts/HistogramDetails";
|
||||
@@ -9,3 +10,4 @@ export * from "./charts/PiePageSpeed";
|
||||
export * from "./charts/PiePageSpeedLegend";
|
||||
export * from "./charts/HistogramPageSpeedDetails";
|
||||
export * from "./charts/HistogramPageSpeedDetailsTooltip";
|
||||
export * from "./charts/HistogramInfrastructure";
|
||||
@@ -196,6 +196,16 @@ const authSlice = createSlice({
|
||||
state.success = true;
|
||||
state.msg = "Logged out successfully";
|
||||
},
|
||||
setAuthState: (state, action) => {
|
||||
state.isLoading = false;
|
||||
state.success = action.payload.success;
|
||||
state.msg = action.payload.msg;
|
||||
state.authToken = action.payload.data.token;
|
||||
state.user = action.payload.data.user;
|
||||
},
|
||||
setUser: (state, action) => {
|
||||
state.user = action.payload;
|
||||
},
|
||||
},
|
||||
extraReducers: (builder) => {
|
||||
// Register thunk
|
||||
@@ -249,4 +259,4 @@ const authSlice = createSlice({
|
||||
});
|
||||
|
||||
export default authSlice.reducer;
|
||||
export const { clearAuthState } = authSlice.actions;
|
||||
export const { clearAuthState, setAuthState, setUser } = authSlice.actions;
|
||||
@@ -19,6 +19,9 @@ const initialState = {
|
||||
infrastructure: {
|
||||
rowsPerPage: 5,
|
||||
},
|
||||
logs: {
|
||||
rowsPerPage: 15,
|
||||
},
|
||||
sidebar: {
|
||||
collapsed: false,
|
||||
},
|
||||
@@ -41,9 +44,10 @@ const uiSlice = createSlice({
|
||||
},
|
||||
setRowsPerPage: (state, action) => {
|
||||
const { table, value } = action.payload;
|
||||
if (state[table]) {
|
||||
state[table].rowsPerPage = value;
|
||||
if (!state[table]) {
|
||||
state[table] = {};
|
||||
}
|
||||
state[table].rowsPerPage = value;
|
||||
},
|
||||
toggleSidebar: (state) => {
|
||||
state.sidebar.collapsed = !state.sidebar.collapsed;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import useSWR from "swr";
|
||||
import type { SWRConfiguration } from "swr";
|
||||
import type { AxiosRequestConfig } from "axios";
|
||||
import { get, patch, post, deleteOp } from "@/Utils/ApiClient";
|
||||
import { get, patch, post, put, deleteOp } from "@/Utils/ApiClient";
|
||||
import { useState } from "react";
|
||||
import { useToast } from "@/Hooks/UseToast";
|
||||
|
||||
@@ -21,7 +21,7 @@ export const useGet = <T>(
|
||||
axiosConfig?: AxiosRequestConfig,
|
||||
swrConfig?: SWRConfiguration
|
||||
) => {
|
||||
const { data, error, isLoading, mutate } = useSWR<ApiResponse<T>>(
|
||||
const { data, error, isLoading, isValidating, mutate } = useSWR<ApiResponse<T>>(
|
||||
url,
|
||||
(url: string) => fetcher<T>(url, axiosConfig),
|
||||
swrConfig
|
||||
@@ -30,6 +30,7 @@ export const useGet = <T>(
|
||||
return {
|
||||
data: data?.data ?? null,
|
||||
isLoading,
|
||||
isValidating,
|
||||
error,
|
||||
refetch: mutate,
|
||||
};
|
||||
@@ -108,6 +109,42 @@ export const usePatch = <B = any, R = any>() => {
|
||||
return { patch: patchFn, loading, error };
|
||||
};
|
||||
|
||||
export const usePut = <B = any, R = any>() => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { toastError, toastSuccess } = useToast();
|
||||
|
||||
const putFn = async (
|
||||
endpoint: string,
|
||||
body?: B,
|
||||
config?: AxiosRequestConfig
|
||||
): Promise<ApiResponse<R> | null> => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const res = await put<ApiResponse<R>>(endpoint, body, {
|
||||
...config,
|
||||
headers: {
|
||||
...config?.headers,
|
||||
},
|
||||
});
|
||||
toastSuccess(res.data?.msg || "Operation successful");
|
||||
return res.data;
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
const errMsg = err?.response?.data?.msg || err.message || "An error occurred";
|
||||
toastError(errMsg);
|
||||
setError(errMsg);
|
||||
return null;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return { put: putFn, loading, error };
|
||||
};
|
||||
|
||||
export const useDelete = <R = any>() => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -1,107 +1,8 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { networkService } from "../main.jsx";
|
||||
import { createToast } from "../Utils/toastUtils.jsx";
|
||||
import { useTheme } from "@emotion/react";
|
||||
import { useMonitorUtils } from "./useMonitorUtils.js";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export const useFetchMonitorsWithSummary = ({ types, monitorUpdateTrigger }) => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [monitors, setMonitors] = useState(undefined);
|
||||
const [monitorsSummary, setMonitorsSummary] = useState(undefined);
|
||||
const [networkError, setNetworkError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchMonitors = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await networkService.getMonitorsWithSummaryByTeamId({
|
||||
types,
|
||||
});
|
||||
const { monitors, summary } = res?.data?.data ?? {};
|
||||
setMonitors(monitors);
|
||||
setMonitorsSummary(summary);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
setNetworkError(true);
|
||||
createToast({
|
||||
body: error.message,
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchMonitors();
|
||||
}, [types, monitorUpdateTrigger]);
|
||||
return [monitors, monitorsSummary, isLoading, networkError];
|
||||
};
|
||||
|
||||
export const useFetchMonitorsWithChecks = ({
|
||||
types,
|
||||
limit,
|
||||
page,
|
||||
rowsPerPage,
|
||||
filter,
|
||||
field,
|
||||
order,
|
||||
monitorUpdateTrigger,
|
||||
}) => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [count, setCount] = useState(undefined);
|
||||
const [monitors, setMonitors] = useState(undefined);
|
||||
const [summary, setSummary] = useState(undefined);
|
||||
const [networkError, setNetworkError] = useState(false);
|
||||
|
||||
const theme = useTheme();
|
||||
const { getMonitorWithPercentage } = useMonitorUtils();
|
||||
useEffect(() => {
|
||||
const fetchMonitors = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await networkService.getMonitorsWithChecksByTeamId({
|
||||
limit,
|
||||
types,
|
||||
page,
|
||||
rowsPerPage,
|
||||
filter,
|
||||
field,
|
||||
order,
|
||||
});
|
||||
|
||||
const { count, monitors, summary } = res?.data?.data ?? {};
|
||||
const mappedMonitors = monitors.map((monitor) =>
|
||||
getMonitorWithPercentage(monitor, theme)
|
||||
);
|
||||
setSummary(summary);
|
||||
setMonitors(mappedMonitors);
|
||||
setCount(count || 0);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
setNetworkError(true);
|
||||
createToast({
|
||||
body: error.message,
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchMonitors();
|
||||
}, [
|
||||
field,
|
||||
filter,
|
||||
getMonitorWithPercentage,
|
||||
limit,
|
||||
order,
|
||||
page,
|
||||
rowsPerPage,
|
||||
theme,
|
||||
types,
|
||||
monitorUpdateTrigger,
|
||||
]);
|
||||
return [summary, monitors, count, isLoading, networkError];
|
||||
};
|
||||
|
||||
export const useFetchMonitorsByTeamId = ({ types, filter, updateTrigger }) => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [monitors, setMonitors] = useState(undefined);
|
||||
@@ -132,225 +33,17 @@ export const useFetchMonitorsByTeamId = ({ types, filter, updateTrigger }) => {
|
||||
return [monitors, isLoading, networkError];
|
||||
};
|
||||
|
||||
export const useFetchStatsByMonitorId = ({
|
||||
monitorId,
|
||||
sortOrder,
|
||||
limit,
|
||||
dateRange,
|
||||
numToDisplay,
|
||||
normalize,
|
||||
updateTrigger,
|
||||
}) => {
|
||||
const [monitor, setMonitor] = useState(undefined);
|
||||
const [audits, setAudits] = useState(undefined);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [networkError, setNetworkError] = useState(false);
|
||||
useEffect(() => {
|
||||
const fetchMonitor = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await networkService.getStatsByMonitorId({
|
||||
monitorId: monitorId,
|
||||
sortOrder,
|
||||
limit,
|
||||
dateRange,
|
||||
numToDisplay,
|
||||
normalize,
|
||||
});
|
||||
setMonitor(res?.data?.data ?? undefined);
|
||||
setAudits(res?.data?.data?.checks?.[0]?.audits ?? undefined);
|
||||
} catch (error) {
|
||||
setNetworkError(true);
|
||||
createToast({ body: error.message });
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchMonitor();
|
||||
}, [monitorId, dateRange, numToDisplay, normalize, sortOrder, limit, updateTrigger]);
|
||||
return [monitor, audits, isLoading, networkError];
|
||||
};
|
||||
|
||||
export const useFetchMonitorGames = ({ setGames, updateTrigger }) => {
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
useEffect(() => {
|
||||
const fetchGames = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await networkService.getMonitorGames();
|
||||
setGames(res.data.data);
|
||||
} catch (error) {
|
||||
createToast({ body: error.message });
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchGames();
|
||||
}, [setGames, updateTrigger]);
|
||||
return [isLoading];
|
||||
};
|
||||
|
||||
export const useFetchMonitorById = ({ monitorId, setMonitor, updateTrigger }) => {
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
useEffect(() => {
|
||||
if (typeof monitorId === "undefined") {
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
const fetchMonitor = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await networkService.getMonitorById({ monitorId: monitorId });
|
||||
setMonitor(res.data.data);
|
||||
} catch (error) {
|
||||
createToast({ body: error.message });
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchMonitor();
|
||||
}, [monitorId, setMonitor, updateTrigger]);
|
||||
return [isLoading];
|
||||
};
|
||||
|
||||
export const useFetchHardwareMonitorById = ({ monitorId, dateRange, updateTrigger }) => {
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [networkError, setNetworkError] = useState(false);
|
||||
const [monitor, setMonitor] = useState(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchMonitor = async () => {
|
||||
try {
|
||||
if (!monitorId) {
|
||||
return { monitor: undefined, isLoading: false, networkError: undefined };
|
||||
}
|
||||
const response = await networkService.getHardwareDetailsByMonitorId({
|
||||
monitorId: monitorId,
|
||||
dateRange: dateRange,
|
||||
});
|
||||
setMonitor(response.data.data);
|
||||
} catch (error) {
|
||||
setNetworkError(true);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchMonitor();
|
||||
}, [monitorId, dateRange, updateTrigger]);
|
||||
return [monitor, isLoading, networkError];
|
||||
};
|
||||
export const useFetchPageSpeedMonitorById = ({ monitorId, dateRange, updateTrigger }) => {
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [networkError, setNetworkError] = useState(false);
|
||||
const [monitor, setMonitor] = useState(undefined);
|
||||
const [monitorStats, setMonitorStats] = useState(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchMonitor = async () => {
|
||||
try {
|
||||
if (!monitorId) {
|
||||
return { monitor: undefined, isLoading: false, networkError: undefined };
|
||||
}
|
||||
const response = await networkService.getPageSpeedDetailsByMonitorId({
|
||||
monitorId: monitorId,
|
||||
dateRange: dateRange,
|
||||
});
|
||||
setMonitor(response.data.data.monitor);
|
||||
setMonitorStats(response.data.data.monitorStats);
|
||||
} catch (error) {
|
||||
setNetworkError(true);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchMonitor();
|
||||
}, [monitorId, dateRange, updateTrigger]);
|
||||
return [monitor, monitorStats, isLoading, networkError];
|
||||
};
|
||||
|
||||
export const useFetchUptimeMonitorById = ({ monitorId, dateRange, trigger }) => {
|
||||
const [networkError, setNetworkError] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [monitor, setMonitor] = useState(undefined);
|
||||
const [monitorStats, setMonitorStats] = useState(undefined);
|
||||
useEffect(() => {
|
||||
const fetchMonitors = async () => {
|
||||
try {
|
||||
const res = await networkService.getUptimeDetailsById({
|
||||
monitorId: monitorId,
|
||||
dateRange: dateRange,
|
||||
normalize: true,
|
||||
});
|
||||
const { monitorData, monitorStats } = res?.data?.data ?? {};
|
||||
setMonitor(monitorData);
|
||||
setMonitorStats(monitorStats);
|
||||
} catch (error) {
|
||||
setNetworkError(true);
|
||||
createToast({ body: error.message });
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchMonitors();
|
||||
}, [dateRange, monitorId, trigger]);
|
||||
return [monitor, monitorStats, isLoading, networkError];
|
||||
};
|
||||
|
||||
export const useCreateMonitor = () => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const createMonitor = async ({ monitor, redirect }) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
await networkService.createMonitor({ monitor });
|
||||
createToast({ body: "Monitor created successfully!" });
|
||||
if (redirect) {
|
||||
navigate(redirect);
|
||||
}
|
||||
} catch (error) {
|
||||
createToast({ body: "Failed to create monitor." });
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
return [createMonitor, isLoading];
|
||||
};
|
||||
|
||||
export const useFetchGlobalSettings = () => {
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [globalSettings, setGlobalSettings] = useState(undefined);
|
||||
useEffect(() => {
|
||||
const fetchGlobalSettings = async () => {
|
||||
try {
|
||||
const res = await networkService.getAppSettings();
|
||||
setGlobalSettings(res?.data);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch global settings:", error);
|
||||
createToast({ body: "Failed to load global settings" });
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchGlobalSettings();
|
||||
}, []);
|
||||
|
||||
return [globalSettings, isLoading];
|
||||
};
|
||||
|
||||
export const useDeleteMonitor = () => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const deleteMonitor = async ({ monitor, redirect }) => {
|
||||
const { t } = useTranslation();
|
||||
const deleteMonitor = async (monitorId, successCallback = () => {}) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
await networkService.deleteMonitorById({ monitorId: monitor.id });
|
||||
createToast({ body: "Monitor deleted successfully!" });
|
||||
if (redirect) {
|
||||
navigate(redirect);
|
||||
}
|
||||
await networkService.deleteMonitorById({ monitorId });
|
||||
successCallback();
|
||||
createToast({ body: t("monitorDeleted") });
|
||||
} catch (error) {
|
||||
createToast({ body: "Failed to delete monitor." });
|
||||
createToast({ body: t("failedDeleteMonitor") });
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -358,68 +51,24 @@ export const useDeleteMonitor = () => {
|
||||
return [deleteMonitor, isLoading];
|
||||
};
|
||||
|
||||
export const useUpdateMonitor = () => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const updateMonitor = async ({ monitor, redirect }) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const updatedFields = {
|
||||
name: monitor.name,
|
||||
statusWindowSize: monitor.statusWindowSize,
|
||||
statusWindowThreshold: monitor.statusWindowThreshold,
|
||||
description: monitor.description,
|
||||
interval: monitor.interval,
|
||||
notifications: monitor.notifications,
|
||||
matchMethod: monitor.matchMethod,
|
||||
expectedValue: monitor.expectedValue,
|
||||
ignoreTlsErrors: monitor.ignoreTlsErrors,
|
||||
jsonPath: monitor.jsonPath,
|
||||
...((monitor.type === "port" || monitor.type === "game") && {
|
||||
port: monitor.port,
|
||||
}),
|
||||
...(monitor.type == "game" && {
|
||||
gameId: monitor.gameId,
|
||||
}),
|
||||
...(monitor.type === "hardware" && {
|
||||
thresholds: monitor.thresholds,
|
||||
secret: monitor.secret,
|
||||
selectedDisks: monitor.selectedDisks,
|
||||
}),
|
||||
};
|
||||
await networkService.updateMonitor({
|
||||
monitorId: monitor.id,
|
||||
updatedFields,
|
||||
});
|
||||
|
||||
createToast({ body: "Monitor updated successfully!" });
|
||||
if (redirect) {
|
||||
navigate(redirect);
|
||||
}
|
||||
} catch (error) {
|
||||
createToast({ body: "Failed to update monitor." });
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
return [updateMonitor, isLoading];
|
||||
};
|
||||
|
||||
export const usePauseMonitor = () => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState(undefined);
|
||||
const pauseMonitor = async ({ monitorId, triggerUpdate }) => {
|
||||
const [error, setError] = useState(null);
|
||||
const { t } = useTranslation();
|
||||
|
||||
const pauseMonitor = async (monitorId, successCallback = () => {}) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await networkService.pauseMonitorById({ monitorId });
|
||||
createToast({
|
||||
body: res.data.data.isActive
|
||||
? "Monitor resumed successfully"
|
||||
: "Monitor paused successfully",
|
||||
});
|
||||
triggerUpdate();
|
||||
successCallback();
|
||||
if (res.data.data.isActive === false) {
|
||||
createToast({ body: t("monitorPaused") });
|
||||
} else {
|
||||
createToast({ body: t("monitorResumed") });
|
||||
}
|
||||
} catch (error) {
|
||||
setError(error);
|
||||
setError(error.message);
|
||||
createToast({ body: t("failedPauseMonitor") });
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -491,7 +140,7 @@ export const useCreateBulkMonitors = () => {
|
||||
|
||||
try {
|
||||
const response = await networkService.createBulkMonitors(formData);
|
||||
return [true, response.data, null]; // [success, data, error]
|
||||
return [true, response.data, null];
|
||||
} catch (err) {
|
||||
const errorMessage = err?.response?.data?.msg || err.message;
|
||||
return [false, null, errorMessage];
|
||||
@@ -503,39 +152,6 @@ export const useCreateBulkMonitors = () => {
|
||||
return [createBulkMonitors, isLoading];
|
||||
};
|
||||
|
||||
export const useExportMonitors = () => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const { t } = useTranslation();
|
||||
|
||||
const exportMonitors = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = await networkService.exportMonitors();
|
||||
|
||||
// Create a download link
|
||||
const url = window.URL.createObjectURL(response.data);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.setAttribute("download", "monitors.csv");
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
window.URL.revokeObjectURL(url);
|
||||
|
||||
createToast({ body: t("export.success") });
|
||||
return [true, null];
|
||||
} catch (err) {
|
||||
const errorMessage = err?.response?.data?.msg || err.message;
|
||||
createToast({ body: errorMessage || t("export.failed") });
|
||||
return [false, errorMessage];
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return [exportMonitors, isLoading];
|
||||
};
|
||||
|
||||
export const useFetchJson = () => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const fetchJson = async () => {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import {
|
||||
addTeamMemberSchema,
|
||||
type AddTeamMemberFormData,
|
||||
} from "@/Validation/addTeamMember";
|
||||
|
||||
export const useAddTeamMemberForm = () => {
|
||||
const defaults: AddTeamMemberFormData = {
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
email: "",
|
||||
password: "",
|
||||
confirm: "",
|
||||
role: ["user"],
|
||||
};
|
||||
|
||||
return {
|
||||
schema: addTeamMemberSchema,
|
||||
defaults,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { inviteSchema, type InviteFormData } from "@/Validation/invite";
|
||||
|
||||
export const useInviteForm = () => {
|
||||
const defaults: InviteFormData = {
|
||||
email: "",
|
||||
role: ["user"],
|
||||
};
|
||||
|
||||
return {
|
||||
resolver: zodResolver(inviteSchema),
|
||||
defaults,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
import { useMemo } from "react";
|
||||
import { loginSchema, type LoginFormData } from "@/Validation/login";
|
||||
|
||||
export const useLoginForm = () => {
|
||||
return useMemo(() => {
|
||||
const defaults: LoginFormData = {
|
||||
email: "",
|
||||
password: "",
|
||||
};
|
||||
|
||||
return { schema: loginSchema, defaults };
|
||||
}, []);
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useMemo } from "react";
|
||||
import dayjs from "dayjs";
|
||||
import {
|
||||
maintenanceWindowSchema,
|
||||
repeatOptions,
|
||||
type MaintenanceWindowFormData,
|
||||
} from "@/Validation/maintenanceWindow";
|
||||
import type { MaintenanceWindow } from "@/Types/MaintenanceWindow";
|
||||
|
||||
interface UseMaintenanceWindowFormOptions {
|
||||
data?: MaintenanceWindow | null;
|
||||
}
|
||||
|
||||
const getRepeatId = (repeatMs: number): string => {
|
||||
const option = repeatOptions.find((opt) => opt.value === repeatMs);
|
||||
return option?.id ?? "none";
|
||||
};
|
||||
|
||||
export const useMaintenanceWindowForm = ({
|
||||
data = null,
|
||||
}: UseMaintenanceWindowFormOptions = {}) => {
|
||||
return useMemo(() => {
|
||||
let defaults: MaintenanceWindowFormData;
|
||||
|
||||
if (data) {
|
||||
const startDate = dayjs(data.start);
|
||||
|
||||
defaults = {
|
||||
name: data.name,
|
||||
repeat: getRepeatId(data.repeat),
|
||||
startDate: startDate.format("YYYY-MM-DD"),
|
||||
startTime: startDate.format("HH:mm"),
|
||||
duration: data.duration ?? 0,
|
||||
durationUnit: data.durationUnit ?? "minutes",
|
||||
monitors: [data.monitorId],
|
||||
};
|
||||
} else {
|
||||
const now = dayjs();
|
||||
defaults = {
|
||||
name: "",
|
||||
repeat: "none",
|
||||
startDate: now.format("YYYY-MM-DD"),
|
||||
startTime: now.format("HH:mm"),
|
||||
duration: 0,
|
||||
durationUnit: "minutes",
|
||||
monitors: [],
|
||||
};
|
||||
}
|
||||
|
||||
return { schema: maintenanceWindowSchema, defaults };
|
||||
}, [data]);
|
||||
};
|
||||
@@ -0,0 +1,108 @@
|
||||
import { useMemo } from "react";
|
||||
import { monitorSchema, type MonitorFormData } from "@/Validation/monitor";
|
||||
import type { Monitor, MonitorType } from "@/Types/Monitor";
|
||||
|
||||
interface UseMonitorFormOptions {
|
||||
data?: Monitor | null;
|
||||
defaultType?: MonitorType;
|
||||
}
|
||||
|
||||
const getBaseDefaults = (data?: Monitor | null) => ({
|
||||
name: data?.name || "",
|
||||
description: data?.description || "",
|
||||
interval: data?.interval || 60000,
|
||||
notifications: data?.notifications || [],
|
||||
statusWindowSize: data?.statusWindowSize || 5,
|
||||
statusWindowThreshold: data?.statusWindowThreshold || 60,
|
||||
});
|
||||
|
||||
export const useMonitorForm = ({
|
||||
data = null,
|
||||
defaultType = "http",
|
||||
}: UseMonitorFormOptions = {}) => {
|
||||
return useMemo(() => {
|
||||
const type = data?.type || defaultType;
|
||||
const base = getBaseDefaults(data);
|
||||
|
||||
let defaults: MonitorFormData;
|
||||
|
||||
switch (type) {
|
||||
case "http":
|
||||
defaults = {
|
||||
...base,
|
||||
type: "http",
|
||||
url: data?.url || "",
|
||||
ignoreTlsErrors: data?.ignoreTlsErrors || false,
|
||||
useAdvancedMatching: data?.useAdvancedMatching || false,
|
||||
matchMethod: data?.matchMethod || "",
|
||||
expectedValue: data?.expectedValue || "",
|
||||
jsonPath: data?.jsonPath || "",
|
||||
};
|
||||
break;
|
||||
case "ping":
|
||||
defaults = {
|
||||
...base,
|
||||
type: "ping",
|
||||
url: data?.url || "",
|
||||
};
|
||||
break;
|
||||
case "port":
|
||||
defaults = {
|
||||
...base,
|
||||
type: "port",
|
||||
url: data?.url || "",
|
||||
port: data?.port || 80,
|
||||
};
|
||||
break;
|
||||
case "docker":
|
||||
defaults = {
|
||||
...base,
|
||||
type: "docker",
|
||||
url: data?.url || "",
|
||||
};
|
||||
break;
|
||||
case "game":
|
||||
defaults = {
|
||||
...base,
|
||||
type: "game",
|
||||
url: data?.url || "",
|
||||
port: data?.port || 27015,
|
||||
gameId: data?.gameId || "",
|
||||
};
|
||||
break;
|
||||
case "pagespeed":
|
||||
defaults = {
|
||||
...base,
|
||||
type: "pagespeed",
|
||||
url: data?.url || "",
|
||||
};
|
||||
break;
|
||||
case "hardware":
|
||||
defaults = {
|
||||
...base,
|
||||
type: "hardware",
|
||||
url: data?.url || "",
|
||||
secret: data?.secret || "",
|
||||
cpuAlertThreshold: data?.cpuAlertThreshold ?? 80,
|
||||
memoryAlertThreshold: data?.memoryAlertThreshold ?? 80,
|
||||
diskAlertThreshold: data?.diskAlertThreshold ?? 80,
|
||||
tempAlertThreshold: data?.tempAlertThreshold ?? 80,
|
||||
selectedDisks: data?.selectedDisks || [],
|
||||
};
|
||||
break;
|
||||
default:
|
||||
defaults = {
|
||||
...base,
|
||||
type: "http",
|
||||
url: "",
|
||||
ignoreTlsErrors: false,
|
||||
useAdvancedMatching: false,
|
||||
matchMethod: "",
|
||||
expectedValue: "",
|
||||
jsonPath: "",
|
||||
};
|
||||
}
|
||||
|
||||
return { schema: monitorSchema, defaults };
|
||||
}, [data, defaultType]);
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useMemo } from "react";
|
||||
import { notificationSchema } from "@/Validation/notifications";
|
||||
import type { Notification } from "@/Types/Notification";
|
||||
|
||||
interface UseNotificationFormOptions {
|
||||
data?: Notification | null;
|
||||
}
|
||||
|
||||
export const useNotificationForm = ({ data = null }: UseNotificationFormOptions = {}) => {
|
||||
return useMemo(() => {
|
||||
const defaults =
|
||||
data?.type === "matrix"
|
||||
? {
|
||||
type: "matrix" as const,
|
||||
notificationName: data.notificationName || "",
|
||||
homeserverUrl: data.homeserverUrl || "",
|
||||
roomId: data.roomId || "",
|
||||
accessToken: data.accessToken || "",
|
||||
}
|
||||
: {
|
||||
type: (data?.type || "email") as Exclude<Notification["type"], "matrix">,
|
||||
notificationName: data?.notificationName || "",
|
||||
address: data?.address || "",
|
||||
};
|
||||
|
||||
return { schema: notificationSchema, defaults };
|
||||
}, [data]);
|
||||
};
|
||||
@@ -1,36 +1,7 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { createToast } from "../Utils/toastUtils.jsx";
|
||||
import { networkService } from "../main.jsx";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { NOTIFICATION_TYPES } from "../Pages/Notifications/utils.js";
|
||||
|
||||
const useCreateNotification = () => {
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const createNotification = async (notification) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
await networkService.createNotification({ notification });
|
||||
createToast({
|
||||
body: t("notifications.create.success"),
|
||||
});
|
||||
navigate("/notifications");
|
||||
} catch (error) {
|
||||
setError(error);
|
||||
createToast({
|
||||
body: t("notifications.create.failed"),
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return [createNotification, isLoading, error];
|
||||
};
|
||||
|
||||
const useGetNotificationsByTeamId = (updateTrigger) => {
|
||||
const [notifications, setNotifications] = useState([]);
|
||||
@@ -60,119 +31,6 @@ const useGetNotificationsByTeamId = (updateTrigger) => {
|
||||
return [notifications, isLoading, error];
|
||||
};
|
||||
|
||||
const useDeleteNotification = () => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
const { t } = useTranslation();
|
||||
|
||||
const deleteNotification = async (id, callback) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
await networkService.deleteNotificationById({ id });
|
||||
createToast({
|
||||
body: t("notifications.delete.success"),
|
||||
});
|
||||
if (callback) {
|
||||
callback();
|
||||
}
|
||||
} catch (error) {
|
||||
setError(error);
|
||||
createToast({
|
||||
body: t("notifications.delete.failed"),
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return [deleteNotification, isLoading, error];
|
||||
};
|
||||
|
||||
const useGetNotificationById = (id, setNotification) => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const getNotificationById = useCallback(async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const response = await networkService.getNotificationById({ id });
|
||||
|
||||
const notification = response?.data?.data ?? null;
|
||||
|
||||
const notificationData = {
|
||||
address: notification?.address,
|
||||
notificationName: notification?.notificationName,
|
||||
type: NOTIFICATION_TYPES.find((type) => type.value === notification?.type)?.id,
|
||||
};
|
||||
|
||||
setNotification(notificationData);
|
||||
} catch (error) {
|
||||
setError(error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [id, setNotification]);
|
||||
|
||||
useEffect(() => {
|
||||
if (id) {
|
||||
getNotificationById();
|
||||
}
|
||||
}, [getNotificationById, id]);
|
||||
|
||||
return [isLoading, error];
|
||||
};
|
||||
|
||||
const useEditNotification = () => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const editNotification = async (id, notification) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
await networkService.editNotification({ id, notification });
|
||||
createToast({
|
||||
body: t("notifications.edit.success"),
|
||||
});
|
||||
navigate(`/notifications`);
|
||||
} catch (error) {
|
||||
setError(error);
|
||||
createToast({
|
||||
body: t("notifications.edit.failed"),
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return [editNotification, isLoading, error];
|
||||
};
|
||||
|
||||
const useTestNotification = () => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
const { t } = useTranslation();
|
||||
|
||||
const testNotification = async (notification) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
await networkService.testNotification({ notification });
|
||||
createToast({
|
||||
body: t("notifications.test.success"),
|
||||
});
|
||||
} catch (error) {
|
||||
setError(error);
|
||||
createToast({
|
||||
body: error?.response?.data?.msg || t("notifications.test.failed"),
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return [testNotification, isLoading, error];
|
||||
};
|
||||
|
||||
const useTestAllNotifications = () => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState(undefined);
|
||||
@@ -197,12 +55,4 @@ const useTestAllNotifications = () => {
|
||||
return [testAllNotifications, isLoading, error];
|
||||
};
|
||||
|
||||
export {
|
||||
useCreateNotification,
|
||||
useGetNotificationsByTeamId,
|
||||
useDeleteNotification,
|
||||
useGetNotificationById,
|
||||
useEditNotification,
|
||||
useTestNotification,
|
||||
useTestAllNotifications,
|
||||
};
|
||||
export { useGetNotificationsByTeamId, useTestAllNotifications };
|
||||
@@ -0,0 +1,13 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { passwordSchema, type PasswordFormData } from "@/Validation/password";
|
||||
|
||||
export const usePasswordForm = () => {
|
||||
return {
|
||||
resolver: zodResolver(passwordSchema),
|
||||
defaults: {
|
||||
currentPassword: "",
|
||||
newPassword: "",
|
||||
confirm: "",
|
||||
} as PasswordFormData,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { profileSchema, type ProfileFormData } from "@/Validation/profile";
|
||||
|
||||
export const useProfileForm = () => {
|
||||
return {
|
||||
resolver: zodResolver(profileSchema),
|
||||
defaults: {
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
profileImage: null,
|
||||
deleteProfileImage: false,
|
||||
} as ProfileFormData,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import { recoverySchema } from "@/Validation/recovery";
|
||||
|
||||
export const useRecoveryForm = () => {
|
||||
const defaults = {
|
||||
email: "",
|
||||
};
|
||||
|
||||
return {
|
||||
schema: recoverySchema,
|
||||
defaults,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
import { registerSchema, type RegisterFormData } from "@/Validation/register";
|
||||
|
||||
export const useRegisterForm = () => {
|
||||
const defaults: RegisterFormData = {
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
email: "",
|
||||
password: "",
|
||||
confirm: "",
|
||||
};
|
||||
|
||||
return {
|
||||
schema: registerSchema,
|
||||
defaults,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useMemo } from "react";
|
||||
import { statusPageSchema, type StatusPageFormData } from "@/Validation/statusPage";
|
||||
import type { StatusPage } from "@/Types/StatusPage";
|
||||
import type { Monitor } from "@/Types/Monitor";
|
||||
|
||||
interface UseStatusPageFormOptions {
|
||||
data?: StatusPage | null;
|
||||
monitors?: Monitor[] | null;
|
||||
}
|
||||
|
||||
const generateDefaultUrl = () => Math.floor(Math.random() * 1000000).toString();
|
||||
|
||||
const transformLogo = (logo: StatusPage["logo"]): StatusPageFormData["logo"] => {
|
||||
if (!logo || !logo.data) return null;
|
||||
return {
|
||||
data: `data:${logo.contentType};base64,${logo.data}`,
|
||||
contentType: logo.contentType,
|
||||
};
|
||||
};
|
||||
|
||||
export const useStatusPageForm = ({
|
||||
data = null,
|
||||
monitors = null,
|
||||
}: UseStatusPageFormOptions = {}) => {
|
||||
return useMemo(() => {
|
||||
const defaults: StatusPageFormData = {
|
||||
companyName: data?.companyName || "",
|
||||
url: data?.url || generateDefaultUrl(),
|
||||
timezone: data?.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
color: data?.color || "#4169E1",
|
||||
monitors: data?.monitors || [],
|
||||
isPublished: data?.isPublished ?? false,
|
||||
showCharts: data?.showCharts ?? true,
|
||||
showUptimePercentage: data?.showUptimePercentage ?? true,
|
||||
showAdminLoginLink: data?.showAdminLoginLink ?? false,
|
||||
customCSS: data?.customCSS || "",
|
||||
logo: transformLogo(data?.logo),
|
||||
};
|
||||
|
||||
return { schema: statusPageSchema, defaults };
|
||||
}, [data, monitors]);
|
||||
};
|
||||
@@ -1,18 +0,0 @@
|
||||
import React from "react";
|
||||
import AppBar from "@/Components/v1/Common/AppBar.jsx";
|
||||
import Footer from "@/Components/v1/Common/Footer.jsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
const AboutUs = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<AppBar />
|
||||
<h1>{t("aboutus")}</h1>
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AboutUs;
|
||||
@@ -0,0 +1,116 @@
|
||||
import { Stack } from "@mui/material";
|
||||
import { ConfigBox } from "@/Components/v2/design-elements";
|
||||
import { TextField, Button } from "@/Components/v2/inputs";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useTheme } from "@mui/material";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import { usePasswordForm } from "@/Hooks/usePasswordForm";
|
||||
import { usePatch } from "@/Hooks/UseApi";
|
||||
import type { PasswordFormData } from "@/Validation/password";
|
||||
|
||||
export const TabPassword = () => {
|
||||
const { t } = useTranslation();
|
||||
const theme = useTheme();
|
||||
const { resolver, defaults } = usePasswordForm();
|
||||
const { patch, loading } = usePatch<FormData, void>();
|
||||
|
||||
const { control, handleSubmit, reset } = useForm<PasswordFormData>({
|
||||
resolver,
|
||||
defaultValues: defaults,
|
||||
});
|
||||
|
||||
const onSubmit = async (data: PasswordFormData) => {
|
||||
const fd = new FormData();
|
||||
fd.append("password", data.currentPassword);
|
||||
fd.append("newPassword", data.newPassword);
|
||||
|
||||
const result = await patch("/auth/user", fd);
|
||||
if (result?.success) {
|
||||
reset();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack
|
||||
gap={theme.spacing(8)}
|
||||
component="form"
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
>
|
||||
<ConfigBox
|
||||
title={t("pages.account.form.currentPassword.title")}
|
||||
subtitle={t("pages.account.form.currentPassword.description")}
|
||||
rightContent={
|
||||
<Controller
|
||||
name="currentPassword"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
type="password"
|
||||
fieldLabel={t("pages.account.form.currentPassword.option.label")}
|
||||
placeholder={t("pages.account.form.currentPassword.option.placeholder")}
|
||||
autoComplete="current-password"
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<ConfigBox
|
||||
title={t("pages.account.form.newPassword.title")}
|
||||
subtitle={t("pages.account.form.newPassword.description")}
|
||||
rightContent={
|
||||
<Stack gap={theme.spacing(8)}>
|
||||
<Controller
|
||||
name="newPassword"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
type="password"
|
||||
fieldLabel={t(
|
||||
"pages.account.form.newPassword.option.newPassword.label"
|
||||
)}
|
||||
placeholder={t(
|
||||
"pages.account.form.newPassword.option.newPassword.placeholder"
|
||||
)}
|
||||
autoComplete="new-password"
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="confirm"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
type="password"
|
||||
fieldLabel={t("pages.account.form.newPassword.option.confirm.label")}
|
||||
placeholder={t(
|
||||
"pages.account.form.newPassword.option.confirm.placeholder"
|
||||
)}
|
||||
autoComplete="new-password"
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Stack>
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="contained"
|
||||
color="primary"
|
||||
loading={loading}
|
||||
sx={{ alignSelf: "flex-end", minWidth: 100 }}
|
||||
>
|
||||
{t("common.buttons.save")}
|
||||
</Button>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,139 @@
|
||||
import { Stack } from "@mui/material";
|
||||
import { ConfigBox } from "@/Components/v2/design-elements";
|
||||
import { TextField, Button } from "@/Components/v2/inputs";
|
||||
import { ImageUpload } from "@/Components/v2/inputs";
|
||||
|
||||
import { useTheme } from "@mui/material";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import { useSelector, useDispatch } from "react-redux";
|
||||
import { useProfileForm } from "@/Hooks/useProfileForm";
|
||||
import { usePatch } from "@/Hooks/UseApi";
|
||||
import { setUser } from "@/Features/Auth/authSlice";
|
||||
import type { ProfileFormData } from "@/Validation/profile";
|
||||
import type { RootState } from "@/Types/state";
|
||||
import type { User } from "@/Types/User";
|
||||
|
||||
export const TabProfile = () => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const dispatch = useDispatch();
|
||||
const user = useSelector((state: RootState) => state.auth?.user);
|
||||
const { resolver, defaults } = useProfileForm();
|
||||
const { patch, loading: patchLoading } = usePatch<FormData, User>();
|
||||
|
||||
const { control, handleSubmit, setValue, watch } = useForm<ProfileFormData>({
|
||||
resolver,
|
||||
defaultValues: {
|
||||
firstName: user?.firstName ?? defaults.firstName,
|
||||
lastName: user?.lastName ?? defaults.lastName,
|
||||
profileImage: defaults.profileImage,
|
||||
deleteProfileImage: defaults.deleteProfileImage,
|
||||
},
|
||||
});
|
||||
|
||||
const currentImage = watch("profileImage");
|
||||
const deleteImage = watch("deleteProfileImage");
|
||||
|
||||
const getCurrentImageSrc = () => {
|
||||
if (deleteImage) return undefined;
|
||||
if (currentImage) return URL.createObjectURL(currentImage);
|
||||
if (user?.avatarImage) return `data:image/png;base64,${user.avatarImage}`;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const handleImageChange = (
|
||||
fileObj: { src: string; name: string; file: File } | undefined
|
||||
) => {
|
||||
if (fileObj) {
|
||||
setValue("profileImage", fileObj.file);
|
||||
setValue("deleteProfileImage", false);
|
||||
} else {
|
||||
setValue("profileImage", null);
|
||||
setValue("deleteProfileImage", true);
|
||||
}
|
||||
};
|
||||
|
||||
const onSubmit = async (data: ProfileFormData) => {
|
||||
const fd = new FormData();
|
||||
fd.append("firstName", data.firstName);
|
||||
fd.append("lastName", data.lastName);
|
||||
|
||||
if (data.profileImage) {
|
||||
fd.append("profileImage", data.profileImage);
|
||||
}
|
||||
|
||||
if (data.deleteProfileImage) {
|
||||
fd.append("deleteProfileImage", "true");
|
||||
}
|
||||
|
||||
const result = await patch("/auth/user", fd);
|
||||
if (result?.success && result.data) {
|
||||
dispatch(setUser(result.data));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack
|
||||
gap={theme.spacing(8)}
|
||||
component="form"
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
>
|
||||
<ConfigBox
|
||||
title={t("pages.account.form.name.title")}
|
||||
subtitle={t("pages.account.form.name.description")}
|
||||
rightContent={
|
||||
<Stack gap={theme.spacing(8)}>
|
||||
<Controller
|
||||
name="firstName"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
fieldLabel={t("pages.account.form.name.option.firstName.label")}
|
||||
placeholder={t("pages.account.form.name.option.firstName.placeholder")}
|
||||
autoComplete="given-name"
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="lastName"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
fieldLabel={t("pages.account.form.name.option.lastName.label")}
|
||||
placeholder={t("pages.account.form.name.option.lastName.placeholder")}
|
||||
autoComplete="family-name"
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Stack>
|
||||
}
|
||||
/>
|
||||
<ConfigBox
|
||||
title={t("pages.account.form.photo.title")}
|
||||
subtitle={t("pages.account.form.photo.description")}
|
||||
rightContent={
|
||||
<ImageUpload
|
||||
src={getCurrentImageSrc()}
|
||||
onChange={handleImageChange}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="contained"
|
||||
color="primary"
|
||||
loading={patchLoading}
|
||||
sx={{ alignSelf: "flex-end", minWidth: 100 }}
|
||||
>
|
||||
{t("common.buttons.save")}
|
||||
</Button>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Stack } from "@mui/material";
|
||||
import { useTheme } from "@mui/material";
|
||||
import { useState, useMemo } from "react";
|
||||
import { HeaderTeamControls } from "./components/HeaderTeamControls";
|
||||
import { TeamTable } from "./components/TeamTable";
|
||||
import { InviteTeamMemberDialog } from "./components/InviteTeamMemberDialog";
|
||||
import { AddTeamMemberDialog } from "./components/AddTeamMemberDialog";
|
||||
import { useGet } from "@/Hooks/UseApi";
|
||||
import type { User, UserRole } from "@/Types/User";
|
||||
|
||||
export const TabTeam = () => {
|
||||
const theme = useTheme();
|
||||
const [filter, setFilter] = useState<UserRole | "">("");
|
||||
const [inviteDialogOpen, setInviteDialogOpen] = useState(false);
|
||||
const [addMemberDialogOpen, setAddMemberDialogOpen] = useState(false);
|
||||
|
||||
const { data: users, refetch } = useGet<User[]>("/auth/users");
|
||||
|
||||
const filteredUsers = useMemo(() => {
|
||||
if (!users) return [];
|
||||
if (!filter) return users;
|
||||
|
||||
return users.filter((u) => u.role.includes(filter));
|
||||
}, [users, filter]);
|
||||
|
||||
const handleOpenInviteDialog = () => setInviteDialogOpen(true);
|
||||
const handleCloseInviteDialog = () => setInviteDialogOpen(false);
|
||||
|
||||
const handleOpenAddMemberDialog = () => setAddMemberDialogOpen(true);
|
||||
const handleCloseAddMemberDialog = () => setAddMemberDialogOpen(false);
|
||||
|
||||
const handleRefetch = () => {
|
||||
refetch();
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack gap={theme.spacing(8)}>
|
||||
<HeaderTeamControls
|
||||
filter={filter}
|
||||
onFilterChange={setFilter}
|
||||
onInviteClick={handleOpenInviteDialog}
|
||||
onAddMemberClick={handleOpenAddMemberDialog}
|
||||
/>
|
||||
<TeamTable users={filteredUsers} />
|
||||
<InviteTeamMemberDialog
|
||||
open={inviteDialogOpen}
|
||||
onClose={handleCloseInviteDialog}
|
||||
/>
|
||||
<AddTeamMemberDialog
|
||||
open={addMemberDialogOpen}
|
||||
onClose={handleCloseAddMemberDialog}
|
||||
onSuccess={handleRefetch}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -1,74 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import Button from "@mui/material/Button";
|
||||
import Menu from "@mui/material/Menu";
|
||||
import MenuItem from "@mui/material/MenuItem";
|
||||
import { useTheme } from "@emotion/react";
|
||||
import Icon from "@/Components/v1/Icon";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Proptypes from "prop-types";
|
||||
|
||||
const AddMemberMenu = ({ handleInviteOpen, handleIsRegisterOpen }) => {
|
||||
const [anchorEl, setAnchorEl] = useState(null);
|
||||
const open = Boolean(anchorEl);
|
||||
const { t } = useTranslation();
|
||||
const theme = useTheme();
|
||||
const handleClick = (event) => {
|
||||
setAnchorEl(event.currentTarget);
|
||||
};
|
||||
const handleClose = () => {
|
||||
setAnchorEl(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="accent"
|
||||
endIcon={
|
||||
<Icon
|
||||
name="ChevronDown"
|
||||
size={20}
|
||||
color="secondary.light"
|
||||
/>
|
||||
}
|
||||
onClick={handleClick}
|
||||
>
|
||||
{t("teamPanel.addTeamMember.addMemberMenu")}
|
||||
</Button>
|
||||
<Menu
|
||||
anchorEl={anchorEl}
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
sx={{
|
||||
"& .MuiPaper-root": {
|
||||
minWidth: anchorEl?.offsetWidth || "auto",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<MenuItem
|
||||
onClick={() => {
|
||||
handleClose();
|
||||
handleInviteOpen();
|
||||
}}
|
||||
>
|
||||
{t("teamPanel.inviteTeamMember")}
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
onClick={() => {
|
||||
handleClose();
|
||||
handleIsRegisterOpen(true);
|
||||
}}
|
||||
>
|
||||
{t("teamPanel.register")}
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
AddMemberMenu.propTypes = {
|
||||
handleInviteOpen: Proptypes.func.isRequired,
|
||||
handleIsRegisterOpen: Proptypes.func.isRequired,
|
||||
};
|
||||
|
||||
export default AddMemberMenu;
|
||||
@@ -1,48 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { newOrChangedCredentials } from "../../../../../Validation/validation.js";
|
||||
import { useTranslation } from "react-i18next";
|
||||
const useAddTeamMember = () => {
|
||||
const { t } = useTranslation();
|
||||
const [errors, setErrors] = useState({});
|
||||
|
||||
const clearErrors = () => setErrors({});
|
||||
|
||||
const validateFields = (name, value, formData) => {
|
||||
const { error } = newOrChangedCredentials.validate(
|
||||
{ [name]: value },
|
||||
{ abortEarly: false, context: { password: formData.password } }
|
||||
);
|
||||
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
[name]: error?.details?.[0]?.message || "",
|
||||
}));
|
||||
};
|
||||
|
||||
const validateForm = (formData, role) => {
|
||||
const { error } = newOrChangedCredentials.validate(formData, {
|
||||
abortEarly: false,
|
||||
context: { password: formData.password },
|
||||
});
|
||||
const formErrors = {};
|
||||
if (error) {
|
||||
for (const err of error.details) {
|
||||
formErrors[err.path[0]] = err.message;
|
||||
}
|
||||
}
|
||||
if (!role[0] || role.length === 0) {
|
||||
formErrors.role = t(
|
||||
"teamPanel.registerTeamMember.auth.common.inputs.role.errors.empty"
|
||||
);
|
||||
}
|
||||
if (Object.keys(formErrors).length > 0) {
|
||||
setErrors(formErrors);
|
||||
return false;
|
||||
}
|
||||
setErrors({});
|
||||
return true;
|
||||
};
|
||||
|
||||
return { errors, setErrors, clearErrors, validateFields, validateForm };
|
||||
};
|
||||
export default useAddTeamMember;
|
||||
@@ -1,213 +0,0 @@
|
||||
import { Button, Stack } from "@mui/material";
|
||||
import { GenericDialog } from "@/Components/v1/Dialog/genericDialog.jsx";
|
||||
import TextInput from "@/Components/v1/Inputs/TextInput/index.jsx";
|
||||
import Select from "@/Components/v1/Inputs/Select/index.jsx";
|
||||
import { useGetInviteToken } from "../../../../Hooks/inviteHooks.js";
|
||||
import { useTheme } from "@emotion/react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { createToast } from "../../../../Utils/toastUtils.jsx";
|
||||
import { useState } from "react";
|
||||
import PasswordTooltip from "../../../Auth/components/PasswordTooltip.jsx";
|
||||
import useAddTeamMember from "./hooks/useAddTeamMember.jsx";
|
||||
import usePasswordFeedback from "../../../Auth/hooks/usePasswordFeedback.jsx";
|
||||
import { PasswordEndAdornment } from "@/Components/v1/Inputs/TextInput/Adornments/index.jsx";
|
||||
import PropTypes from "prop-types";
|
||||
|
||||
const INITIAL_FORM_STATE = {
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
email: "",
|
||||
password: "",
|
||||
confirm: "",
|
||||
teamId: "",
|
||||
};
|
||||
|
||||
const INITIAL_ROLE_STATE = ["user"];
|
||||
const AddTeamMember = ({ handleIsRegisterOpen, isRegisterOpen, onMemberAdded }) => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const { errors, setErrors, clearErrors, validateFields, validateForm } =
|
||||
useAddTeamMember();
|
||||
const { feedback, handlePasswordFeedback } = usePasswordFeedback();
|
||||
const [getInviteToken, clearToken, isLoading, error, token, addTeamMember] =
|
||||
useGetInviteToken();
|
||||
const [form, setForm] = useState(INITIAL_FORM_STATE);
|
||||
const [role, setRole] = useState(INITIAL_ROLE_STATE);
|
||||
const [isLoadingSubmit, setIsLoadingSubmit] = useState(false);
|
||||
const closeAddMemberModal = () => {
|
||||
handleIsRegisterOpen(false);
|
||||
setForm(INITIAL_FORM_STATE);
|
||||
setRole(INITIAL_ROLE_STATE);
|
||||
clearErrors();
|
||||
clearToken();
|
||||
};
|
||||
|
||||
const onChange = (e) => {
|
||||
let { name, value } = e.target;
|
||||
if (name === "email") value = value.toLowerCase();
|
||||
const updatedForm = { ...form, [name]: value };
|
||||
validateFields(name, value, updatedForm);
|
||||
setForm(updatedForm);
|
||||
|
||||
if (name === "password" || name === "confirm") {
|
||||
handlePasswordFeedback(updatedForm, name, value, form, errors, setErrors);
|
||||
}
|
||||
};
|
||||
|
||||
const onsubmitAddMember = async (event) => {
|
||||
event.preventDefault();
|
||||
if (!validateForm(form, role)) return;
|
||||
try {
|
||||
setIsLoadingSubmit(true);
|
||||
await addTeamMember(form, role);
|
||||
createToast({
|
||||
body: t("teamPanel.registerToast.success"),
|
||||
});
|
||||
onMemberAdded();
|
||||
closeAddMemberModal();
|
||||
} catch (error) {
|
||||
const errorMsg = error.response?.data?.msg || error.message || "unknownError";
|
||||
createToast({
|
||||
type: "error",
|
||||
body: t(errorMsg),
|
||||
});
|
||||
} finally {
|
||||
setIsLoadingSubmit(false);
|
||||
}
|
||||
};
|
||||
const tErr = (key) => (key ? t([`teamPanel.registerTeamMember.${key}`, key]) : "");
|
||||
return (
|
||||
<>
|
||||
<GenericDialog
|
||||
title={t("teamPanel.addTeamMember.title")}
|
||||
description={t("teamPanel.addTeamMember.description")}
|
||||
open={isRegisterOpen}
|
||||
onClose={closeAddMemberModal}
|
||||
theme={theme}
|
||||
width={{ sm: "55%", md: "50%", lg: "40%", xl: "30%" }}
|
||||
>
|
||||
<TextInput
|
||||
name="firstName"
|
||||
label={t("auth.common.inputs.firstName.label")}
|
||||
isRequired={true}
|
||||
gap={theme.spacing(4)}
|
||||
placeholder={t("auth.common.inputs.firstName.placeholder")}
|
||||
value={form.firstName}
|
||||
onChange={onChange}
|
||||
error={errors.firstName ? true : false}
|
||||
helperText={errors.firstName ? tErr(errors.firstName) : null}
|
||||
sx={{ mb: errors.firstName ? theme.spacing(15) : theme.spacing(5) }}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
name="lastName"
|
||||
label={t("auth.common.inputs.lastName.label")}
|
||||
isRequired={true}
|
||||
gap={theme.spacing(4)}
|
||||
placeholder={t("auth.common.inputs.lastName.placeholder")}
|
||||
value={form.lastName}
|
||||
onChange={onChange}
|
||||
error={errors.lastName ? true : false}
|
||||
helperText={errors.lastName ? tErr(errors.lastName) : null}
|
||||
sx={{ mb: errors.lastName ? theme.spacing(15) : theme.spacing(5) }}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
type="email"
|
||||
label={t("auth.common.inputs.email.label")}
|
||||
name="email"
|
||||
gap={theme.spacing(4)}
|
||||
isRequired={true}
|
||||
id="input-team-member"
|
||||
placeholder={t("teamPanel.email")}
|
||||
value={form.email}
|
||||
onChange={onChange}
|
||||
error={errors.email ? true : false}
|
||||
helperText={errors.email ? tErr(errors.email) : null}
|
||||
sx={{ mb: errors.email ? theme.spacing(15) : theme.spacing(5) }}
|
||||
/>
|
||||
|
||||
<Select
|
||||
label={t("teamPanel.role")}
|
||||
id="team-member-role"
|
||||
name="role"
|
||||
required={true}
|
||||
placeholder={t("teamPanel.selectRole")}
|
||||
isHidden={true}
|
||||
value={role[0] || ""}
|
||||
sx={{ mb: theme.spacing(5) }}
|
||||
onChange={(event) => setRole([event.target.value])}
|
||||
items={[
|
||||
{ _id: "admin", name: t("roles.admin") },
|
||||
{ _id: "user", name: t("roles.teamMember") },
|
||||
]}
|
||||
/>
|
||||
|
||||
<PasswordTooltip
|
||||
feedback={feedback}
|
||||
form={form}
|
||||
>
|
||||
<TextInput
|
||||
type="password"
|
||||
id="register-password-input"
|
||||
name="password"
|
||||
label={t("auth.common.inputs.password.label")}
|
||||
isRequired={true}
|
||||
placeholder="••••••••••"
|
||||
value={form.password}
|
||||
onChange={onChange}
|
||||
error={errors.password && errors.password[0] ? true : false}
|
||||
endAdornment={<PasswordEndAdornment />}
|
||||
sx={{ mb: theme.spacing(5) }}
|
||||
/>
|
||||
</PasswordTooltip>
|
||||
<TextInput
|
||||
type="password"
|
||||
id="register-confirm-input"
|
||||
name="confirm"
|
||||
label={t("auth.common.inputs.passwordConfirm.label")}
|
||||
gap={theme.spacing(4)}
|
||||
isRequired={true}
|
||||
placeholder={t("auth.common.inputs.passwordConfirm.placeholder")}
|
||||
autoComplete="current-password"
|
||||
value={form.confirm}
|
||||
onChange={onChange}
|
||||
error={errors.confirm && errors.confirm[0] ? true : false}
|
||||
endAdornment={<PasswordEndAdornment />}
|
||||
sx={{ mb: theme.spacing(5) }}
|
||||
/>
|
||||
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={theme.spacing(10)}
|
||||
mt={theme.spacing(8)}
|
||||
justifyContent="flex-end"
|
||||
>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="error"
|
||||
onClick={closeAddMemberModal}
|
||||
disabled={isLoadingSubmit}
|
||||
>
|
||||
{t("teamPanel.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="accent"
|
||||
onClick={onsubmitAddMember}
|
||||
disabled={isLoadingSubmit}
|
||||
>
|
||||
{t("teamPanel.addTeamMember.addButton")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</GenericDialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
AddTeamMember.propTypes = {
|
||||
handleIsRegisterOpen: PropTypes.func.isRequired,
|
||||
isRegisterOpen: PropTypes.bool.isRequired,
|
||||
onMemberAdded: PropTypes.func.isRequired,
|
||||
};
|
||||
|
||||
export default AddTeamMember;
|
||||
@@ -0,0 +1,187 @@
|
||||
import { Stack } from "@mui/material";
|
||||
import MenuItem from "@mui/material/MenuItem";
|
||||
import { useTheme } from "@mui/material";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod/dist/zod.js";
|
||||
import { Dialog, TextField, Select } from "@/Components/v2/inputs";
|
||||
import { useAddTeamMemberForm } from "@/Hooks/useAddTeamMemberForm";
|
||||
import type { AddTeamMemberFormData } from "@/Validation/addTeamMember";
|
||||
import type { UserRole, User } from "@/Types/User";
|
||||
import { usePost } from "@/Hooks/UseApi";
|
||||
|
||||
interface AddTeamMemberDialogProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess?: () => void;
|
||||
}
|
||||
|
||||
interface RegisterPayload {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
password: string;
|
||||
role: string[];
|
||||
}
|
||||
|
||||
export const AddTeamMemberDialog = ({
|
||||
open,
|
||||
onClose,
|
||||
onSuccess,
|
||||
}: AddTeamMemberDialogProps) => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const { schema, defaults } = useAddTeamMemberForm();
|
||||
const { post, loading } = usePost<RegisterPayload, User>();
|
||||
|
||||
const { control, handleSubmit, reset, setError } = useForm<AddTeamMemberFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: defaults,
|
||||
values: defaults,
|
||||
});
|
||||
|
||||
const roleOptions: { value: UserRole; label: string }[] = [
|
||||
{ value: "admin", label: t("common.auth.roles.admin") },
|
||||
{ value: "user", label: t("common.auth.roles.user") },
|
||||
];
|
||||
|
||||
const handleClose = () => {
|
||||
reset();
|
||||
onClose();
|
||||
};
|
||||
|
||||
const onSubmit = async (data: AddTeamMemberFormData) => {
|
||||
if (loading) return;
|
||||
|
||||
const { confirm, ...userData } = data;
|
||||
const payload: RegisterPayload = userData;
|
||||
|
||||
const result = await post("/auth/users", payload);
|
||||
|
||||
if (result?.success) {
|
||||
reset();
|
||||
onClose();
|
||||
onSuccess?.();
|
||||
} else if (result?.msg) {
|
||||
if (result.msg.toLowerCase().includes("email")) {
|
||||
setError("email", { message: result.msg });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
title={t("pages.account.team.addMember.title")}
|
||||
content={t("pages.account.team.addMember.description")}
|
||||
onCancel={handleClose}
|
||||
onConfirm={handleSubmit(onSubmit)}
|
||||
confirmText={t("common.buttons.addMember")}
|
||||
loading={loading}
|
||||
maxWidth="sm"
|
||||
fullWidth
|
||||
>
|
||||
<Stack
|
||||
gap={theme.spacing(4)}
|
||||
mt={theme.spacing(4)}
|
||||
>
|
||||
<Controller
|
||||
name="firstName"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
fieldLabel={t("pages.auth.register.form.option.name.label")}
|
||||
placeholder={t("pages.auth.register.form.option.name.placeholder")}
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
fullWidth
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="lastName"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
fieldLabel={t("pages.auth.register.form.option.surname.label")}
|
||||
placeholder={t("pages.auth.register.form.option.surname.placeholder")}
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
fullWidth
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="email"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
fieldLabel={t("pages.auth.common.form.option.email.label")}
|
||||
placeholder={t("pages.auth.common.form.option.email.placeholder")}
|
||||
type="email"
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
fullWidth
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="role"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
{...field}
|
||||
value={field.value[0] ?? "user"}
|
||||
onChange={(e) => field.onChange([e.target.value])}
|
||||
fieldLabel={t("pages.account.team.invite.role.label")}
|
||||
placeholder={t("pages.account.team.invite.role.placeholder")}
|
||||
fullWidth
|
||||
>
|
||||
{roleOptions.map((option) => (
|
||||
<MenuItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
>
|
||||
{option.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="password"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
fieldLabel={t("pages.auth.common.form.option.password.label")}
|
||||
placeholder={t("pages.auth.common.form.option.password.placeholder")}
|
||||
type="password"
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
fullWidth
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="confirm"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
fieldLabel={t("pages.auth.common.form.option.confirmPassword.label")}
|
||||
placeholder={t("pages.auth.common.form.option.password.placeholder")}
|
||||
type="password"
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
fullWidth
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Stack>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
import Stack from "@mui/material/Stack";
|
||||
import MenuItem from "@mui/material/MenuItem";
|
||||
import { Button, Select } from "@/Components/v2/inputs";
|
||||
import { Icon } from "@/Components/v2/design-elements";
|
||||
import { UserPlus, Mail } from "lucide-react";
|
||||
|
||||
import { UserRoles } from "@/Types/User";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import type { UserRole } from "@/Types/User";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useIsAdmin, useIsSuperAdmin } from "@/Hooks/useIsAdmin";
|
||||
|
||||
interface HeaderTeamControlsProps {
|
||||
filter: UserRole | "";
|
||||
onFilterChange: (value: UserRole | "") => void;
|
||||
onInviteClick?: () => void;
|
||||
onAddMemberClick?: () => void;
|
||||
}
|
||||
|
||||
export const HeaderTeamControls = ({
|
||||
filter,
|
||||
onFilterChange,
|
||||
onInviteClick,
|
||||
onAddMemberClick,
|
||||
}: HeaderTeamControlsProps) => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const isAdmin = useIsAdmin();
|
||||
const isSuperAdmin = useIsSuperAdmin();
|
||||
|
||||
const handleFilterChange = (event: { target: { value: unknown } }) => {
|
||||
onFilterChange(event.target.value as UserRole | "");
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack
|
||||
direction="row"
|
||||
alignItems="center"
|
||||
justifyContent="flex-end"
|
||||
gap={theme.spacing(4)}
|
||||
>
|
||||
<Select
|
||||
value={filter}
|
||||
onChange={handleFilterChange}
|
||||
placeholder={t("pages.account.team.filter.placeholder")}
|
||||
sx={{ minWidth: 150 }}
|
||||
>
|
||||
<MenuItem value="">{t("pages.account.team.filter.all")}</MenuItem>
|
||||
{UserRoles.map((role) => (
|
||||
<MenuItem
|
||||
key={role}
|
||||
value={role}
|
||||
>
|
||||
{t(`common.auth.roles.${role}`)}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
{isAdmin && (
|
||||
<Button
|
||||
variant="contained"
|
||||
color="primary"
|
||||
startIcon={<Icon icon={Mail} />}
|
||||
onClick={onInviteClick}
|
||||
>
|
||||
{t("common.buttons.inviteMember")}
|
||||
</Button>
|
||||
)}
|
||||
{isSuperAdmin && (
|
||||
<Button
|
||||
variant="contained"
|
||||
color="primary"
|
||||
startIcon={<Icon icon={UserPlus} />}
|
||||
onClick={onAddMemberClick}
|
||||
>
|
||||
{t("common.buttons.addMember")}
|
||||
</Button>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,164 @@
|
||||
import { Stack } from "@mui/material";
|
||||
import MenuItem from "@mui/material/MenuItem";
|
||||
import { useTheme, FormHelperText, Typography } from "@mui/material";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import { Dialog, TextField, Select, Button } from "@/Components/v2/inputs";
|
||||
import type { UserRole } from "@/Types/User";
|
||||
import { useInviteForm } from "@/Hooks/useInviteForm";
|
||||
import type { InviteFormData } from "@/Validation/invite";
|
||||
import { usePost } from "@/Hooks/UseApi";
|
||||
|
||||
const CLIENT_HOST = import.meta.env.VITE_APP_CLIENT_HOST;
|
||||
|
||||
interface InviteResponse {
|
||||
token: string;
|
||||
}
|
||||
|
||||
interface InviteTeamMemberDialogProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export const InviteTeamMemberDialog = ({
|
||||
open,
|
||||
onClose,
|
||||
}: InviteTeamMemberDialogProps) => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const { resolver, defaults } = useInviteForm();
|
||||
|
||||
const { control, handleSubmit, reset } = useForm<InviteFormData>({
|
||||
resolver,
|
||||
defaultValues: defaults,
|
||||
values: defaults,
|
||||
});
|
||||
|
||||
const { post: generateToken, loading: generateLoading } = usePost<
|
||||
InviteFormData,
|
||||
InviteResponse
|
||||
>();
|
||||
const { post: sendInvite, loading: sendLoading } = usePost<
|
||||
InviteFormData,
|
||||
InviteResponse
|
||||
>();
|
||||
const [inviteLink, setInviteLink] = useState<string | null>(null);
|
||||
|
||||
const roleOptions: { value: UserRole; label: string }[] = [
|
||||
{ value: "admin", label: t("common.auth.roles.admin") },
|
||||
{ value: "user", label: t("common.auth.roles.user") },
|
||||
];
|
||||
|
||||
const handleGenerateToken = async (data: InviteFormData) => {
|
||||
const result = await generateToken("/invite", data);
|
||||
if (result?.data?.token) {
|
||||
const token = result.data.token;
|
||||
const link = CLIENT_HOST ? `${CLIENT_HOST}/register/${token}` : token;
|
||||
setInviteLink(link);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSendInvite = async (data: InviteFormData) => {
|
||||
const result = await sendInvite("/invite/send", data);
|
||||
if (result?.success) {
|
||||
handleClose();
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
reset();
|
||||
setInviteLink(null);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
title={t("pages.account.team.invite.title")}
|
||||
content={t("pages.account.team.invite.description")}
|
||||
onCancel={handleClose}
|
||||
onConfirm={handleSubmit(handleSendInvite)}
|
||||
confirmText={t("common.buttons.sendInvite")}
|
||||
loading={sendLoading || generateLoading}
|
||||
maxWidth="sm"
|
||||
fullWidth
|
||||
additionalButtons={
|
||||
<Button
|
||||
variant="contained"
|
||||
color="primary"
|
||||
onClick={handleSubmit(handleGenerateToken)}
|
||||
loading={generateLoading || sendLoading}
|
||||
>
|
||||
{t("common.buttons.generateToken")}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Stack
|
||||
gap={theme.spacing(4)}
|
||||
mt={theme.spacing(4)}
|
||||
>
|
||||
<Controller
|
||||
name="email"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
fieldLabel={t("pages.account.team.invite.email.label")}
|
||||
placeholder={t("pages.account.team.invite.email.placeholder")}
|
||||
type="email"
|
||||
fullWidth
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="role"
|
||||
control={control}
|
||||
render={({ field: { value, onChange, ...field }, fieldState }) => (
|
||||
<>
|
||||
<Select
|
||||
{...field}
|
||||
value={Array.isArray(value) ? (value[0] ?? "") : ""}
|
||||
onChange={(e) => onChange([e.target.value as UserRole])}
|
||||
fieldLabel={t("pages.account.team.invite.role.label")}
|
||||
placeholder={t("pages.account.team.invite.role.placeholder")}
|
||||
fullWidth
|
||||
error={!!fieldState.error}
|
||||
>
|
||||
{roleOptions.map((option) => (
|
||||
<MenuItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
>
|
||||
{option.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
{fieldState.error && (
|
||||
<FormHelperText error>{fieldState.error.message}</FormHelperText>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
{inviteLink && (
|
||||
<>
|
||||
<Typography variant="body2">
|
||||
{t("pages.account.team.invite.linkLabel")}
|
||||
</Typography>
|
||||
<TextField
|
||||
value={inviteLink}
|
||||
fullWidth
|
||||
slotProps={{
|
||||
input: {
|
||||
readOnly: true,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -1,281 +0,0 @@
|
||||
import TabPanel from "@mui/lab/TabPanel";
|
||||
import { useState } from "react";
|
||||
import { useTheme } from "@emotion/react";
|
||||
import { Box, Stack, Typography, Button } from "@mui/material";
|
||||
import { PasswordEndAdornment } from "@/Components/v1/Inputs/TextInput/Adornments/index.jsx";
|
||||
import TextInput from "@/Components/v1/Inputs/TextInput/index.jsx";
|
||||
import { newOrChangedCredentials } from "../../../Validation/validation.js";
|
||||
import Alert from "@/Components/v1/Alert/index.jsx";
|
||||
import { update } from "../../../Features/Auth/authSlice.js";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { createToast } from "../../../Utils/toastUtils.jsx";
|
||||
import { getTouchedFieldErrors } from "../../../Validation/error.js";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
const defaultPasswordsState = {
|
||||
password: "",
|
||||
newPassword: "",
|
||||
confirm: "",
|
||||
};
|
||||
|
||||
/**
|
||||
* PasswordPanel component manages the form for editing password.
|
||||
*
|
||||
* @returns {JSX.Element}
|
||||
*/
|
||||
|
||||
const PasswordPanel = () => {
|
||||
const theme = useTheme();
|
||||
const dispatch = useDispatch();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const SPACING_GAP = theme.spacing(12);
|
||||
|
||||
//redux state
|
||||
const { isLoading } = useSelector((state) => state.auth);
|
||||
|
||||
const idToName = {
|
||||
"edit-current-password": "password",
|
||||
"edit-new-password": "newPassword",
|
||||
"edit-confirm-password": "confirm",
|
||||
};
|
||||
|
||||
const [localData, setLocalData] = useState(defaultPasswordsState);
|
||||
const [errors, setErrors] = useState(defaultPasswordsState);
|
||||
const [touchedFields, setTouchedFields] = useState({
|
||||
password: false,
|
||||
newPassword: false,
|
||||
confirm: false,
|
||||
});
|
||||
|
||||
const handleChange = (event) => {
|
||||
const { value, id } = event.target;
|
||||
const name = idToName[id];
|
||||
|
||||
const updatedData = {
|
||||
...localData,
|
||||
[name]: value,
|
||||
};
|
||||
const updatedTouchedFields = {
|
||||
...touchedFields,
|
||||
[name]: true,
|
||||
};
|
||||
|
||||
const validation = newOrChangedCredentials.validate(
|
||||
{ ...updatedData },
|
||||
{ abortEarly: false, context: { password: updatedData.newPassword } }
|
||||
);
|
||||
|
||||
const updatedErrors = getTouchedFieldErrors(validation, updatedTouchedFields);
|
||||
|
||||
if (!touchedFields[name]) {
|
||||
setTouchedFields(updatedTouchedFields);
|
||||
}
|
||||
|
||||
setLocalData(updatedData);
|
||||
setErrors(updatedErrors);
|
||||
};
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
|
||||
const { error } = newOrChangedCredentials.validate(localData, {
|
||||
abortEarly: false,
|
||||
context: { password: localData.newPassword },
|
||||
});
|
||||
|
||||
if (error) {
|
||||
const newErrors = {};
|
||||
error.details.forEach((err) => {
|
||||
newErrors[err.path[0]] = err.message;
|
||||
});
|
||||
setErrors(newErrors);
|
||||
} else {
|
||||
const action = await dispatch(update({ localData }));
|
||||
if (action.payload.success) {
|
||||
createToast({
|
||||
body: t(
|
||||
"passwordPanel.passwordChangedSuccess",
|
||||
"Your password was changed successfully."
|
||||
),
|
||||
});
|
||||
setLocalData({
|
||||
password: "",
|
||||
newPassword: "",
|
||||
confirm: "",
|
||||
});
|
||||
} else {
|
||||
// TODO: Check for other errors?
|
||||
createToast({
|
||||
body: t(
|
||||
"passwordPanel.passwordInputIncorrect",
|
||||
"Your password input was incorrect."
|
||||
),
|
||||
});
|
||||
setErrors({ password: "*" + action.payload.msg + "." });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<TabPanel
|
||||
value="password"
|
||||
sx={{
|
||||
"& h1, & input": {
|
||||
color: theme.palette.primary.contrastTextTertiary,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Stack
|
||||
component="form"
|
||||
onSubmit={handleSubmit}
|
||||
noValidate
|
||||
spellCheck="false"
|
||||
gap={theme.spacing(26)}
|
||||
maxWidth={"80ch"} // Keep maxWidth
|
||||
>
|
||||
<TextInput
|
||||
type="text"
|
||||
id="hidden-username"
|
||||
name="username"
|
||||
autoComplete="username"
|
||||
hidden={true}
|
||||
value=""
|
||||
/>
|
||||
|
||||
<Stack
|
||||
direction="row"
|
||||
justifyContent={"flex-start"}
|
||||
alignItems={"center"}
|
||||
gap={SPACING_GAP}
|
||||
flexWrap={"wrap"}
|
||||
>
|
||||
<Typography
|
||||
component="h1"
|
||||
width="20ch"
|
||||
>
|
||||
{t("passwordPanel.currentPassword", "Current password")}
|
||||
</Typography>
|
||||
<TextInput
|
||||
type="password"
|
||||
id="edit-current-password"
|
||||
placeholder={t(
|
||||
"passwordPanel.enterCurrentPassword",
|
||||
"Enter your current password"
|
||||
)}
|
||||
autoComplete="current-password"
|
||||
value={localData.password}
|
||||
onChange={handleChange}
|
||||
error={errors[idToName["edit-current-password"]] ? true : false}
|
||||
helperText={
|
||||
errors[idToName["edit-current-password"]]
|
||||
? t(errors[idToName["edit-current-password"]])
|
||||
: ""
|
||||
}
|
||||
endAdornment={<PasswordEndAdornment />}
|
||||
flex={1}
|
||||
/>
|
||||
</Stack>
|
||||
<Stack
|
||||
direction="row"
|
||||
alignItems={"flex-start"}
|
||||
gap={SPACING_GAP}
|
||||
flexWrap={"wrap"}
|
||||
>
|
||||
<Typography
|
||||
component="h1"
|
||||
width="20ch"
|
||||
>
|
||||
{t("passwordPanel.newPassword", "New password")}
|
||||
</Typography>
|
||||
|
||||
<TextInput
|
||||
type="password"
|
||||
id="edit-new-password"
|
||||
placeholder={t("passwordPanel.enterNewPassword", "Enter your new password")}
|
||||
autoComplete="new-password"
|
||||
value={localData.newPassword}
|
||||
onChange={handleChange}
|
||||
error={errors[idToName["edit-new-password"]] ? true : false}
|
||||
helperText={
|
||||
errors[idToName["edit-new-password"]]
|
||||
? t(errors[idToName["edit-new-password"]])
|
||||
: ""
|
||||
}
|
||||
endAdornment={<PasswordEndAdornment />}
|
||||
flex={1}
|
||||
/>
|
||||
</Stack>
|
||||
<Stack
|
||||
direction="row"
|
||||
alignItems={"flex-start"}
|
||||
gap={SPACING_GAP}
|
||||
flexWrap={"wrap"}
|
||||
>
|
||||
<Typography
|
||||
component="h1"
|
||||
width="20ch"
|
||||
>
|
||||
{t("passwordPanel.confirmNewPassword", "Confirm new password")}
|
||||
</Typography>
|
||||
|
||||
<TextInput
|
||||
type="password"
|
||||
id="edit-confirm-password"
|
||||
placeholder={t("confirmPassword")}
|
||||
autoComplete="new-password"
|
||||
value={localData.confirm}
|
||||
onChange={handleChange}
|
||||
error={errors[idToName["edit-confirm-password"]] ? true : false}
|
||||
helperText={
|
||||
errors[idToName["edit-confirm-password"]]
|
||||
? t(errors[idToName["edit-confirm-password"]])
|
||||
: ""
|
||||
}
|
||||
endAdornment={<PasswordEndAdornment />}
|
||||
flex={1}
|
||||
/>
|
||||
</Stack>
|
||||
{Object.keys(errors).length > 0 && (
|
||||
<Box sx={{ maxWidth: "70ch" }}>
|
||||
<Alert
|
||||
variant="warning"
|
||||
body={t(
|
||||
"passwordPanel.passwordRequirements",
|
||||
"New password must contain at least 8 characters and must have at least one uppercase letter, one lowercase letter, one number and one special character."
|
||||
)}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
<Stack
|
||||
direction="row"
|
||||
justifyContent="flex-end"
|
||||
>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="accent"
|
||||
type="submit"
|
||||
loading={isLoading}
|
||||
loadingIndicator={t("commonSaving", "Saving...")}
|
||||
disabled={
|
||||
Object.keys(errors).length > 0 ||
|
||||
Object.values(localData).filter((value) => value === "").length > 0
|
||||
}
|
||||
sx={{
|
||||
px: theme.spacing(12),
|
||||
mt: theme.spacing(20),
|
||||
}}
|
||||
>
|
||||
{t("commonSave", "Save")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</TabPanel>
|
||||
);
|
||||
};
|
||||
|
||||
PasswordPanel.propTypes = {
|
||||
// No props are being passed to this component, hence no specific PropTypes are defined.
|
||||
};
|
||||
|
||||
export default PasswordPanel;
|
||||
@@ -1,437 +0,0 @@
|
||||
import { useTheme } from "@emotion/react";
|
||||
import { useState } from "react";
|
||||
import TabPanel from "@mui/lab/TabPanel";
|
||||
import { Box, Button, Divider, Stack, Typography } from "@mui/material";
|
||||
import Avatar from "@/Components/v1/Avatar/index.jsx";
|
||||
import TextInput from "@/Components/v1/Inputs/TextInput/index.jsx";
|
||||
import ImageUpload from "@/Components/v1/Inputs/ImageUpload/index.jsx";
|
||||
import { newOrChangedCredentials } from "../../../Validation/validation.js";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { clearAuthState, deleteUser, update } from "../../../Features/Auth/authSlice.js";
|
||||
import { createToast } from "../../../Utils/toastUtils.jsx";
|
||||
import { logger } from "../../../Utils/Logger.js";
|
||||
import { GenericDialog } from "@/Components/v1/Dialog/genericDialog.jsx";
|
||||
import Dialog from "@/Components/v1/Dialog/index.jsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
/**
|
||||
* ProfilePanel component displays a form for editing user profile information
|
||||
* and allows for actions like updating profile picture, credentials,
|
||||
* and deleting account.
|
||||
*
|
||||
* @returns {JSX.Element}
|
||||
*/
|
||||
|
||||
const ProfilePanel = () => {
|
||||
const theme = useTheme();
|
||||
const dispatch = useDispatch();
|
||||
const { t } = useTranslation();
|
||||
const SPACING_GAP = theme.spacing(12);
|
||||
|
||||
//redux state
|
||||
const { user, isLoading } = useSelector((state) => state.auth);
|
||||
|
||||
const idToName = {
|
||||
"edit-first-name": "firstName",
|
||||
"edit-last-name": "lastName",
|
||||
// Disabled for now, will revisit in the future
|
||||
// "edit-email": "email",
|
||||
};
|
||||
|
||||
// Local state for form data, errors, and file handling
|
||||
const [localData, setLocalData] = useState({
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
// email: user.email, // Disabled for now
|
||||
});
|
||||
const [errors, setErrors] = useState({});
|
||||
const [file, setFile] = useState();
|
||||
|
||||
// Handles input field changes and performs validation
|
||||
const handleChange = (event) => {
|
||||
errors["unchanged"] && clearError("unchanged");
|
||||
const { value, id } = event.target;
|
||||
const name = idToName[id];
|
||||
setLocalData((prev) => ({
|
||||
...prev,
|
||||
[name]: value,
|
||||
}));
|
||||
|
||||
validateField({ [name]: value }, newOrChangedCredentials, name);
|
||||
};
|
||||
|
||||
// Validates input against provided schema and updates error state
|
||||
const validateField = (toValidate, schema, name = "picture") => {
|
||||
const { error } = schema.validate(toValidate, { abortEarly: false });
|
||||
setErrors((prev) => {
|
||||
const prevErrors = { ...prev };
|
||||
if (error) prevErrors[name] = error.details[0].message;
|
||||
else delete prevErrors[name];
|
||||
return prevErrors;
|
||||
});
|
||||
if (error) return true;
|
||||
};
|
||||
|
||||
// Clears specific error from errors state
|
||||
const clearError = (err) => {
|
||||
setErrors((prev) => {
|
||||
const updatedErrors = { ...prev };
|
||||
if (updatedErrors[err]) delete updatedErrors[err];
|
||||
return updatedErrors;
|
||||
});
|
||||
};
|
||||
|
||||
// Resets picture-related states and clears interval
|
||||
const removePicture = () => {
|
||||
errors["picture"] && clearError("picture");
|
||||
setFile(undefined);
|
||||
setLocalData((prev) => ({
|
||||
...prev,
|
||||
file: undefined,
|
||||
deleteProfileImage: true,
|
||||
}));
|
||||
};
|
||||
|
||||
// Opens the picture update modal
|
||||
const openPictureModal = () => {
|
||||
setIsOpen("picture");
|
||||
setFile(undefined);
|
||||
};
|
||||
|
||||
// Closes the picture update modal and resets related states
|
||||
const closePictureModal = () => {
|
||||
if (errors["picture"]) clearError("picture");
|
||||
setFile(undefined);
|
||||
setIsOpen("");
|
||||
};
|
||||
|
||||
// Updates profile image displayed on UI
|
||||
const handleUpdatePicture = () => {
|
||||
setLocalData((prev) => ({
|
||||
...prev,
|
||||
file: file?.src,
|
||||
deleteProfileImage: false,
|
||||
}));
|
||||
setIsOpen("");
|
||||
if (errors["unchanged"]) clearError("unchanged");
|
||||
};
|
||||
|
||||
// Handles form submission to update user profile
|
||||
const handleSaveProfile = async (event) => {
|
||||
event.preventDefault();
|
||||
const nameChanged =
|
||||
localData.firstName !== user.firstName || localData.lastName !== user.lastName;
|
||||
|
||||
const avatarChanged =
|
||||
localData.deleteProfileImage === true ||
|
||||
(localData.file && localData.file !== `data:image/png;base64,${user.avatarImage}`);
|
||||
|
||||
if (!nameChanged && !avatarChanged) {
|
||||
createToast({
|
||||
body: "Unable to update profile — no changes detected.",
|
||||
});
|
||||
setErrors({ unchanged: "unable to update profile" });
|
||||
return;
|
||||
}
|
||||
|
||||
const action = await dispatch(update({ localData }));
|
||||
if (action.payload.success) {
|
||||
createToast({
|
||||
body: "Your profile data was changed successfully.",
|
||||
});
|
||||
} else {
|
||||
createToast({
|
||||
body: "There was an error updating your profile data.",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Removes current profile image from UI
|
||||
const handleDeletePicture = () => {
|
||||
setLocalData((prev) => ({
|
||||
...prev,
|
||||
deleteProfileImage: true,
|
||||
}));
|
||||
setFile(undefined);
|
||||
errors["unchanged"] && clearError("unchanged");
|
||||
};
|
||||
|
||||
// Initiates the account deletion process
|
||||
const handleDeleteAccount = async () => {
|
||||
const action = await dispatch(deleteUser());
|
||||
if (action.payload.success) {
|
||||
dispatch(clearAuthState());
|
||||
} else {
|
||||
if (action.payload) {
|
||||
// dispatch errors
|
||||
createToast({
|
||||
body: action.payload.msg,
|
||||
});
|
||||
} else {
|
||||
// unknown errors
|
||||
createToast({
|
||||
body: "Unknown error.",
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Modal state and control functions
|
||||
const [isOpen, setIsOpen] = useState("");
|
||||
const isModalOpen = (name) => isOpen === name;
|
||||
|
||||
return (
|
||||
<TabPanel
|
||||
value="profile"
|
||||
sx={{
|
||||
"& h1, & p, & input": {
|
||||
color: theme.palette.primary.contrastTextTertiary,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Stack
|
||||
component="form"
|
||||
noValidate
|
||||
spellCheck="false"
|
||||
gap={SPACING_GAP}
|
||||
>
|
||||
<Stack
|
||||
direction="row"
|
||||
gap={SPACING_GAP}
|
||||
>
|
||||
{/* This 0.9 is a bit magic numbering, refactor */}
|
||||
<Box flex={0.9}>
|
||||
<Typography component="h1">{t("FirstName")}</Typography>
|
||||
</Box>
|
||||
<TextInput
|
||||
id="edit-first-name"
|
||||
value={localData.firstName}
|
||||
placeholder="Enter your first name"
|
||||
autoComplete="given-name"
|
||||
onChange={handleChange}
|
||||
error={errors[idToName["edit-first-name"]] ? true : false}
|
||||
helperText={
|
||||
errors[idToName["edit-first-name"]]
|
||||
? t(errors[idToName["edit-first-name"]])
|
||||
: ""
|
||||
}
|
||||
flex={1}
|
||||
/>
|
||||
</Stack>
|
||||
<Stack
|
||||
direction="row"
|
||||
gap={SPACING_GAP}
|
||||
>
|
||||
<Box flex={0.9}>
|
||||
<Typography component="h1">{t("LastName")}</Typography>
|
||||
</Box>
|
||||
<TextInput
|
||||
id="edit-last-name"
|
||||
placeholder="Enter your last name"
|
||||
autoComplete="family-name"
|
||||
value={localData.lastName}
|
||||
onChange={handleChange}
|
||||
error={errors[idToName["edit-last-name"]] ? true : false}
|
||||
helperText={
|
||||
errors[idToName["edit-last-name"]]
|
||||
? t(errors[idToName["edit-last-name"]])
|
||||
: ""
|
||||
}
|
||||
flex={1}
|
||||
/>
|
||||
</Stack>
|
||||
<Stack
|
||||
direction="row"
|
||||
gap={SPACING_GAP}
|
||||
>
|
||||
<Stack flex={0.9}>
|
||||
<Typography component="h1">{t("auth.common.inputs.email.label")}</Typography>
|
||||
<Typography
|
||||
component="p"
|
||||
sx={{ opacity: 0.6 }}
|
||||
>
|
||||
{t("EmailDescriptionText")}
|
||||
</Typography>
|
||||
</Stack>
|
||||
<TextInput
|
||||
id="edit-email"
|
||||
value={user.email}
|
||||
placeholder="Enter your email"
|
||||
autoComplete="email"
|
||||
onChange={() => logger.warn("disabled")}
|
||||
disabled={true}
|
||||
flex={1}
|
||||
/>
|
||||
</Stack>
|
||||
<Stack
|
||||
direction="row"
|
||||
gap={SPACING_GAP}
|
||||
>
|
||||
<Stack flex={0.9}>
|
||||
<Typography component="h1">{t("YourPhoto")}</Typography>
|
||||
<Typography
|
||||
component="p"
|
||||
sx={{ opacity: 0.6 }}
|
||||
>
|
||||
{t("PhotoDescriptionText")}
|
||||
</Typography>
|
||||
</Stack>
|
||||
<Stack
|
||||
direction="row"
|
||||
alignItems="center"
|
||||
flex={1}
|
||||
gap={"8px"}
|
||||
>
|
||||
<Avatar
|
||||
src={
|
||||
localData?.deleteProfileImage
|
||||
? "/static/images/avatar/2.jpg"
|
||||
: localData?.file
|
||||
? localData.file
|
||||
: ""
|
||||
}
|
||||
sx={{ marginRight: "8px" }}
|
||||
/>
|
||||
<Button
|
||||
variant="contained" // CAIO_REIVEW
|
||||
color="error"
|
||||
onClick={handleDeletePicture}
|
||||
>
|
||||
{t("delete")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained" // CAIO_REVIEW
|
||||
color="accent"
|
||||
onClick={openPictureModal}
|
||||
>
|
||||
{t("update")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
<Divider
|
||||
aria-hidden="true"
|
||||
width="0"
|
||||
sx={{
|
||||
marginY: theme.spacing(1),
|
||||
}}
|
||||
/>
|
||||
<Stack
|
||||
direction="row"
|
||||
justifyContent="flex-end"
|
||||
>
|
||||
<Box width="fit-content">
|
||||
<Button
|
||||
variant="contained"
|
||||
color="accent"
|
||||
onClick={handleSaveProfile}
|
||||
loading={isLoading}
|
||||
loadingIndicator="Saving..."
|
||||
disabled={Object.keys(errors).length !== 0 && !errors?.picture && true}
|
||||
sx={{ px: theme.spacing(12) }}
|
||||
>
|
||||
{t("save")}
|
||||
</Button>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Stack>
|
||||
<Divider
|
||||
aria-hidden="true"
|
||||
sx={{
|
||||
marginY: theme.spacing(20),
|
||||
borderColor: theme.palette.primary.lowContrast,
|
||||
}}
|
||||
/>
|
||||
{!user.role.includes("demo") && (
|
||||
<Box
|
||||
component="form"
|
||||
noValidate
|
||||
spellCheck="false"
|
||||
>
|
||||
<Box mb={theme.spacing(6)}>
|
||||
<Typography component="h1">{t("DeleteAccountTitle")}</Typography>
|
||||
<Typography
|
||||
component="p"
|
||||
sx={{ opacity: 0.6 }}
|
||||
>
|
||||
{t("DeleteDescriptionText")}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="error"
|
||||
onClick={() => setIsOpen("delete")}
|
||||
>
|
||||
{t("DeleteAccountButton")}
|
||||
</Button>
|
||||
</Box>
|
||||
)}
|
||||
<Dialog
|
||||
open={isModalOpen("delete")}
|
||||
theme={theme}
|
||||
title={t("DeleteWarningTitle")}
|
||||
description={t("DeleteAccountWarning")}
|
||||
onCancel={() => setIsOpen("")}
|
||||
confirmationButtonLabel={t("DeleteAccountButton")}
|
||||
onConfirm={handleDeleteAccount}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
|
||||
<GenericDialog
|
||||
title={"Upload Image"}
|
||||
open={isModalOpen("picture")}
|
||||
onClose={closePictureModal}
|
||||
theme={theme}
|
||||
>
|
||||
<ImageUpload
|
||||
src={
|
||||
file?.src
|
||||
? file.src
|
||||
: localData?.deleteProfileImage
|
||||
? ""
|
||||
: localData?.file
|
||||
? localData.file
|
||||
: user?.avatarImage
|
||||
? `data:image/png;base64,${user.avatarImage}`
|
||||
: ""
|
||||
}
|
||||
onChange={(newFile) => {
|
||||
if (newFile) {
|
||||
setFile(newFile);
|
||||
clearError("unchanged");
|
||||
}
|
||||
}}
|
||||
previewIsRound
|
||||
maxSize={3 * 1024 * 1024}
|
||||
/>
|
||||
<Stack
|
||||
direction="row"
|
||||
mt={theme.spacing(10)}
|
||||
gap={theme.spacing(5)}
|
||||
justifyContent="flex-end"
|
||||
>
|
||||
<Button
|
||||
variant="text"
|
||||
color="info"
|
||||
onClick={removePicture}
|
||||
>
|
||||
{t("remove")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="accent"
|
||||
onClick={handleUpdatePicture}
|
||||
disabled={!!errors.picture || !file?.src}
|
||||
>
|
||||
{t("update")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</GenericDialog>
|
||||
</TabPanel>
|
||||
);
|
||||
};
|
||||
|
||||
ProfilePanel.propTypes = {
|
||||
// No props are being passed to this component, hence no specific PropTypes are defined.
|
||||
};
|
||||
|
||||
export default ProfilePanel;
|
||||
@@ -1,360 +0,0 @@
|
||||
import { useTheme } from "@emotion/react";
|
||||
import TabPanel from "@mui/lab/TabPanel";
|
||||
import { Button, ButtonGroup, Stack, Typography } from "@mui/material";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import TextInput from "@/Components/v1/Inputs/TextInput/index.jsx";
|
||||
import { newOrChangedCredentials } from "../../../Validation/validation.js";
|
||||
import { networkService } from "../../../main.jsx";
|
||||
import { createToast } from "../../../Utils/toastUtils.jsx";
|
||||
import Select from "@/Components/v1/Inputs/Select/index.jsx";
|
||||
import { GenericDialog } from "@/Components/v1/Dialog/genericDialog.jsx";
|
||||
import AddTeamMember from "./AddTeamMember/index.jsx";
|
||||
import DataTable from "@/Components/v1/Table/index.jsx";
|
||||
import { useGetInviteToken } from "../../../Hooks/inviteHooks.js";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useIsSuperAdmin } from "@/Hooks/useIsAdmin.js";
|
||||
import AddMemberMenu from "./AddMemberMenu/index.jsx";
|
||||
/**
|
||||
* TeamPanel component manages the organization and team members,
|
||||
* providing functionalities like renaming the organization, managing team members,
|
||||
* and inviting new members.
|
||||
*
|
||||
* @returns {JSX.Element}
|
||||
*/
|
||||
|
||||
const TeamPanel = () => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const SPACING_GAP = theme.spacing(12);
|
||||
|
||||
const [toInvite, setToInvite] = useState({
|
||||
email: "",
|
||||
role: ["user"],
|
||||
});
|
||||
const [data, setData] = useState([]);
|
||||
const [members, setMembers] = useState([]);
|
||||
const [filter, setFilter] = useState("all");
|
||||
const [isDisabled, setIsDisabled] = useState(true);
|
||||
const [errors, setErrors] = useState({});
|
||||
const [isSendingInvite, setIsSendingInvite] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const [getInviteToken, clearToken, isLoading, error, token] = useGetInviteToken();
|
||||
const isSuperAdmin = useIsSuperAdmin();
|
||||
|
||||
const headers = [
|
||||
{
|
||||
id: "name",
|
||||
content: t("teamPanel.table.name"),
|
||||
render: (row) => {
|
||||
return (
|
||||
<Stack>
|
||||
<Typography color={theme.palette.primary.contrastTextSecondary}>
|
||||
{row.firstName + " " + row.lastName}
|
||||
</Typography>
|
||||
<Typography>
|
||||
{t("teamPanel.table.created")}{" "}
|
||||
{new Date(row.createdAt).toLocaleDateString()}
|
||||
</Typography>
|
||||
</Stack>
|
||||
);
|
||||
},
|
||||
},
|
||||
{ id: "email", content: t("teamPanel.table.email"), render: (row) => row.email },
|
||||
{
|
||||
id: "role",
|
||||
content: t("teamPanel.table.role"),
|
||||
render: (row) => row.role,
|
||||
},
|
||||
];
|
||||
const [refreshTrigger, setRefreshTrigger] = useState(false);
|
||||
const refreshTeamList = () => {
|
||||
setRefreshTrigger((prev) => !prev);
|
||||
};
|
||||
useEffect(() => {
|
||||
const fetchTeam = async () => {
|
||||
try {
|
||||
const response = await networkService.getAllUsers();
|
||||
setMembers(response.data.data);
|
||||
} catch (error) {
|
||||
createToast({
|
||||
body: error.message || "Error fetching team members.",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
fetchTeam();
|
||||
}, [refreshTrigger]);
|
||||
|
||||
useEffect(() => {
|
||||
const ROLE_MAP = {
|
||||
superadmin: t("roles.superAdmin"),
|
||||
admin: t("roles.admin"),
|
||||
user: t("roles.teamMember"),
|
||||
demo: t("roles.demoUser"),
|
||||
};
|
||||
let team = members;
|
||||
if (filter !== "all")
|
||||
team = members.filter((member) => {
|
||||
if (filter === "admin") {
|
||||
return member.role.includes("admin") || member.role.includes("superadmin");
|
||||
}
|
||||
return member.role.includes(filter);
|
||||
});
|
||||
|
||||
team = team.map((member) => ({
|
||||
...member,
|
||||
id: member.id,
|
||||
role: member.role.map((role) => ROLE_MAP[role]).join(","),
|
||||
}));
|
||||
setData(team);
|
||||
}, [members, filter, t]);
|
||||
|
||||
useEffect(() => {
|
||||
setIsDisabled(Object.keys(errors).length !== 0 || toInvite.email === "");
|
||||
}, [errors, toInvite.email]);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isRegisterOpen, setIsRegisterOpen] = useState(false);
|
||||
const handleIsRegisterOpen = (open) => {
|
||||
setIsRegisterOpen(open);
|
||||
};
|
||||
|
||||
const handleChange = (event) => {
|
||||
const { value } = event.target;
|
||||
const newEmail = value?.toLowerCase() || value;
|
||||
setToInvite((prev) => ({
|
||||
...prev,
|
||||
email: newEmail,
|
||||
}));
|
||||
|
||||
const validation = newOrChangedCredentials.validate(
|
||||
{ email: newEmail },
|
||||
{ abortEarly: false }
|
||||
);
|
||||
|
||||
setErrors((prev) => {
|
||||
const updatedErrors = { ...prev };
|
||||
|
||||
if (validation.error) {
|
||||
updatedErrors.email = validation.error.details[0].message;
|
||||
} else {
|
||||
delete updatedErrors.email;
|
||||
}
|
||||
return updatedErrors;
|
||||
});
|
||||
};
|
||||
|
||||
const handleGetToken = async () => {
|
||||
await getInviteToken({ email: toInvite.email, role: toInvite.role });
|
||||
};
|
||||
const handleInviteMember = async () => {
|
||||
if (!toInvite.email) {
|
||||
setErrors((prev) => ({ ...prev, email: "Email is required." }));
|
||||
return;
|
||||
}
|
||||
setIsSendingInvite(true);
|
||||
if (!toInvite.role.includes("user") || !toInvite.role.includes("admin"))
|
||||
setToInvite((prev) => ({ ...prev, role: ["user"] }));
|
||||
|
||||
const { error } = newOrChangedCredentials.validate(
|
||||
{ email: toInvite.email },
|
||||
{
|
||||
abortEarly: false,
|
||||
}
|
||||
);
|
||||
|
||||
if (error) {
|
||||
setErrors((prev) => ({ ...prev, email: error.details[0].message }));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await networkService.sendInvitationToken({
|
||||
email: toInvite.email,
|
||||
role: toInvite.role,
|
||||
});
|
||||
closeInviteModal();
|
||||
createToast({
|
||||
body: "Member invited. They will receive an email with details on how to create their account.",
|
||||
});
|
||||
} catch (error) {
|
||||
createToast({
|
||||
body: error?.response?.data?.msg || error.message || "Unknown error.",
|
||||
});
|
||||
} finally {
|
||||
setIsSendingInvite(false);
|
||||
}
|
||||
};
|
||||
|
||||
const closeInviteModal = () => {
|
||||
setIsOpen(false);
|
||||
clearToken();
|
||||
setToInvite({ email: "", role: ["0"] });
|
||||
setErrors({});
|
||||
};
|
||||
|
||||
return (
|
||||
<TabPanel
|
||||
value="team"
|
||||
sx={{
|
||||
"& h1": {
|
||||
color: theme.palette.primary.contrastTextTertiary,
|
||||
},
|
||||
"& .MuiTable-root .MuiTableBody-root .MuiTableCell-root, & .MuiTable-root p + p":
|
||||
{
|
||||
color: theme.palette.primary.contrastTextSecondary,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Stack
|
||||
component="form"
|
||||
noValidate
|
||||
spellCheck="false"
|
||||
gap={SPACING_GAP}
|
||||
>
|
||||
<Typography component="h1">{t("teamPanel.teamMembers")}</Typography>
|
||||
<Stack
|
||||
direction="row"
|
||||
justifyContent="space-between"
|
||||
>
|
||||
<Stack
|
||||
direction="row"
|
||||
alignItems="flex-end"
|
||||
gap={theme.spacing(6)}
|
||||
sx={{ fontSize: 14 }}
|
||||
>
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
variant="group"
|
||||
filled={(filter === "all").toString()}
|
||||
onClick={() => setFilter("all")}
|
||||
>
|
||||
{t("teamPanel.filter.all")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="group"
|
||||
filled={(filter === "admin").toString()}
|
||||
onClick={() => setFilter("admin")}
|
||||
>
|
||||
{t("roles.superAdmin")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="group"
|
||||
filled={(filter === "user").toString()}
|
||||
onClick={() => setFilter("user")}
|
||||
>
|
||||
{t("teamPanel.filter.member")}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</Stack>
|
||||
|
||||
<AddTeamMember
|
||||
handleIsRegisterOpen={handleIsRegisterOpen}
|
||||
isRegisterOpen={isRegisterOpen}
|
||||
onMemberAdded={refreshTeamList}
|
||||
/>
|
||||
<AddMemberMenu
|
||||
handleInviteOpen={() => setIsOpen(true)}
|
||||
handleIsRegisterOpen={handleIsRegisterOpen}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<DataTable
|
||||
headers={headers}
|
||||
data={data}
|
||||
config={{
|
||||
emptyView: t("teamPanel.noMembers"),
|
||||
rowSX: {
|
||||
cursor: isSuperAdmin ? "pointer" : "default",
|
||||
},
|
||||
onRowClick: (row) => {
|
||||
if (isSuperAdmin) {
|
||||
navigate(`/account/team/${row.id}`);
|
||||
}
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
<GenericDialog
|
||||
title={t("teamPanel.inviteNewTeamMember")}
|
||||
description={t("teamPanel.inviteDescription")}
|
||||
open={isOpen}
|
||||
onClose={closeInviteModal}
|
||||
theme={theme}
|
||||
>
|
||||
<TextInput
|
||||
marginBottom={SPACING_GAP}
|
||||
type="email"
|
||||
id="input-team-member"
|
||||
placeholder={t("teamPanel.email")}
|
||||
value={toInvite.email}
|
||||
onChange={handleChange}
|
||||
error={errors.email ? true : false}
|
||||
helperText={t(errors.email)}
|
||||
/>
|
||||
<Select
|
||||
id="team-member-role"
|
||||
placeholder={t("teamPanel.selectRole")}
|
||||
isHidden={true}
|
||||
value={toInvite.role[0]}
|
||||
onChange={(event) =>
|
||||
setToInvite((prev) => ({
|
||||
...prev,
|
||||
role: [event.target.value],
|
||||
}))
|
||||
}
|
||||
items={[
|
||||
{ _id: "admin", name: t("roles.admin") },
|
||||
{ _id: "user", name: t("roles.teamMember") },
|
||||
]}
|
||||
/>
|
||||
{token && <Typography>{t("teamPanel.inviteLink")}</Typography>}
|
||||
{token && (
|
||||
<TextInput
|
||||
id="invite-token"
|
||||
value={token}
|
||||
/>
|
||||
)}
|
||||
<Stack
|
||||
direction="row"
|
||||
gap={theme.spacing(4)}
|
||||
mt={theme.spacing(8)}
|
||||
justifyContent="flex-end"
|
||||
>
|
||||
<Button
|
||||
loading={isSendingInvite}
|
||||
variant="contained" // CAIO_REVIEW
|
||||
color="error"
|
||||
onClick={closeInviteModal}
|
||||
>
|
||||
{t("teamPanel.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="accent"
|
||||
onClick={handleGetToken}
|
||||
loading={isSendingInvite}
|
||||
disabled={isDisabled}
|
||||
>
|
||||
{t("teamPanel.getToken")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="accent"
|
||||
onClick={handleInviteMember}
|
||||
loading={isSendingInvite}
|
||||
disabled={isDisabled}
|
||||
>
|
||||
{t("teamPanel.emailToken")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</GenericDialog>
|
||||
</TabPanel>
|
||||
);
|
||||
};
|
||||
|
||||
TeamPanel.propTypes = {
|
||||
// No props are being passed to this component, hence no specific PropTypes are defined.
|
||||
};
|
||||
|
||||
export default TeamPanel;
|
||||
@@ -0,0 +1,60 @@
|
||||
import Typography from "@mui/material/Typography";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Table } from "@/Components/v2/design-elements";
|
||||
import type { Header } from "@/Components/v2/design-elements/Table";
|
||||
import { useIsSuperAdmin } from "@/Hooks/useIsAdmin";
|
||||
import type { User } from "@/Types/User";
|
||||
|
||||
interface TeamTableProps {
|
||||
users: User[];
|
||||
}
|
||||
|
||||
export const TeamTable = ({ users }: TeamTableProps) => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const isSuperAdmin = useIsSuperAdmin();
|
||||
|
||||
const headers: Header<User>[] = [
|
||||
{
|
||||
id: "name",
|
||||
content: t("common.table.headers.name"),
|
||||
render: (row) => <Typography>{`${row.firstName} ${row.lastName}`}</Typography>,
|
||||
},
|
||||
{
|
||||
id: "email",
|
||||
content: t("pages.account.team.table.headers.email"),
|
||||
render: (row) => <Typography>{row.email}</Typography>,
|
||||
},
|
||||
{
|
||||
id: "role",
|
||||
content: t("pages.account.team.table.headers.role"),
|
||||
render: (row) => (
|
||||
<Typography>
|
||||
{row.role.map((r) => t(`common.auth.roles.${r}`)).join(", ")}
|
||||
</Typography>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "created",
|
||||
content: t("pages.account.team.table.headers.created"),
|
||||
render: (row) => (
|
||||
<Typography>{new Date(row.createdAt).toLocaleDateString()}</Typography>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const handleRowClick = (row: User) => {
|
||||
if (isSuperAdmin) {
|
||||
navigate(`/account/team/${row.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Table
|
||||
headers={headers}
|
||||
data={users}
|
||||
onRowClick={isSuperAdmin ? handleRowClick : undefined}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -1,99 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import PropTypes from "prop-types";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useSelector } from "react-redux";
|
||||
import { Box, Tab, useTheme } from "@mui/material";
|
||||
import CustomTabList from "@/Components/v1/Tab/index.jsx";
|
||||
import TabContext from "@mui/lab/TabContext";
|
||||
import ProfilePanel from "./components/ProfilePanel.jsx";
|
||||
import PasswordPanel from "./components/PasswordPanel.jsx";
|
||||
import TeamPanel from "./components/TeamPanel.jsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
/**
|
||||
* Account component renders a settings page with tabs for Profile, Password, and Team settings.
|
||||
* @param {string} [props.open] - Specifies the initially open tab: 'profile', 'password', or 'team'.
|
||||
* @returns {JSX.Element}
|
||||
*/
|
||||
const Account = ({ open = "profile" }) => {
|
||||
const theme = useTheme();
|
||||
const navigate = useNavigate();
|
||||
const [focusedTab, setFocusedTab] = useState(null); // Track focused tab
|
||||
const tab = open;
|
||||
const handleTabChange = (event, newTab) => {
|
||||
navigate(`/account/${newTab}`);
|
||||
};
|
||||
const { user } = useSelector((state) => state.auth);
|
||||
const { t } = useTranslation();
|
||||
|
||||
const requiredRoles = ["superadmin", "admin"];
|
||||
let tabList = [
|
||||
{ name: t("menu.profile"), value: "profile" },
|
||||
{ name: t("menu.password"), value: "password" },
|
||||
{ name: t("menu.team"), value: "team" },
|
||||
];
|
||||
|
||||
const hideTeams = !requiredRoles.some((role) => user.role.includes(role));
|
||||
|
||||
if (hideTeams) {
|
||||
tabList = [
|
||||
{ name: t("menu.profile"), value: "profile" },
|
||||
{ name: t("menu.password"), value: "password" },
|
||||
];
|
||||
}
|
||||
|
||||
// Remove password for demo
|
||||
if (user.role.includes("demo")) {
|
||||
tabList = [{ name: t("menu.profile"), value: "profile" }];
|
||||
}
|
||||
|
||||
const handleKeyDown = (event) => {
|
||||
const currentIndex = tabList.findIndex((item) => item.value === tab);
|
||||
if (event.key === "Tab") {
|
||||
const nextIndex = (currentIndex + 1) % tabList.length;
|
||||
setFocusedTab(tabList[nextIndex].value);
|
||||
} else if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
navigate(`/account/${focusedTab}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFocus = (tabName) => {
|
||||
setFocusedTab(tabName);
|
||||
};
|
||||
|
||||
return (
|
||||
<Box
|
||||
px={theme.spacing(20)}
|
||||
py={theme.spacing(12)}
|
||||
>
|
||||
<TabContext value={tab}>
|
||||
<CustomTabList
|
||||
value={tab}
|
||||
onChange={handleTabChange}
|
||||
aria-label="account tabs"
|
||||
>
|
||||
{tabList.map((item, index) => (
|
||||
<Tab
|
||||
label={item.name}
|
||||
key={index}
|
||||
value={item.value}
|
||||
onKeyDown={handleKeyDown}
|
||||
onFocus={() => handleFocus(item.value)}
|
||||
tabIndex={index}
|
||||
/>
|
||||
))}
|
||||
</CustomTabList>
|
||||
<ProfilePanel />
|
||||
{user.role.includes("superadmin") && <PasswordPanel />}
|
||||
{!hideTeams && <TeamPanel />}
|
||||
</TabContext>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
Account.propTypes = {
|
||||
open: PropTypes.oneOf(["profile", "password", "team"]),
|
||||
};
|
||||
|
||||
export default Account;
|
||||
@@ -0,0 +1,39 @@
|
||||
import { BasePage, Tabs, Tab } from "@/Components/v2/design-elements";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { TabProfile } from "./TabProfile";
|
||||
import { TabPassword } from "./TabPassword";
|
||||
import { TabTeam } from "./TabTeam";
|
||||
|
||||
interface AccountProps {
|
||||
open?: "profile" | "password" | "team";
|
||||
}
|
||||
|
||||
const TAB_MAP = {
|
||||
profile: 0,
|
||||
password: 1,
|
||||
team: 2,
|
||||
} as const;
|
||||
|
||||
const Account = ({ open = "profile" }: AccountProps) => {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState<number>(TAB_MAP[open]);
|
||||
|
||||
return (
|
||||
<BasePage>
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onChange={(_, newValue: number) => setActiveTab(newValue)}
|
||||
>
|
||||
<Tab label={t("pages.account.tabs.profile")} />
|
||||
<Tab label={t("pages.account.tabs.password")} />
|
||||
<Tab label={t("pages.account.tabs.team")} />
|
||||
</Tabs>
|
||||
{activeTab === 0 && <TabProfile />}
|
||||
{activeTab === 1 && <TabPassword />}
|
||||
{activeTab === 2 && <TabTeam />}
|
||||
</BasePage>
|
||||
);
|
||||
};
|
||||
|
||||
export default Account;
|
||||
@@ -2,7 +2,7 @@ import { Box, Button, Stack, Typography } from "@mui/material";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTheme } from "@emotion/react";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useNavigate, useLocation } from "react-router-dom";
|
||||
import { createToast } from "../../Utils/toastUtils.jsx";
|
||||
import { forgotPassword } from "../../Features/Auth/authSlice.js";
|
||||
import { Trans, useTranslation } from "react-i18next";
|
||||
@@ -17,6 +17,7 @@ const CheckEmail = () => {
|
||||
const navigate = useNavigate();
|
||||
const dispatch = useDispatch();
|
||||
const { t } = useTranslation();
|
||||
const location = useLocation();
|
||||
|
||||
const [email, setEmail] = useState();
|
||||
const [disabled, setDisabled] = useState(false);
|
||||
@@ -83,7 +84,9 @@ const CheckEmail = () => {
|
||||
|
||||
const handleNavigate = () => {
|
||||
sessionStorage.removeItem("email");
|
||||
navigate("/login");
|
||||
location.state?.from
|
||||
? navigate(location.state.from, { replace: true })
|
||||
: navigate("/login");
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -219,7 +222,11 @@ const CheckEmail = () => {
|
||||
>
|
||||
<Typography display="inline-block">
|
||||
<Trans
|
||||
i18nKey="auth.forgotPassword.links.login"
|
||||
i18nKey={
|
||||
location.state?.from === "/account/password"
|
||||
? "Go back to <a>Account Password</a>"
|
||||
: "auth.forgotPassword.links.login"
|
||||
}
|
||||
components={{
|
||||
a: (
|
||||
<Typography
|
||||
|
||||
@@ -1,234 +0,0 @@
|
||||
import { Box, Stack, Typography, Button } from "@mui/material";
|
||||
import { useTheme } from "@emotion/react";
|
||||
import { createToast } from "../../Utils/toastUtils.jsx";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { forgotPassword } from "../../Features/Auth/authSlice.js";
|
||||
import { useEffect, useState } from "react";
|
||||
import { newOrChangedCredentials } from "../../Validation/validation.js";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import TextInput from "@/Components/v1/Inputs/TextInput/index.jsx";
|
||||
import Logo from "@/assets/icons/checkmate-icon.svg?react";
|
||||
import Background from "@/assets/Images/background-grid.svg?react";
|
||||
import IconBox from "@/Components/v1/IconBox/index.jsx";
|
||||
import Icon from "@/Components/v1/Icon";
|
||||
import { Trans, useTranslation } from "react-i18next";
|
||||
import "./index.css";
|
||||
|
||||
const ForgotPassword = () => {
|
||||
const navigate = useNavigate();
|
||||
const dispatch = useDispatch();
|
||||
const theme = useTheme();
|
||||
|
||||
const { isLoading } = useSelector((state) => state.auth);
|
||||
const [errors, setErrors] = useState({});
|
||||
const [form, setForm] = useState({
|
||||
email: "",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const email = sessionStorage.getItem("email");
|
||||
email && setForm({ email: sessionStorage.getItem("email") });
|
||||
}, []);
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
|
||||
const { error } = newOrChangedCredentials.validate(form, { abortEarly: false });
|
||||
|
||||
if (error) {
|
||||
// validation errors
|
||||
const err =
|
||||
error.details && error.details.length > 0
|
||||
? error.details[0].message // FIXME: Possibly untranslated string
|
||||
: t("auth.common.errors.validation");
|
||||
setErrors({ email: err });
|
||||
createToast({
|
||||
body: err,
|
||||
});
|
||||
} else {
|
||||
const action = await dispatch(forgotPassword(form));
|
||||
if (action.payload.success) {
|
||||
sessionStorage.setItem("email", form.email);
|
||||
navigate("/check-email");
|
||||
createToast({
|
||||
body: t("auth.forgotPassword.toasts.sent").replace("<email/>", form.email),
|
||||
});
|
||||
} else {
|
||||
if (action.payload) {
|
||||
// dispatch errors
|
||||
createToast({
|
||||
body: action.payload.msg, // FIXME: Potentially untranslated string
|
||||
});
|
||||
} else {
|
||||
// unknown errors
|
||||
createToast({
|
||||
body: t("common.toasts.unknownError"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleChange = (event) => {
|
||||
const { value } = event.target;
|
||||
setForm({ email: value });
|
||||
|
||||
const { error } = newOrChangedCredentials.validate(
|
||||
{ email: value },
|
||||
{ abortEarly: false }
|
||||
);
|
||||
|
||||
if (error) setErrors({ email: error.details[0].message });
|
||||
else delete errors.email;
|
||||
};
|
||||
|
||||
const handleNavigate = () => {
|
||||
sessionStorage.removeItem("email");
|
||||
navigate("/login");
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack
|
||||
className="forgot-password-page auth"
|
||||
overflow="hidden"
|
||||
sx={{
|
||||
"& h1": {
|
||||
color: theme.palette.primary.main,
|
||||
fontWeight: 600,
|
||||
fontSize: 21,
|
||||
},
|
||||
"& p": {
|
||||
/* TODO font size from theme */
|
||||
fontSize: 14,
|
||||
color: theme.palette.primary.contrastTextSecondary,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
className="background-pattern-svg"
|
||||
sx={{
|
||||
"& svg g g:last-of-type path": {
|
||||
stroke: theme.palette.primary.lowContrast,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Background style={{ width: "100%" }} />
|
||||
</Box>
|
||||
<Stack
|
||||
direction="row"
|
||||
alignItems="center"
|
||||
px={theme.spacing(12)}
|
||||
gap={theme.spacing(4)}
|
||||
>
|
||||
<Logo style={{ borderRadius: theme.shape.borderRadius }} />
|
||||
<Typography sx={{ userSelect: "none" }}>{t("common.appName")}</Typography>
|
||||
</Stack>
|
||||
<Stack
|
||||
width="100%"
|
||||
maxWidth={600}
|
||||
flex={1}
|
||||
justifyContent="center"
|
||||
px={{ xs: theme.spacing(12), lg: theme.spacing(20) }}
|
||||
pb={theme.spacing(20)}
|
||||
mx="auto"
|
||||
sx={{
|
||||
"& > .MuiStack-root": {
|
||||
border: 1,
|
||||
borderRadius: theme.spacing(5),
|
||||
borderColor: theme.palette.primary.lowContrast,
|
||||
backgroundColor: theme.palette.primary.main,
|
||||
padding: {
|
||||
xs: theme.spacing(12),
|
||||
sm: theme.spacing(20),
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Stack
|
||||
gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }}
|
||||
alignItems="center"
|
||||
textAlign="center"
|
||||
>
|
||||
<Box>
|
||||
<Stack
|
||||
direction="row"
|
||||
justifyContent="center"
|
||||
>
|
||||
<IconBox
|
||||
height={48}
|
||||
width={48}
|
||||
minWidth={48}
|
||||
borderRadius={12}
|
||||
svgWidth={24}
|
||||
svgHeight={24}
|
||||
mb={theme.spacing(4)}
|
||||
>
|
||||
<Icon name="Key" />
|
||||
</IconBox>
|
||||
</Stack>
|
||||
<Typography component="h1">{t("auth.forgotPassword.heading")}</Typography>
|
||||
<Typography>{t("auth.forgotPassword.subheadings.stepOne")}</Typography>
|
||||
</Box>
|
||||
<Box
|
||||
component="form"
|
||||
width="95%"
|
||||
textAlign="left"
|
||||
noValidate
|
||||
spellCheck={false}
|
||||
onSubmit={handleSubmit}
|
||||
>
|
||||
<TextInput
|
||||
type="email"
|
||||
id="forgot-password-email-input"
|
||||
label={t("auth.common.inputs.email.label")}
|
||||
isRequired={true}
|
||||
placeholder={t("auth.common.inputs.email.placeholder")}
|
||||
value={form.email}
|
||||
onChange={handleChange}
|
||||
error={errors.email ? true : false}
|
||||
helperText={t(errors.email)} // Localization keys are in validation.js
|
||||
/>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="accent"
|
||||
loading={isLoading}
|
||||
disabled={errors.email !== undefined}
|
||||
onClick={handleSubmit}
|
||||
sx={{
|
||||
width: "100%",
|
||||
mt: theme.spacing(15),
|
||||
}}
|
||||
>
|
||||
{t("auth.common.navigation.continue")}
|
||||
</Button>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Stack>
|
||||
<Box
|
||||
textAlign="center"
|
||||
p={theme.spacing(12)}
|
||||
>
|
||||
<Typography display="inline-block">
|
||||
<Trans
|
||||
i18nKey="auth.forgotPassword.links.login"
|
||||
components={{
|
||||
a: (
|
||||
<Typography
|
||||
component="span"
|
||||
color={theme.palette.accent.main}
|
||||
ml={theme.spacing(2)}
|
||||
onClick={handleNavigate}
|
||||
sx={{ userSelect: "none" }}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export default ForgotPassword;
|
||||
@@ -1,22 +0,0 @@
|
||||
// Hook to avoid double submits and manage loading state
|
||||
import { useState, useCallback } from "react";
|
||||
|
||||
const useLoadingSubmit = () => {
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const executeSubmit = useCallback(
|
||||
async (submitFunction) => {
|
||||
if (submitting) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
return await submitFunction();
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
},
|
||||
[submitting]
|
||||
);
|
||||
|
||||
return { submitting, executeSubmit };
|
||||
};
|
||||
|
||||
export default useLoadingSubmit;
|
||||
@@ -1,19 +0,0 @@
|
||||
import { useState } from "react";
|
||||
|
||||
const useLoginForm = () => {
|
||||
const [form, setForm] = useState({
|
||||
email: "",
|
||||
password: "",
|
||||
});
|
||||
const onChange = (e) => {
|
||||
let { name, value } = e.target;
|
||||
if (name === "email") {
|
||||
value = value.toLowerCase();
|
||||
}
|
||||
const updatedForm = { ...form, [name]: value };
|
||||
setForm(updatedForm);
|
||||
};
|
||||
return [form, onChange];
|
||||
};
|
||||
|
||||
export default useLoginForm;
|
||||
@@ -1,40 +0,0 @@
|
||||
import { useDispatch } from "react-redux";
|
||||
import { login } from "../../../../Features/Auth/authSlice.js";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { createToast } from "../../../../Utils/toastUtils.jsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
const useLoginSubmit = () => {
|
||||
const dispatch = useDispatch();
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const handleLoginSubmit = async (form, setErrors) => {
|
||||
const action = await dispatch(login(form));
|
||||
if (action.payload.success) {
|
||||
navigate("/uptime");
|
||||
createToast({
|
||||
body: t("auth.login.toasts.success"),
|
||||
});
|
||||
} else {
|
||||
if (action.payload) {
|
||||
if (action.payload.msg === "Incorrect password")
|
||||
setErrors({
|
||||
password: t("auth.login.errors.password.incorrect"),
|
||||
});
|
||||
// dispatch errors
|
||||
createToast({
|
||||
body: t("auth.login.toasts.incorrectPassword"),
|
||||
});
|
||||
} else {
|
||||
// unknown errors
|
||||
createToast({
|
||||
body: t("common.toasts.unknownError"),
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
return [handleLoginSubmit];
|
||||
};
|
||||
|
||||
export default useLoginSubmit;
|
||||
@@ -1,31 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { loginCredentials } from "../../../../Validation/validation.js";
|
||||
|
||||
const useValidateLoginForm = () => {
|
||||
const [errors, setErrors] = useState({
|
||||
email: "",
|
||||
password: "",
|
||||
});
|
||||
const validateField = (name, value) => {
|
||||
const { error } = loginCredentials.validate({ [name]: value });
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
[name]: error?.details?.[0]?.message || "",
|
||||
}));
|
||||
};
|
||||
const validateForm = (form) => {
|
||||
const { error } = loginCredentials.validate(form, { abortEarly: false });
|
||||
if (error) {
|
||||
const formErrors = {};
|
||||
for (const err of error.details) {
|
||||
formErrors[err.path[0]] = err.message;
|
||||
}
|
||||
setErrors(formErrors);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
return [errors, setErrors, validateField, validateForm];
|
||||
};
|
||||
|
||||
export default useValidateLoginForm;
|
||||
@@ -1,102 +0,0 @@
|
||||
// Components
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Button from "@mui/material/Button";
|
||||
import TextInput from "@/Components/v1/Inputs/TextInput/index.jsx";
|
||||
import { PasswordEndAdornment } from "@/Components/v1/Inputs/TextInput/Adornments/index.jsx";
|
||||
import TextLink from "@/Components/v1/TextLink/index.jsx";
|
||||
import AuthPageWrapper from "../components/AuthPageWrapper.jsx";
|
||||
// Utils
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import useLoginForm from "./hooks/useLoginForm.jsx";
|
||||
import useValidateLoginForm from "./hooks/useValidateLoginForm.jsx";
|
||||
import useLoginSubmit from "./hooks/useLoginSubmit.jsx";
|
||||
import useLoadingSubmit from "./hooks/useLoadingSubmit.jsx";
|
||||
|
||||
const Login = () => {
|
||||
// Hooks
|
||||
const { t } = useTranslation();
|
||||
const theme = useTheme();
|
||||
const [form, onChange] = useLoginForm();
|
||||
const [errors, setErrors, validateField, validateForm] = useValidateLoginForm();
|
||||
const [handleLoginSubmit] = useLoginSubmit();
|
||||
const { submitting, executeSubmit } = useLoadingSubmit();
|
||||
|
||||
// Handlers
|
||||
const handleChange = (e) => {
|
||||
onChange(e);
|
||||
validateField(e.target.name, e.target.value);
|
||||
};
|
||||
const onSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
const isValid = validateForm(form);
|
||||
if (!isValid) return;
|
||||
await executeSubmit(() => handleLoginSubmit(form, setErrors));
|
||||
};
|
||||
return (
|
||||
<AuthPageWrapper
|
||||
welcome={t("auth.login.welcome")}
|
||||
heading={t("auth.login.heading")}
|
||||
>
|
||||
<Stack
|
||||
component="form"
|
||||
width="100%"
|
||||
padding={theme.spacing(8)}
|
||||
gap={theme.spacing(12)}
|
||||
onSubmit={onSubmit}
|
||||
sx={{
|
||||
width: {
|
||||
sm: "80%",
|
||||
md: "70%",
|
||||
lg: "65%",
|
||||
xl: "65%",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<TextInput
|
||||
type="email"
|
||||
name="email"
|
||||
label={t("auth.common.inputs.email.label")}
|
||||
placeholder={t("auth.common.inputs.email.placeholder")}
|
||||
autoComplete="email"
|
||||
value={form.email}
|
||||
onChange={handleChange}
|
||||
error={errors.email ? true : false}
|
||||
helperText={errors.email ? t(errors.email) : ""} // Localization keys are in validation.js
|
||||
/>
|
||||
<TextInput
|
||||
type="password"
|
||||
name="password"
|
||||
label={t("auth.common.inputs.password.label")}
|
||||
placeholder="••••••••••"
|
||||
autoComplete="current-password"
|
||||
value={form.password}
|
||||
onChange={handleChange}
|
||||
error={errors.password ? true : false}
|
||||
helperText={errors.password ? t(errors.password) : ""} // Localization keys are in validation.js
|
||||
endAdornment={<PasswordEndAdornment />}
|
||||
/>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="accent"
|
||||
type="submit"
|
||||
sx={{ width: "100%", alignSelf: "center", fontWeight: 700 }}
|
||||
loading={submitting}
|
||||
>
|
||||
Login
|
||||
</Button>
|
||||
</Stack>
|
||||
<TextLink
|
||||
text={t("auth.login.links.forgotPassword")}
|
||||
linkText={t("auth.login.links.forgotPasswordLink")}
|
||||
href="/forgot-password"
|
||||
/>
|
||||
<TextLink
|
||||
text={t("auth.login.links.register")}
|
||||
linkText={t("auth.login.links.registerLink")}
|
||||
href="/register"
|
||||
/>
|
||||
</AuthPageWrapper>
|
||||
);
|
||||
};
|
||||
export default Login;
|
||||
@@ -0,0 +1,95 @@
|
||||
import { BaseAuthPage, TextLink } from "@/Components/v2/design-elements";
|
||||
import { Button, TextField } from "@/Components/v2/inputs";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod/dist/zod.js";
|
||||
import { useLoginForm } from "@/Hooks/useLoginForm";
|
||||
import type { LoginFormData } from "@/Validation/login";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { setAuthState } from "@/Features/Auth/authSlice";
|
||||
import { usePost } from "@/Hooks/UseApi";
|
||||
|
||||
const LoginPage = () => {
|
||||
const { t } = useTranslation();
|
||||
const dispatch = useDispatch();
|
||||
const navigate = useNavigate();
|
||||
const { post, loading } = usePost();
|
||||
|
||||
const { schema, defaults } = useLoginForm();
|
||||
|
||||
const { control, handleSubmit } = useForm<LoginFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: defaults,
|
||||
});
|
||||
|
||||
const onSubmit = async (data: LoginFormData) => {
|
||||
if (loading) return;
|
||||
|
||||
const result = await post("/auth/login", data);
|
||||
|
||||
if (result?.success) {
|
||||
dispatch(setAuthState(result));
|
||||
navigate("/uptime");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<BaseAuthPage
|
||||
component="form"
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
title={t("pages.auth.login.title")}
|
||||
subtitle={t("pages.auth.login.subtitle")}
|
||||
>
|
||||
<Controller
|
||||
name="email"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
fieldLabel={t("pages.auth.common.form.option.email.label")}
|
||||
placeholder={t("pages.auth.common.form.option.email.placeholder")}
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error ? t(fieldState.error.message ?? "") : ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="password"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
type="password"
|
||||
fieldLabel={t("pages.auth.common.form.option.password.label")}
|
||||
placeholder={t("pages.auth.common.form.option.password.placeholder")}
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error ? t(fieldState.error.message ?? "") : ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Button
|
||||
variant="contained"
|
||||
type="submit"
|
||||
loading={loading}
|
||||
>
|
||||
{t("pages.auth.login.submit")}
|
||||
</Button>
|
||||
<TextLink
|
||||
alignSelf={"center"}
|
||||
text={t("pages.auth.login.links.forgotPassword.text")}
|
||||
linkText={t("pages.auth.login.links.forgotPassword.linkText")}
|
||||
href="/forgot-password"
|
||||
/>
|
||||
<TextLink
|
||||
alignSelf={"center"}
|
||||
text={t("pages.auth.login.links.register.text")}
|
||||
linkText={t("pages.auth.login.links.register.linkText")}
|
||||
href="/register"
|
||||
/>
|
||||
</BaseAuthPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoginPage;
|
||||
@@ -0,0 +1,69 @@
|
||||
import { Button, TextField } from "@/Components/v2/inputs";
|
||||
import { BaseAuthPage, TextLink } from "@/Components/v2/design-elements";
|
||||
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod/dist/zod.js";
|
||||
import { useRecoveryForm } from "@/Hooks/useRecoveryForm";
|
||||
import type { RecoveryFormData } from "@/Validation/recovery";
|
||||
import { usePost } from "@/Hooks/UseApi";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
const ForgotPasswordPage = () => {
|
||||
const { t } = useTranslation();
|
||||
const { post, loading } = usePost();
|
||||
|
||||
const { schema, defaults } = useRecoveryForm();
|
||||
|
||||
const { control, handleSubmit } = useForm<RecoveryFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: defaults,
|
||||
});
|
||||
|
||||
const onSubmit = async (data: RecoveryFormData) => {
|
||||
if (loading) return;
|
||||
|
||||
const result = await post("/auth/recovery/request", data);
|
||||
|
||||
if (result?.success) {
|
||||
// Navigate to Check email page
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<BaseAuthPage
|
||||
component="form"
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
title={t("pages.auth.forgotPassword.title")}
|
||||
subtitle={t("pages.auth.forgotPassword.subtitle")}
|
||||
>
|
||||
<Controller
|
||||
name="email"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
fieldLabel={t("pages.auth.common.form.option.email.label")}
|
||||
placeholder={t("pages.auth.common.form.option.email.placeholder")}
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error ? t(fieldState.error.message ?? "") : ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Button
|
||||
variant="contained"
|
||||
type="submit"
|
||||
loading={loading}
|
||||
>
|
||||
{t("pages.auth.forgotPassword.submit")}
|
||||
</Button>
|
||||
<TextLink
|
||||
alignSelf={"center"}
|
||||
text={t("pages.auth.forgotPassword.links.login.text")}
|
||||
linkText={t("pages.auth.forgotPassword.links.login.linkText")}
|
||||
href="/login"
|
||||
/>
|
||||
</BaseAuthPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default ForgotPasswordPage;
|
||||
@@ -1,330 +0,0 @@
|
||||
// Components
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import TextInput from "@/Components/v1/Inputs/TextInput/index.jsx";
|
||||
import Button from "@mui/material/Button";
|
||||
import Box from "@mui/material/Box";
|
||||
import PasswordTooltip from "../components/PasswordTooltip.jsx";
|
||||
|
||||
// Utils
|
||||
import { useTheme } from "@emotion/react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { networkService } from "../../../main.jsx";
|
||||
import { newOrChangedCredentials } from "../../../Validation/validation.js";
|
||||
import { register } from "../../../Features/Auth/authSlice.js";
|
||||
import AuthPageWrapper from "../components/AuthPageWrapper.jsx";
|
||||
import { createToast } from "../../../Utils/toastUtils.jsx";
|
||||
import PropTypes from "prop-types";
|
||||
|
||||
const getFeedbackStatus = (form, errors, field, criteria) => {
|
||||
const fieldErrors = errors?.[field];
|
||||
const isFieldEmpty = form?.[field]?.length === 0;
|
||||
const hasError = fieldErrors?.includes(criteria) || fieldErrors?.includes("empty");
|
||||
const isCorrect = !isFieldEmpty && !hasError;
|
||||
|
||||
if (isCorrect) {
|
||||
return "success";
|
||||
} else if (hasError) {
|
||||
return "error";
|
||||
} else {
|
||||
return "info";
|
||||
}
|
||||
};
|
||||
|
||||
const Register = ({ superAdminExists }) => {
|
||||
// Redux
|
||||
const { isLoading } = useSelector((state) => state.auth);
|
||||
|
||||
// Local state
|
||||
const [form, setForm] = useState({
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
email: "",
|
||||
password: "",
|
||||
confirm: "",
|
||||
role: [],
|
||||
teamId: "",
|
||||
});
|
||||
|
||||
const [errors, setErrors] = useState({});
|
||||
const [feedback, setFeedback] = useState({});
|
||||
|
||||
// Hooks
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const { token } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const dispatch = useDispatch();
|
||||
|
||||
// Effects
|
||||
useEffect(() => {
|
||||
const fetchInvite = async () => {
|
||||
if (token !== undefined) {
|
||||
try {
|
||||
const res = await networkService.verifyInvitationToken(token);
|
||||
const invite = res.data.data;
|
||||
const { email } = invite;
|
||||
setForm((prevForm) => {
|
||||
if (!prevForm.email) {
|
||||
return { ...prevForm, email };
|
||||
}
|
||||
return prevForm;
|
||||
});
|
||||
} catch (error) {
|
||||
navigate("/register", { replace: true });
|
||||
}
|
||||
}
|
||||
};
|
||||
fetchInvite();
|
||||
}, [form, token, navigate]);
|
||||
|
||||
// Handlers
|
||||
const onChange = (e) => {
|
||||
let { name, value } = e.target;
|
||||
if (name === "email") value = value.toLowerCase();
|
||||
const updatedForm = { ...form, [name]: value };
|
||||
|
||||
const { error } = newOrChangedCredentials.validate(
|
||||
{ [name]: value },
|
||||
{ abortEarly: false, context: { password: form.password } }
|
||||
);
|
||||
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
[name]: error?.details?.[0]?.message || "",
|
||||
}));
|
||||
|
||||
setForm(updatedForm);
|
||||
};
|
||||
|
||||
const onPasswordChange = (e) => {
|
||||
const { name, value } = e.target;
|
||||
const updatedForm = { ...form, [name]: value };
|
||||
setForm(updatedForm);
|
||||
const validateValue = { [name]: value };
|
||||
const validateOptions = { abortEarly: false, context: { password: form.password } };
|
||||
if (name === "password" && form.confirm.length > 0) {
|
||||
validateValue.confirm = form.confirm;
|
||||
validateOptions.context = { password: value };
|
||||
} else if (name === "confirm") {
|
||||
validateValue.password = form.password;
|
||||
}
|
||||
const { error } = newOrChangedCredentials.validate(validateValue, validateOptions);
|
||||
|
||||
const pwdErrors = error?.details.map((error) => ({
|
||||
path: error.path[0],
|
||||
type: error.type,
|
||||
}));
|
||||
|
||||
const errorsByPath =
|
||||
pwdErrors &&
|
||||
pwdErrors.reduce((acc, { path, type }) => {
|
||||
if (!acc[path]) {
|
||||
acc[path] = [];
|
||||
}
|
||||
acc[path].push(type);
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
const oldErrors = { ...errors };
|
||||
if (name === "password") {
|
||||
oldErrors.password = undefined;
|
||||
} else if (name === "confirm") {
|
||||
oldErrors.confirm = undefined;
|
||||
}
|
||||
const newErrors = { ...oldErrors, ...errorsByPath };
|
||||
|
||||
setErrors(newErrors);
|
||||
|
||||
const newFeedback = {
|
||||
length: getFeedbackStatus(updatedForm, errorsByPath, "password", "string.min"),
|
||||
special: getFeedbackStatus(updatedForm, errorsByPath, "password", "special"),
|
||||
number: getFeedbackStatus(updatedForm, errorsByPath, "password", "number"),
|
||||
uppercase: getFeedbackStatus(updatedForm, errorsByPath, "password", "uppercase"),
|
||||
lowercase: getFeedbackStatus(updatedForm, errorsByPath, "password", "lowercase"),
|
||||
confirm: getFeedbackStatus(updatedForm, errorsByPath, "confirm", "different"),
|
||||
};
|
||||
|
||||
setFeedback(newFeedback);
|
||||
};
|
||||
|
||||
const onSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
const toSubmit = {
|
||||
...form,
|
||||
role: superAdminExists ? form.role : ["superadmin"],
|
||||
inviteToken: token ? token : "",
|
||||
};
|
||||
|
||||
const { error } = newOrChangedCredentials.validate(toSubmit, {
|
||||
abortEarly: false,
|
||||
context: { password: form.password },
|
||||
});
|
||||
|
||||
if (error) {
|
||||
const formErrors = {};
|
||||
for (const err of error.details) {
|
||||
formErrors[err.path[0]] = err.message;
|
||||
}
|
||||
setErrors(formErrors);
|
||||
return;
|
||||
}
|
||||
|
||||
delete toSubmit.confirm;
|
||||
|
||||
const action = await dispatch(register({ user: toSubmit, token }));
|
||||
if (action.payload.success) {
|
||||
navigate("/uptime");
|
||||
createToast({
|
||||
body: t("auth.registration.toasts.success"),
|
||||
});
|
||||
} else {
|
||||
if (action.payload) {
|
||||
createToast({
|
||||
body: action.payload.msg,
|
||||
});
|
||||
} else {
|
||||
createToast({
|
||||
body: t("common.toasts.unknownError"),
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthPageWrapper
|
||||
heading={t("auth.registration.heading.user")}
|
||||
welcome={t("auth.registration.welcome")}
|
||||
>
|
||||
<Stack
|
||||
component="form"
|
||||
width="100%"
|
||||
padding={theme.spacing(8)}
|
||||
gap={theme.spacing(8)}
|
||||
onSubmit={onSubmit}
|
||||
sx={{
|
||||
width: {
|
||||
sm: "80%",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Typography variant="h2">
|
||||
{superAdminExists
|
||||
? t("auth.registration.description.user")
|
||||
: t("auth.registration.description.superAdmin")}
|
||||
</Typography>
|
||||
<Stack
|
||||
direction={{ xs: "column", lg: "row" }}
|
||||
justifyContent="space-between"
|
||||
gap={theme.spacing(4)}
|
||||
>
|
||||
<TextInput
|
||||
name="firstName"
|
||||
sx={{ flex: 1 }}
|
||||
label={t("auth.common.inputs.firstName.label")}
|
||||
width="100%"
|
||||
gap={theme.spacing(4)}
|
||||
isRequired={true}
|
||||
placeholder={t("auth.common.inputs.firstName.placeholder")}
|
||||
autoComplete="given-name"
|
||||
value={form.firstName}
|
||||
onChange={onChange}
|
||||
error={errors.firstName ? true : false}
|
||||
helperText={errors.firstName ? t(errors.firstName) : ""}
|
||||
/>
|
||||
<TextInput
|
||||
name="lastName"
|
||||
label={t("auth.common.inputs.lastName.label")}
|
||||
sx={{ flex: 1 }}
|
||||
width="100%"
|
||||
gap={theme.spacing(4)}
|
||||
isRequired={true}
|
||||
placeholder={t("auth.common.inputs.lastName.placeholder")}
|
||||
autoComplete="family-name"
|
||||
value={form.lastName}
|
||||
onChange={onChange}
|
||||
error={errors.lastName ? true : false}
|
||||
helperText={errors.lastName ? t(errors.lastName) : ""} // Localization keys are in validation.js
|
||||
/>
|
||||
</Stack>
|
||||
<TextInput
|
||||
type="email"
|
||||
name="email"
|
||||
gap={theme.spacing(4)}
|
||||
label={t("auth.common.inputs.email.label")}
|
||||
isRequired={true}
|
||||
placeholder={t("auth.common.inputs.email.placeholder")}
|
||||
autoComplete="email"
|
||||
value={form.email}
|
||||
onInput={(e) => (e.target.value = e.target.value.toLowerCase())}
|
||||
onChange={onChange}
|
||||
error={errors.email ? true : false}
|
||||
helperText={errors.email ? t(errors.email) : ""} // Localization keys are in validation.js
|
||||
/>
|
||||
<PasswordTooltip
|
||||
feedback={feedback}
|
||||
form={form}
|
||||
>
|
||||
<Box>
|
||||
<TextInput
|
||||
type="password"
|
||||
id="register-password-input"
|
||||
name="password"
|
||||
label={t("auth.common.inputs.password.label")}
|
||||
gap={theme.spacing(4)}
|
||||
isRequired={true}
|
||||
placeholder="••••••••••"
|
||||
autoComplete="current-password"
|
||||
value={form.password}
|
||||
onChange={onPasswordChange}
|
||||
error={errors.password && errors.password[0] ? true : false}
|
||||
helperText={
|
||||
errors.password === "auth.common.inputs.password.errors.empty"
|
||||
? t(errors.password)
|
||||
: ""
|
||||
}
|
||||
/>
|
||||
</Box>
|
||||
</PasswordTooltip>
|
||||
<TextInput
|
||||
type="password"
|
||||
id="register-confirm-input"
|
||||
name="confirm"
|
||||
label={t("auth.common.inputs.passwordConfirm.label")}
|
||||
gap={theme.spacing(4)}
|
||||
isRequired={true}
|
||||
placeholder={t("auth.common.inputs.passwordConfirm.placeholder")}
|
||||
autoComplete="current-password"
|
||||
value={form.confirm}
|
||||
onChange={onPasswordChange}
|
||||
marginBottom={theme.spacing(4)}
|
||||
error={errors.confirm && errors.confirm[0] ? true : false}
|
||||
/>
|
||||
<Button
|
||||
disabled={isLoading}
|
||||
variant="contained"
|
||||
color="accent"
|
||||
type="submit"
|
||||
sx={{
|
||||
width: "100%",
|
||||
alignSelf: "center",
|
||||
fontWeight: 700,
|
||||
mt: theme.spacing(10),
|
||||
}}
|
||||
>
|
||||
{t("auth.common.navigation.continue")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</AuthPageWrapper>
|
||||
);
|
||||
};
|
||||
|
||||
Register.propTypes = {
|
||||
superAdminExists: PropTypes.bool,
|
||||
};
|
||||
|
||||
export default Register;
|
||||
@@ -0,0 +1,162 @@
|
||||
import { BaseAuthPage } from "@/Components/v2/design-elements";
|
||||
import { Button, TextField } from "@/Components/v2/inputs";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod/dist/zod.js";
|
||||
import { useRegisterForm } from "@/Hooks/useRegisterForm";
|
||||
import type { RegisterFormData } from "@/Validation/register";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { usePost } from "@/Hooks/UseApi";
|
||||
import { setAuthState } from "@/Features/Auth/authSlice";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import type { AuthResponse } from "@/Types/User";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
interface RegisterPayload {
|
||||
user: Omit<RegisterFormData, "confirm">;
|
||||
token?: string;
|
||||
}
|
||||
|
||||
interface InviteVerifyResponse {
|
||||
email: string;
|
||||
}
|
||||
|
||||
const RegisterPage = () => {
|
||||
const { t } = useTranslation();
|
||||
const { schema, defaults } = useRegisterForm();
|
||||
const { post, loading } = usePost<RegisterPayload, AuthResponse>();
|
||||
const dispatch = useDispatch();
|
||||
const navigate = useNavigate();
|
||||
const { token } = useParams<{ token?: string }>();
|
||||
|
||||
const { post: verifyToken } = usePost<{ token: string }, InviteVerifyResponse>();
|
||||
const hasVerified = useRef(false);
|
||||
|
||||
const { control, handleSubmit, setError, reset } = useForm<RegisterFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: defaults,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!token || hasVerified.current) return;
|
||||
hasVerified.current = true;
|
||||
|
||||
verifyToken("/invite/verify", { token }).then((result) => {
|
||||
if (result?.success && result?.data) {
|
||||
reset({
|
||||
...defaults,
|
||||
email: result.data.email ?? "",
|
||||
});
|
||||
} else {
|
||||
navigate("/register", { replace: true });
|
||||
}
|
||||
});
|
||||
}, [token]);
|
||||
|
||||
const onSubmit = async (data: RegisterFormData) => {
|
||||
if (loading) return;
|
||||
|
||||
const { confirm, ...userData } = data;
|
||||
const payload: RegisterPayload = { user: userData };
|
||||
if (token) {
|
||||
payload.token = token;
|
||||
}
|
||||
const result = await post("/auth/register", payload);
|
||||
|
||||
if (result?.success) {
|
||||
dispatch(setAuthState(result));
|
||||
navigate("/uptime");
|
||||
} else if (result?.msg) {
|
||||
if (result.msg.toLowerCase().includes("email")) {
|
||||
setError("email", { message: result.msg });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<BaseAuthPage
|
||||
component="form"
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
title={t("pages.auth.register.title")}
|
||||
subtitle={t("pages.auth.register.subtitle")}
|
||||
>
|
||||
<Controller
|
||||
name="firstName"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
fieldLabel={t("pages.auth.register.form.option.name.label")}
|
||||
placeholder={t("pages.auth.register.form.option.name.placeholder")}
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="lastName"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
fieldLabel={t("pages.auth.register.form.option.surname.label")}
|
||||
placeholder={t("pages.auth.register.form.option.surname.placeholder")}
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="email"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
disabled={!!token}
|
||||
fieldLabel={t("pages.auth.common.form.option.email.label")}
|
||||
placeholder={t("pages.auth.common.form.option.email.placeholder")}
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="password"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
type="password"
|
||||
fieldLabel={t("pages.auth.common.form.option.password.label")}
|
||||
placeholder={t("pages.auth.common.form.option.password.placeholder")}
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="confirm"
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
type="password"
|
||||
fieldLabel={t("pages.auth.common.form.option.confirmPassword.label")}
|
||||
placeholder={t("pages.auth.common.form.option.password.placeholder")}
|
||||
error={!!fieldState.error}
|
||||
helperText={fieldState.error?.message ?? ""}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Button
|
||||
variant="contained"
|
||||
type="submit"
|
||||
loading={loading}
|
||||
>
|
||||
{t("pages.auth.register.submit")}
|
||||
</Button>
|
||||
</BaseAuthPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default RegisterPage;
|
||||
@@ -1,107 +0,0 @@
|
||||
import Background from "@/assets/Images/background-grid.svg?react";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import AuthHeader from "./AuthHeader.jsx";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import Logo from "@/assets/icons/checkmate-icon.svg?react";
|
||||
import PropTypes from "prop-types";
|
||||
|
||||
const AuthPageWrapper = ({ children, heading, welcome }) => {
|
||||
const theme = useTheme();
|
||||
return (
|
||||
<Stack
|
||||
gap={theme.spacing(10)}
|
||||
minHeight="100vh"
|
||||
position="relative"
|
||||
backgroundColor={theme.palette.primary.main}
|
||||
sx={{ overflow: "hidden" }}
|
||||
>
|
||||
<AuthHeader hideLogo={true} />
|
||||
<Box
|
||||
sx={{
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: "0%",
|
||||
transform: "translate(-40%, -40%)",
|
||||
zIndex: 0,
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
"& svg g g:last-of-type path": {
|
||||
stroke: theme.palette.primary.lowContrast,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Background style={{ width: "100%" }} />
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
position: "absolute",
|
||||
bottom: 0,
|
||||
right: 0,
|
||||
transform: "translate(45%, 55%)",
|
||||
zIndex: 0,
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
"& svg g g:last-of-type path": {
|
||||
stroke: theme.palette.primary.lowContrast,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Background style={{ width: "100%" }} />
|
||||
</Box>
|
||||
<Stack
|
||||
backgroundColor={theme.palette.primary.main}
|
||||
sx={{
|
||||
borderRadius: theme.spacing(8),
|
||||
boxShadow: theme.palette.tertiary.cardShadow,
|
||||
margin: "auto",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing(10),
|
||||
padding: theme.spacing(20),
|
||||
zIndex: 1,
|
||||
position: "relative",
|
||||
width: {
|
||||
sm: "60%",
|
||||
md: "50%",
|
||||
lg: "40%",
|
||||
xl: "30%",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
mb={theme.spacing(10)}
|
||||
mt={theme.spacing(5)}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: { xs: 60, sm: 70, md: 80 },
|
||||
}}
|
||||
/>
|
||||
<Logo style={{ width: "100%", height: "100%" }} />
|
||||
</Box>
|
||||
<Stack
|
||||
mb={theme.spacing(4)}
|
||||
textAlign="center"
|
||||
>
|
||||
<Typography
|
||||
variant="h1"
|
||||
mb={theme.spacing(2)}
|
||||
>
|
||||
{welcome}
|
||||
</Typography>
|
||||
<Typography variant="h1">{heading}</Typography>
|
||||
</Stack>
|
||||
{children}
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export default AuthPageWrapper;
|
||||
|
||||
AuthPageWrapper.propTypes = {
|
||||
children: PropTypes.node,
|
||||
heading: PropTypes.node,
|
||||
welcome: PropTypes.node,
|
||||
};
|
||||
+13
-9
@@ -1,26 +1,32 @@
|
||||
// Components
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Stack, { type StackProps } from "@mui/material/Stack";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import Logo from "@/assets/icons/checkmate-icon.svg?react";
|
||||
import LanguageSelector from "@/Components/LanguageSelector.jsx";
|
||||
import ThemeSwitch from "@/Components/v1/ThemeSwitch/index.jsx";
|
||||
import { LanguageSelector, SwitchTheme } from "@/Components/v2/inputs";
|
||||
|
||||
// Utils
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
const AuthHeader = ({ hideLogo = false }) => {
|
||||
interface HeaderAuthControlsProps extends StackProps {
|
||||
hideLogo?: boolean;
|
||||
}
|
||||
|
||||
export const HeaderAuthControls = ({
|
||||
hideLogo = false,
|
||||
...stackProps
|
||||
}: HeaderAuthControlsProps) => {
|
||||
// Hooks
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Stack
|
||||
width={"100%"}
|
||||
direction="row"
|
||||
alignItems="center"
|
||||
justifyContent="space-between"
|
||||
px={theme.spacing(12)}
|
||||
gap={theme.spacing(4)}
|
||||
{...stackProps}
|
||||
>
|
||||
<Stack
|
||||
direction="row"
|
||||
@@ -40,10 +46,8 @@ const AuthHeader = ({ hideLogo = false }) => {
|
||||
alignItems="center"
|
||||
>
|
||||
<LanguageSelector />
|
||||
<ThemeSwitch />
|
||||
<SwitchTheme />
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export default AuthHeader;
|
||||
@@ -0,0 +1,132 @@
|
||||
import {
|
||||
Table,
|
||||
Pagination,
|
||||
ValueLabel,
|
||||
StatusLabel,
|
||||
} from "@/Components/v2/design-elements";
|
||||
import Box from "@mui/material/Box";
|
||||
import type { Header } from "@/Components/v2/design-elements/Table";
|
||||
import type { Monitor, MonitorStatus } from "@/Types/Monitor";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { formatDateWithTz } from "@/Utils/TimeUtils";
|
||||
import { useNavigate } from "react-router";
|
||||
import type { Check } from "@/Types/Check";
|
||||
import type { RootState } from "@/Types/state";
|
||||
import { useSelector } from "react-redux";
|
||||
|
||||
export const ChecksTable = ({
|
||||
monitors,
|
||||
checks,
|
||||
checksCount,
|
||||
page,
|
||||
setPage,
|
||||
rowsPerPage,
|
||||
setRowsPerPage,
|
||||
}: {
|
||||
monitors: Monitor[] | null;
|
||||
checks: Check[];
|
||||
checksCount: number;
|
||||
page: number;
|
||||
setPage: (page: number) => void;
|
||||
rowsPerPage: number;
|
||||
setRowsPerPage: (rowsPerPage: number) => void;
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const uiTimezone = useSelector((state: RootState) => state.ui.timezone);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const getHeaders = (t: Function, uiTimezone: string) => {
|
||||
const headers: Header<Check>[] = [
|
||||
{
|
||||
id: "monitorName",
|
||||
content: t("common.table.headers.monitor"),
|
||||
render: (row) => {
|
||||
return (
|
||||
monitors?.find((monitor) => monitor.id === row.metadata.monitorId)?.name ||
|
||||
"N/A"
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
content: "Status",
|
||||
render: (row) => {
|
||||
return <StatusLabel status={row.status as MonitorStatus} />;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "date",
|
||||
content: t("common.table.headers.dateTime"),
|
||||
render: (row) => {
|
||||
return formatDateWithTz(
|
||||
row.createdAt,
|
||||
"ddd, MMMM D, YYYY, HH:mm A",
|
||||
uiTimezone
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "statusCode",
|
||||
content: t("pages.checks.table.headers.statusCode"),
|
||||
render: (row) => {
|
||||
const code = row.statusCode;
|
||||
if (!code) return "N/A";
|
||||
const value = code < 300 ? "positive" : code < 400 ? "neutral" : "negative";
|
||||
return (
|
||||
<ValueLabel
|
||||
value={value}
|
||||
text={String(code)}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "message",
|
||||
content: t("common.table.headers.message"),
|
||||
render: (row) => {
|
||||
return row.message || "N/A";
|
||||
},
|
||||
},
|
||||
];
|
||||
return headers;
|
||||
};
|
||||
|
||||
const headers = getHeaders(t, uiTimezone);
|
||||
|
||||
const handlePageChange = (
|
||||
_e: React.MouseEvent<HTMLButtonElement> | null,
|
||||
newPage: number
|
||||
) => {
|
||||
setPage(newPage);
|
||||
};
|
||||
|
||||
const handleRowsPerPageChange = (
|
||||
e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>
|
||||
) => {
|
||||
const value = Number(e.target.value);
|
||||
setPage(0);
|
||||
setRowsPerPage(value);
|
||||
};
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Table
|
||||
headers={headers}
|
||||
data={checks}
|
||||
onRowClick={(row) => {
|
||||
navigate(`/checks/${row.id}`);
|
||||
}}
|
||||
emptyViewText={t("pages.checks.table.empty")}
|
||||
/>
|
||||
<Pagination
|
||||
component="div"
|
||||
count={checksCount}
|
||||
page={page}
|
||||
rowsPerPage={rowsPerPage}
|
||||
onPageChange={handlePageChange}
|
||||
onRowsPerPageChange={handleRowsPerPageChange}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
@@ -1,233 +0,0 @@
|
||||
//Components
|
||||
import Stack from "@mui/material/Stack";
|
||||
import DataTable from "@/Components/v1/Table/index.jsx";
|
||||
import Table from "@mui/material/Table";
|
||||
import TableBody from "@mui/material/TableBody";
|
||||
import TableRow from "@mui/material/TableRow";
|
||||
import TableCell from "@mui/material/TableCell";
|
||||
import TableSkeleton from "@/Components/v1/Table/skeleton.jsx";
|
||||
import Pagination from "@/Components/v1/Table/TablePagination/index.jsx";
|
||||
import { StatusLabel } from "@/Components/v1/Label/index.jsx";
|
||||
import { HttpStatusLabel } from "@/Components/v1/HttpStatusLabel/index.jsx";
|
||||
import GenericFallback from "@/Components/v1/GenericFallback/index.jsx";
|
||||
import NetworkError from "@/Components/v1/GenericFallback/NetworkError.jsx";
|
||||
|
||||
//Utils
|
||||
import { formatDateWithTz } from "@/Utils/timeUtilsLegacy.js";
|
||||
import { useSelector } from "react-redux";
|
||||
import { useState } from "react";
|
||||
import PropTypes from "prop-types";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useFetchChecksTeam, useFetchChecksByMonitor } from "@/Hooks/checkHooks.js";
|
||||
import { Typography, useTheme } from "@mui/material";
|
||||
import { lighten } from "@mui/material/styles";
|
||||
|
||||
const GetTooltip = (row) => {
|
||||
const theme = useTheme();
|
||||
const phases = row?.timings?.phases;
|
||||
|
||||
const phaseKeyFormattingMap = {
|
||||
firstByte: "first byte",
|
||||
};
|
||||
return (
|
||||
<Stack
|
||||
backgroundColor={lighten(theme.palette.primary.main, 0.1)}
|
||||
border={`1px solid ${theme.palette.primary.lowContrast}`}
|
||||
borderRadius={theme.shape.borderRadius}
|
||||
py={theme.spacing(2)}
|
||||
px={theme.spacing(4)}
|
||||
>
|
||||
<Typography
|
||||
variant="body2"
|
||||
color={theme.palette.primary.contrastText}
|
||||
>{`Status code: ${row?.statusCode}`}</Typography>
|
||||
<Typography
|
||||
variant="body2"
|
||||
color={theme.palette.primary.contrastText}
|
||||
>{`Response time: ${row?.responseTime} ms`}</Typography>
|
||||
{phases && (
|
||||
<>
|
||||
<Typography
|
||||
variant="body2"
|
||||
color={theme.palette.primary.contrastText}
|
||||
>{`Request timing: `}</Typography>
|
||||
<Table
|
||||
size="small"
|
||||
sx={{ ml: theme.spacing(2), mt: theme.spacing(2) }}
|
||||
>
|
||||
<TableBody>
|
||||
{Object.keys(phases)?.map((phaseKey) => (
|
||||
<TableRow key={phaseKey}>
|
||||
<TableCell sx={{ border: "none", p: 0 }}>
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="success"
|
||||
>
|
||||
{`${phaseKeyFormattingMap[phaseKey] || phaseKey}:`}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell sx={{ border: "none", p: 0 }}>
|
||||
<Typography
|
||||
color={theme.palette.primary.contrastText}
|
||||
variant="body2"
|
||||
>{`${phases[phaseKey]} ms`}</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
const IncidentTable = ({
|
||||
isLoading,
|
||||
monitors,
|
||||
selectedMonitor,
|
||||
filter,
|
||||
dateRange,
|
||||
updateTrigger,
|
||||
}) => {
|
||||
//Redux state
|
||||
const uiTimezone = useSelector((state) => state.ui.timezone);
|
||||
|
||||
//Local state
|
||||
const [page, setPage] = useState(0);
|
||||
const [rowsPerPage, setRowsPerPage] = useState(10);
|
||||
const selectedMonitorDetails = monitors?.[selectedMonitor];
|
||||
const selectedMonitorType = selectedMonitorDetails?.type;
|
||||
|
||||
//Hooks
|
||||
const [checksMonitor, checksCountMonitor, isLoadingMonitor, networkErrorMonitor] =
|
||||
useFetchChecksByMonitor({
|
||||
monitorId: selectedMonitor === "0" ? undefined : selectedMonitor,
|
||||
type: selectedMonitorType,
|
||||
status: false,
|
||||
sortOrder: "desc",
|
||||
limit: null,
|
||||
dateRange,
|
||||
filter: filter === "resolved" ? "all" : filter,
|
||||
ack: filter === "resolved" ? true : false,
|
||||
page: page,
|
||||
rowsPerPage: rowsPerPage,
|
||||
enabled: selectedMonitor !== "0",
|
||||
updateTrigger,
|
||||
});
|
||||
|
||||
const [checksTeam, checksCountTeam, isLoadingTeam, networkErrorTeam] =
|
||||
useFetchChecksTeam({
|
||||
status: false,
|
||||
sortOrder: "desc",
|
||||
limit: null,
|
||||
dateRange,
|
||||
filter: filter === "resolved" ? "all" : filter,
|
||||
ack: filter === "resolved" ? true : false,
|
||||
page: page,
|
||||
rowsPerPage: rowsPerPage,
|
||||
enabled: selectedMonitor === "0",
|
||||
updateTrigger,
|
||||
});
|
||||
|
||||
const checks = selectedMonitor === "0" ? checksTeam : checksMonitor;
|
||||
const checksCount = selectedMonitor === "0" ? checksCountTeam : checksCountMonitor;
|
||||
isLoading = isLoadingTeam || isLoadingMonitor;
|
||||
const networkError = selectedMonitor === "0" ? networkErrorTeam : networkErrorMonitor;
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
//Handlers
|
||||
const handleChangePage = (_, newPage) => {
|
||||
setPage(newPage);
|
||||
};
|
||||
|
||||
const handleChangeRowsPerPage = (event) => {
|
||||
setRowsPerPage(event.target.value);
|
||||
};
|
||||
|
||||
const headers = [
|
||||
{
|
||||
id: "monitorName",
|
||||
content: t("incidentsTableMonitorName"),
|
||||
render: (row) => {
|
||||
return monitors?.[row.metadata?.monitorId]?.name || "N/A";
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
content: t("incidentsTableStatus"),
|
||||
render: (row) => {
|
||||
const status = row.status === true ? "up" : "down";
|
||||
return (
|
||||
<StatusLabel
|
||||
status={status}
|
||||
text={status}
|
||||
customStyles={{ textTransform: "capitalize" }}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "dateTime",
|
||||
content: t("incidentsTableDateTime"),
|
||||
render: (row) => {
|
||||
const formattedDate = formatDateWithTz(
|
||||
row.createdAt,
|
||||
"YYYY-MM-DD HH:mm:ss A",
|
||||
uiTimezone
|
||||
);
|
||||
return formattedDate;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "statusCode",
|
||||
content: t("incidentsTableStatusCode"),
|
||||
render: (row) => <HttpStatusLabel status={row.statusCode} />,
|
||||
},
|
||||
{ id: "message", content: t("incidentsTableMessage"), render: (row) => row.message },
|
||||
];
|
||||
|
||||
if (isLoading) return <TableSkeleton />;
|
||||
|
||||
if (networkError) {
|
||||
return (
|
||||
<GenericFallback>
|
||||
<NetworkError />
|
||||
</GenericFallback>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isLoading && typeof checksCount === "undefined") {
|
||||
return <GenericFallback>{t("incidentsTableNoIncidents")}</GenericFallback>;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
headers={headers}
|
||||
data={checks}
|
||||
config={{ tooltipContent: GetTooltip }}
|
||||
/>
|
||||
<Pagination
|
||||
paginationLabel={t("incidentsTablePaginationLabel")}
|
||||
itemCount={checksCount}
|
||||
page={page}
|
||||
rowsPerPage={rowsPerPage}
|
||||
handleChangePage={handleChangePage}
|
||||
handleChangeRowsPerPage={handleChangeRowsPerPage}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
IncidentTable.propTypes = {
|
||||
isLoading: PropTypes.bool,
|
||||
monitors: PropTypes.object,
|
||||
selectedMonitor: PropTypes.string,
|
||||
filter: PropTypes.string,
|
||||
dateRange: PropTypes.string,
|
||||
updateTrigger: PropTypes.bool,
|
||||
setUpdateTrigger: PropTypes.func,
|
||||
};
|
||||
export default IncidentTable;
|
||||
@@ -1,139 +0,0 @@
|
||||
// Components
|
||||
import { Stack, Typography, Button, ButtonGroup } from "@mui/material";
|
||||
import Select from "@/Components/v1/Inputs/Select/index.jsx";
|
||||
import PropTypes from "prop-types";
|
||||
|
||||
//Utils
|
||||
import { useTheme } from "@emotion/react";
|
||||
import SkeletonLayout from "./skeleton.jsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
const OptionsHeader = ({
|
||||
shouldRender,
|
||||
selectedMonitor = 0,
|
||||
setSelectedMonitor,
|
||||
monitors,
|
||||
filter = "all",
|
||||
setFilter,
|
||||
dateRange = "hour",
|
||||
setDateRange,
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const monitorNames = typeof monitors !== "undefined" ? Object.values(monitors) : [];
|
||||
const filterOptions = [
|
||||
{ id: "all", name: t("incidentsOptionsHeaderFilterAll") },
|
||||
{ id: "down", name: t("incidentsOptionsHeaderFilterDown") },
|
||||
{ id: "resolve", name: t("incidentsOptionsHeaderFilterCannotResolve") },
|
||||
{ id: "resolved", name: t("incidentsOptionsHeaderFilterResolved") },
|
||||
];
|
||||
|
||||
// The stacks below which are three in number have the same style so
|
||||
const stackStyles = {
|
||||
direction: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing(6),
|
||||
};
|
||||
|
||||
if (!shouldRender) return <SkeletonLayout />;
|
||||
|
||||
return (
|
||||
<Stack
|
||||
direction="row"
|
||||
justifyContent="space-between"
|
||||
>
|
||||
<Stack {...stackStyles}>
|
||||
<Typography
|
||||
display="inline-block"
|
||||
component="h1"
|
||||
color={theme.palette.primary.contrastTextSecondary}
|
||||
>
|
||||
{t("incidentsOptionsHeader")}
|
||||
</Typography>
|
||||
<Select
|
||||
id="incidents-select-monitor"
|
||||
placeholder={t("incidentsOptionsPlaceholderAllServers")}
|
||||
value={selectedMonitor}
|
||||
onChange={(e) => setSelectedMonitor(e.target.value)}
|
||||
items={monitorNames}
|
||||
sx={{
|
||||
backgroundColor: theme.palette.primary.main,
|
||||
color: theme.palette.primary.contrastTextSecondary,
|
||||
}}
|
||||
maxWidth={250}
|
||||
/>
|
||||
</Stack>
|
||||
<Stack {...stackStyles}>
|
||||
<Typography
|
||||
display="inline-block"
|
||||
component="h1"
|
||||
color={theme.palette.primary.contrastTextSecondary}
|
||||
>
|
||||
{t("incidentsOptionsHeaderFilterBy")}
|
||||
</Typography>
|
||||
<Select
|
||||
id="incidents-select-filter"
|
||||
value={filter}
|
||||
onChange={(e) => setFilter(e.target.value)}
|
||||
items={filterOptions}
|
||||
sx={{
|
||||
backgroundColor: theme.palette.primary.main,
|
||||
color: theme.palette.primary.contrastTextSecondary,
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
<Stack {...stackStyles}>
|
||||
<Typography
|
||||
display="inline-block"
|
||||
component="h1"
|
||||
color={theme.palette.primary.contrastTextSecondary}
|
||||
>
|
||||
{t("incidentsOptionsHeaderShow")}
|
||||
</Typography>
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
variant="group"
|
||||
filled={(dateRange === "hour").toString()}
|
||||
onClick={() => setDateRange("hour")}
|
||||
>
|
||||
{t("incidentsOptionsHeaderLastHour")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="group"
|
||||
filled={(dateRange === "day").toString()}
|
||||
onClick={() => setDateRange("day")}
|
||||
>
|
||||
{t("incidentsOptionsHeaderLastDay")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="group"
|
||||
filled={(dateRange === "week").toString()}
|
||||
onClick={() => setDateRange("week")}
|
||||
>
|
||||
{t("incidentsOptionsHeaderLastWeek")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="group"
|
||||
filled={(dateRange === "all").toString()}
|
||||
onClick={() => setDateRange("all")}
|
||||
>
|
||||
{t("incidentsOptionsHeaderFilterAll")}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
OptionsHeader.propTypes = {
|
||||
shouldRender: PropTypes.bool,
|
||||
selectedMonitor: PropTypes.string,
|
||||
setSelectedMonitor: PropTypes.func,
|
||||
monitors: PropTypes.object,
|
||||
filter: PropTypes.string,
|
||||
setFilter: PropTypes.func,
|
||||
dateRange: PropTypes.string,
|
||||
setDateRange: PropTypes.func,
|
||||
};
|
||||
|
||||
export default OptionsHeader;
|
||||
@@ -1,11 +0,0 @@
|
||||
import { Stack, Skeleton } from "@mui/material";
|
||||
|
||||
const SkeletonLayout = () => {
|
||||
return (
|
||||
<Stack>
|
||||
<Skeleton height={40} />
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export default SkeletonLayout;
|
||||
Loaded 100 of 352 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user