initial commit

This commit is contained in:
Alex Holliday committed 2025-11-13 13:47:26 -08:00
1 parent 7cb985116e
commit 75acf7b38f
955 files changed
+37333 -87054

No files matched your search

+222
View File
@@ -0,0 +1,222 @@
import Typography from "@mui/material/Typography";
import Box from "@mui/material/Box";
import MenuItem from "@mui/material/MenuItem";
import Stack from "@mui/material/Stack";
import { Button, TextInput, Select } from "@/components/inputs";
import { BasePage, ConfigBox } from "@/components/design-elements";
import { useEffect, useState, useMemo } from "react";
import { useTheme } from "@mui/material/styles";
import { useTranslation } from "react-i18next";
import { inviteSchema } from "@/validation/zod";
import { z } from "zod";
import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useGet, usePost } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
const host = import.meta.env.VITE_APP_HOST;
type FormValues = z.infer<typeof inviteSchema>;
const Invite = () => {
const { t } = useTranslation();
const theme = useTheme();
const [token, setToken] = useState<string | null>(null);
const { post, loading } = usePost<FormValues, any>();
const onSubmit = async (data: FormValues) => {
const res = await post("/invite", data);
if (res) {
setToken(res.data);
}
};
const { response } = useGet<ApiResponse<any>>("/roles");
const roles = response?.data;
const orgRoles = useMemo(
() => roles?.filter((role: any) => role.scope === "organization"),
[roles]
);
const teamRoles = useMemo(
() => roles?.filter((role: any) => role.scope === "team"),
[roles]
);
const { response: teamsResponse } = useGet<ApiResponse<any>>("/teams");
const teams = teamsResponse?.data;
const {
handleSubmit,
control,
reset,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(inviteSchema),
defaultValues: {
email: "",
teamId: "",
teamRoleId: "",
orgRoleId: "",
},
});
useEffect(() => {
reset({
teamId: teams?.[0]?._id || "",
teamRoleId: teamRoles?.[0]?._id || "",
});
}, [teams, teamRoles, reset]);
return (
<BasePage component="form" onSubmit={handleSubmit(onSubmit)}>
<ConfigBox
title="Required"
subtitle="These fields are required"
rightContent={
<Stack gap={theme.spacing(4)} maxWidth={400}>
<Controller
name="email"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
fieldLabel={t("auth.common.inputs.email.label")}
fullWidth
placeholder={t("auth.common.inputs.email.placeholder")}
error={!!errors.email}
helperText={errors.email ? errors.email.message : ""}
/>
)}
/>
<Controller
name="teamId"
control={control}
render={({ field }) => {
return (
<Stack gap={theme.spacing(8)}>
<Select
value={field.value}
fieldLabel="Team"
error={!!errors.teamId}
onChange={field.onChange}
>
{teams?.map((team: any) => {
return (
<MenuItem key={team._id} value={team._id}>
{team.name}
</MenuItem>
);
})}
</Select>
</Stack>
);
}}
/>
<Controller
name="teamRoleId"
control={control}
render={({ field }) => {
const currentRole = teamRoles?.find(
(role: any) => role._id === field.value
);
return (
<Stack gap={theme.spacing(8)}>
<Select
value={field.value}
fieldLabel="Team role"
error={!!errors.teamRoleId}
onChange={field.onChange}
>
{teamRoles?.map((role: any) => {
return (
<MenuItem key={role._id} value={role._id}>
{role.name}
</MenuItem>
);
})}
</Select>
<Stack>
<Typography mb={theme.spacing(4)}>
{currentRole && `Permissions:`}
</Typography>
{currentRole?.permissions?.map((perm: string) => (
<Typography variant="body2" key={perm}>
- {perm}
</Typography>
))}
</Stack>
</Stack>
);
}}
/>
</Stack>
}
/>
<ConfigBox
title="Optional"
subtitle="You can also assign an organization role"
rightContent={
<Stack gap={theme.spacing(4)} maxWidth={400}>
<Controller
name="orgRoleId"
control={control}
render={({ field }) => {
const currentOrgRole = orgRoles?.find(
(role: any) => role._id === field.value
);
return (
<Stack gap={theme.spacing(8)}>
<Select
value={field.value}
fieldLabel="Organization role"
error={!!errors.orgRoleId}
onChange={field.onChange}
>
{orgRoles?.map((role: any) => {
return (
<MenuItem key={role._id} value={role._id}>
{role.name}
</MenuItem>
);
})}
</Select>
<Stack>
<Typography mb={theme.spacing(4)}>
{currentOrgRole && `Permissions:`}
</Typography>
{currentOrgRole?.permissions?.map((perm: string) => (
<Typography variant="body2" key={perm}>
- {perm}
</Typography>
))}
</Stack>
</Stack>
);
}}
/>
</Stack>
}
/>
{token && (
<Stack>
<Typography variant="h2">Invite link:</Typography>
<Typography>{`${host}/register/${token}`}</Typography>
</Stack>
)}
<Box flex={1}>
<Button
loading={loading}
variant="contained"
color="accent"
type="submit"
>
Send Invite
</Button>
</Box>
</BasePage>
);
};
export default Invite;
+150
View File
@@ -0,0 +1,150 @@
import { AuthBasePage } from "@/components/auth";
import { Button, TextInput, TextLink } from "@/components/inputs";
import Stack from "@mui/material/Stack";
import { zodResolver } from "@hookform/resolvers/zod";
import { usePost } from "@/hooks/UseApi";
import { useNavigate } from "react-router";
import { useTheme } from "@mui/material/styles";
import { useAppDispatch } from "@/hooks/AppHooks";
import { useTranslation } from "react-i18next";
import {
setAuthenticated,
setUser,
setSelectedTeamId,
logout,
} from "@/features/authSlice";
import { z } from "zod";
import { useForm, Controller } from "react-hook-form";
import type { IUser } from "@/types/user";
const schema = z.object({
email: z.email("Invalid email address"),
password: z.string().min(6, "Password must be at least 6 characters"),
});
type FormData = z.infer<typeof schema>;
const Login = () => {
const { t } = useTranslation();
const dispatch = useAppDispatch();
const theme = useTheme();
const { post, loading } = usePost<FormData, IUser>();
const navigate = useNavigate();
const {
handleSubmit,
control,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
email: "",
password: "",
},
});
const onSubmit = async (data: FormData) => {
const result = await post("/auth/login", data);
if (!result) {
dispatch(logout());
navigate("/login");
}
const user = result?.data || null;
if (!user) {
dispatch(logout());
navigate("/login");
return;
}
dispatch(setAuthenticated(true));
dispatch(setUser(user));
dispatch(setSelectedTeamId(user.teams[0]?.id || null));
navigate("/");
};
return (
<AuthBasePage
title={t("auth.login.welcome")}
subtitle={t("auth.login.heading")}
>
<Stack
width={"100%"}
alignItems={"center"}
justifyContent={"center"}
gap={theme.spacing(8)}
>
<Stack
component="form"
padding={theme.spacing(8)}
gap={theme.spacing(12)}
onSubmit={handleSubmit(onSubmit)}
maxWidth={400}
sx={{
width: {
sm: "80%",
md: "70%",
lg: "65%",
xl: "65%",
},
}}
>
<Controller
name="email"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
fieldLabel={t("auth.common.inputs.email.label")}
fullWidth
placeholder={t("auth.common.inputs.email.placeholder")}
error={!!errors.email}
helperText={errors.email ? errors.email.message : ""}
/>
)}
/>
<Controller
name="password"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
type="password"
fieldLabel={t("auth.common.inputs.password.label")}
fullWidth
placeholder="••••••••••"
error={!!errors.password}
helperText={errors.password ? errors.password.message : ""}
/>
)}
/>
<Button
variant="contained"
loading={loading}
color="accent"
type="submit"
sx={{ width: "100%", alignSelf: "center", fontWeight: 700 }}
>
Login
</Button>
</Stack>
<TextLink
text={t("auth.login.links.forgotPassword")}
linkText={t("auth.login.links.forgotPasswordLink")}
href="/recovery"
/>
<TextLink
text={t("auth.login.links.register")}
linkText={t("auth.login.links.registerLink")}
href="/register"
/>
</Stack>
</AuthBasePage>
);
};
export default Login;
+65
View File
@@ -0,0 +1,65 @@
import { AuthBasePage } from "@/components/auth";
import Stack from "@mui/material/Stack";
import { RegisterForm } from "./RegisterForm";
import {
setAuthenticated,
setUser,
setSelectedTeamId,
logout,
} from "@/features/authSlice";
import { useAppDispatch } from "@/hooks/AppHooks";
import { useTranslation } from "react-i18next";
import { usePost } from "@/hooks/UseApi";
import { useNavigate } from "react-router";
import { z } from "zod";
import { registerSchema } from "@/validation/zod";
type FormData = z.infer<typeof registerSchema>;
const Register = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const { post, loading, error } = usePost<Partial<FormData>, any>();
const dispatch = useAppDispatch();
const onSubmit = async (data: FormData) => {
const submit = {
email: data.email,
password: data.password,
firstName: data.firstName,
lastName: data.lastName,
};
const result = await post("/auth/register", submit);
if (!result) {
dispatch(logout());
navigate("/login");
}
const user = result?.data || null;
if (!user) {
dispatch(logout());
navigate("/login");
return;
}
dispatch(setAuthenticated(true));
dispatch(setUser(user));
dispatch(setSelectedTeamId(user.teams[0]?.id || null));
navigate("/");
};
return (
<AuthBasePage
title={t("auth.registration.welcome")}
subtitle={t("auth.registration.heading.user")}
>
<Stack alignItems={"center"} width={"100%"}>
<RegisterForm onSubmit={onSubmit} loading={loading} error={error} />
</Stack>
</AuthBasePage>
);
};
export default Register;
+177
View File
@@ -0,0 +1,177 @@
import Stack from "@mui/material/Stack";
import { TextInput } from "@/components/inputs";
import { Button } from "@/components/inputs";
import Typography from "@mui/material/Typography";
import { useForm, Controller } from "react-hook-form";
import type { SubmitHandler } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect } from "react";
import { z } from "zod";
import { useTranslation } from "react-i18next";
import { useTheme } from "@mui/material/styles";
import { useInitForm } from "@/hooks/forms/UseInitRegisterForm";
import { registerSchema } from "@/validation/zod";
type FormData = z.infer<typeof registerSchema>;
export const RegisterForm = ({
mode = "register",
hasUser = false,
initialData,
onSubmit,
loading,
error,
}: {
mode?: "register" | "invite";
hasUser?: boolean;
initialData?: Partial<FormData>;
onSubmit: SubmitHandler<FormData>;
loading: boolean;
error: string | null;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const {
handleSubmit,
control,
reset,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(registerSchema),
defaultValues: {
email: "",
password: "",
confirmPassword: "",
},
});
useEffect(() => {
reset(defaults);
}, [initialData, reset, defaults]);
if (hasUser && mode === "invite") {
return (
<Button
variant="contained"
color="accent"
onClick={() => onSubmit(defaults)}
>
Accept invite
</Button>
);
}
return (
<Stack
component="form"
padding={theme.spacing(8)}
gap={theme.spacing(12)}
onSubmit={handleSubmit(onSubmit)}
maxWidth={400}
sx={{
width: {
sm: "80%",
md: "70%",
lg: "65%",
xl: "65%",
},
}}
>
<Controller
name="email"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
disabled={mode === "invite"}
{...field}
fieldLabel={t("auth.common.inputs.email.label")}
fullWidth
placeholder={t("auth.common.inputs.email.placeholder")}
error={!!errors.email}
helperText={errors.email ? errors.email.message : ""}
/>
)}
/>
<Controller
disabled={defaults.firstName ? true : false}
name="firstName"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
fieldLabel={t("auth.common.inputs.firstName.label")}
fullWidth
placeholder={t("auth.common.inputs.firstName.placeholder")}
error={!!errors.firstName}
helperText={errors.firstName ? errors.firstName.message : ""}
/>
)}
/>
<Controller
disabled={defaults.lastName ? true : false}
name="lastName"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
fieldLabel={t("auth.common.inputs.lastName.label")}
fullWidth
placeholder={t("auth.common.inputs.lastName.placeholder")}
error={!!errors.lastName}
helperText={errors.lastName ? errors.lastName.message : ""}
/>
)}
/>
<Controller
name="password"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
type="password"
fieldLabel={t("auth.common.inputs.password.label")}
fullWidth
placeholder="••••••••••"
error={!!errors.password}
helperText={errors.password ? errors.password.message : ""}
/>
)}
/>
<Controller
name="confirmPassword"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
type="password"
fieldLabel={t("auth.common.inputs.passwordConfirm.label")}
fullWidth
placeholder={t("auth.common.inputs.passwordConfirm.placeholder")}
error={!!errors.confirmPassword}
helperText={
errors.confirmPassword ? errors.confirmPassword.message : ""
}
/>
)}
/>
<Button
variant="contained"
loading={loading}
color="accent"
type="submit"
sx={{ width: "100%", alignSelf: "center", fontWeight: 700 }}
>
{mode === "invite" ? "Accept invitation" : "Register"}
</Button>
{error && <Typography color="error">{error}</Typography>}
</Stack>
);
};
+89
View File
@@ -0,0 +1,89 @@
import { AuthBasePage } from "@/components/auth";
import Stack from "@mui/material/Stack";
import { RegisterForm } from "./RegisterForm";
import {
setAuthenticated,
setUser,
setSelectedTeamId,
} from "@/features/authSlice";
import { useAppDispatch } from "@/hooks/AppHooks";
import type { ApiResponse } from "@/hooks/UseApi";
import { useTranslation } from "react-i18next";
import { usePost } from "@/hooks/UseApi";
import { useNavigate } from "react-router";
import { z } from "zod";
import { registerSchema } from "@/validation/zod";
import { useGet } from "@/hooks/UseApi";
import { useParams } from "react-router";
import type { IUser } from "@/types/user";
type FormData = z.infer<typeof registerSchema>;
const RegisterInvite = () => {
const { id: token } = useParams();
const { t } = useTranslation();
const navigate = useNavigate();
const { post, loading, error } = usePost<Partial<FormData>, IUser>();
const { response, error: errorInvite } = useGet<ApiResponse<any>>(
`/invite/${token}`
);
const { user, invite } = response?.data || {};
const hasUser = Boolean(user);
const dispatch = useAppDispatch();
const onSubmit = async (data: FormData) => {
const submit = {
...(data.firstName && { firstName: data.firstName }),
...(data.lastName && { lastName: data.lastName }),
...(data.password && { password: data.password }),
...(data.confirmPassword && { confirmPassword: data.confirmPassword }),
};
const result = await post(`/auth/register/invite/${token}`, submit);
if (!result) {
dispatch(setAuthenticated(false));
navigate("/login");
return;
}
const user: IUser = result.data;
if (!user) {
dispatch(setAuthenticated(false));
navigate("/login");
return;
}
dispatch(setAuthenticated(true));
dispatch(setUser(user));
dispatch(setSelectedTeamId(user.teams[0]?.id || null));
navigate("/");
};
if (errorInvite) {
return "No invite found";
}
return (
<AuthBasePage
title={t("auth.registration.welcome")}
subtitle={t("auth.registration.heading.user")}
>
<Stack alignItems={"center"} width={"100%"}>
<RegisterForm
mode="invite"
hasUser={hasUser}
initialData={{
email: invite?.email || "",
}}
onSubmit={onSubmit}
loading={loading}
error={error}
/>
</Stack>
</AuthBasePage>
);
};
export default RegisterInvite;
@@ -0,0 +1,25 @@
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { useTheme, alpha } from "@mui/material/styles";
import type { ILogEntry } from "@/types/log";
export const DiagnosticLogDetails = ({ logEntry }: { logEntry: ILogEntry }) => {
const theme = useTheme();
return (
<Stack
bgcolor={alpha(theme.palette.error.main, 0.1)}
sx={{
p: theme.spacing(4),
}}
>
<Typography variant="h2" textTransform={"capitalize"}>
{"Stack trace"}
</Typography>
<Typography sx={{ wordBreak: "break-word", whiteSpace: "pre-wrap" }}>
{logEntry.stack}{" "}
</Typography>
</Stack>
);
};
@@ -0,0 +1,38 @@
import { BasePage, Tab, Tabs, InfoBox } from "@/components/design-elements";
import { DiagnosticsLogTab } from "@/pages/diagnostic/DiagnosticsLogTab";
import { DiagnosticsQueueTab } from "@/pages/diagnostic/DiagnosticsQueueTab";
import { FileText, ListTodo } from "lucide-react";
import { useState } from "react";
const DiagnosticPage = () => {
const [tabValue, setTabValue] = useState("logs");
const handleTabChange = (_: React.SyntheticEvent, newValue: string) => {
setTabValue(newValue);
};
return (
<BasePage>
<InfoBox
title="System Diagnostics"
description="Review system logs and background job status to troubleshoot issues. Monitor the health of your monitoring infrastructure and investigate any problems."
/>
<Tabs value={tabValue} onChange={handleTabChange}>
<Tab
label="Logs"
value="logs"
icon={<FileText size={18} strokeWidth={1.5} />}
/>
<Tab
label="Jobs"
value="jobs"
icon={<ListTodo size={18} strokeWidth={1.5} />}
/>
</Tabs>
{tabValue === "logs" && <DiagnosticsLogTab />}
{tabValue === "jobs" && <DiagnosticsQueueTab />}
</BasePage>
);
};
export default DiagnosticPage;
@@ -0,0 +1,103 @@
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { Select } from "@/components/inputs";
import MenuItem from "@mui/material/MenuItem";
import { Table } from "@/components/design-elements";
import type { Header } from "@/components/design-elements/Table";
import { DiagnosticLogDetails } from "@/pages/diagnostic/DiagnosticLogDetails";
import { useState } from "react";
import { useGet } from "@/hooks/UseApi";
import { useTheme } from "@mui/material/styles";
import type { ILogEntry } from "@/types/log";
import type { ApiResponse } from "@/hooks/UseApi";
export const DiagnosticsLogTab = () => {
const theme = useTheme();
const [logLevel, setLogLevel] = useState("all");
const { response } = useGet<ApiResponse<ILogEntry[]>>(
`/diagnostic/logs`,
{},
{ refreshInterval: 5000 }
);
const logEntries = response?.data || [];
const levelColors = {
info: theme.palette.success.main,
warn: theme.palette.warning.main,
error: theme.palette.error.main,
debug: theme.palette.accent.main,
};
const headers: Header<ILogEntry>[] = [
{
id: "timestamp",
content: "Timestamp",
render: (log: ILogEntry) => log.timestamp,
},
{
id: "level",
content: "Level",
render: (log: ILogEntry) => {
const color =
levelColors[log.level] || theme.palette.primary.contrastText;
return (
<span
style={{ color, fontWeight: "bold", textTransform: "uppercase" }}
>
{log.level}
</span>
);
},
},
{
id: "service",
content: "Service",
render: (log: ILogEntry) => log.service,
},
{
id: "message",
content: "Message",
render: (log: ILogEntry) => log.message,
},
];
const filteredLogEntries = logEntries
.filter((log: ILogEntry) => {
if (logLevel === "all") return true;
return log.level === logLevel;
})
.map((log, idx) => ({ ...log, id: `${log.timestamp}-${idx}` }));
return (
<Stack spacing={theme.spacing(4)}>
<Stack direction="row" spacing={theme.spacing(4)} alignItems={"center"}>
<Typography variant="h2">Log level: </Typography>
<Select
value={logLevel}
onChange={(e) => {
setLogLevel(e.target.value);
}}
>
<MenuItem value="all">All</MenuItem>
<MenuItem value="error">Error</MenuItem>
<MenuItem value="warn">Warn</MenuItem>
<MenuItem value="info">Info</MenuItem>
<MenuItem value="debug">Debug</MenuItem>
</Select>
</Stack>
<Table
headers={headers}
data={filteredLogEntries}
expandableRows={true}
renderExpandedContent={(row) => {
if (!row.stack) return null;
return <DiagnosticLogDetails logEntry={row} />;
}}
cardsOnSmallScreens={true}
/>
</Stack>
);
};
@@ -0,0 +1,165 @@
import Stack from "@mui/material/Stack";
import { StatBox } from "@/components/design-elements";
import { Table } from "@/components/design-elements";
import { useTheme } from "@mui/material/styles";
import { useTranslation } from "react-i18next";
import { useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import type { IJob, IJobMetrics } from "@/types/job";
import type { Header } from "@/components/design-elements/Table";
export const DiagnosticsQueueTab = () => {
const { t } = useTranslation();
const theme = useTheme();
const { response } = useGet<
ApiResponse<{ jobs: IJob[]; metrics: IJobMetrics }>
>(`/diagnostic/jobs`, {}, { refreshInterval: 5000 });
const jobs: IJob[] = response?.data?.jobs || [];
const metrics = response?.data?.metrics;
if (!metrics) {
return null;
}
const getHeaders = () => {
const headers: Header<IJob>[] = [
{
id: "name",
content: t("diagnosticsPage.tableHeaderId"),
render: (row) => {
return row?.id || "-";
},
},
{
id: "url",
content: t("diagnosticsPage.tableHeaderUrl"),
render: (row) => {
return row?.data?.url || "-";
},
},
{
id: "interval",
content: t("diagnosticsPage.tableHeaderInterval"),
render: (row) => {
if (!row?.data?.interval) return "-";
const seconds = row.data.interval / 1000;
return `${seconds}s`;
},
},
{
id: "type",
content: t("diagnosticsPage.tableHeaderType"),
render: (row) => {
return row?.data?.type || "-";
},
},
{
id: "active",
content: t("diagnosticsPage.tableHeaderActive"),
render: (row) => {
return row?.data?.isActive ? "true" : "false";
},
},
{
id: "runCount",
content: t("diagnosticsPage.tableHeaderRunCount"),
render: (row) => {
return row?.runCount || "-";
},
},
{
id: "lastRun",
content: t("diagnosticsPage.tableHeaderLastRun"),
render: (row) => {
if (!row?.lastRunAt) return "-";
const date = new Date(row.lastRunAt);
return (
<Stack>
<div>{date.toLocaleDateString()}</div>
<div>{date.toLocaleTimeString()}</div>
</Stack>
);
},
},
{
id: "lockedAt",
content: t("diagnosticsPage.tableHeaderLockedAt"),
render: (row) => {
if (!row?.lockedAt) return "-";
const date = new Date(row.lockedAt);
return (
<Stack>
<div>{date.toLocaleDateString()}</div>
<div>{date.toLocaleTimeString()}</div>
</Stack>
);
},
},
{
id: "lastFinishedAt",
content: t("diagnosticsPage.tableHeaderLastFinishedAt"),
render: (row) => {
if (!row?.lastFinishedAt) return "-";
const date = new Date(row.lastFinishedAt);
return (
<Stack>
<div>{date.toLocaleDateString()}</div>
<div>{date.toLocaleTimeString()}</div>
</Stack>
);
},
},
{
id: "lastRunTook",
content: t("diagnosticsPage.tableHeaderLastRunTook"),
render: (row) => {
return row?.lastRunTook || "-";
},
},
];
return headers;
};
const headers = getHeaders();
return (
<Stack spacing={theme.spacing(8)}>
<Stack direction={{ s: "column", md: "row" }} gap={theme.spacing(8)}>
<StatBox
title={t("diagnosticsPage.statBoxJobsTitle")}
subtitle={`${metrics?.jobs}`}
sx={{ width: "100%" }}
tooltip="Total number of monitoring jobs in the queue"
/>
<StatBox
title={t("diagnosticsPage.statBoxActiveJobsTitle")}
subtitle={`${metrics.activeJobs}`}
sx={{ width: "100%" }}
tooltip="Jobs currently running or locked for execution"
/>
<StatBox
title={t("diagnosticsPage.statBoxFailingJobsTitle")}
subtitle={`${metrics.failingJobs}`}
sx={{ width: "100%" }}
tooltip="Jobs that failed on their last execution"
/>
<StatBox
title={t("diagnosticsPage.statBoxTotalRunsTitle")}
subtitle={`${metrics.totalRuns}`}
sx={{ width: "100%" }}
tooltip="Total number of job executions across all jobs"
/>
<StatBox
title={t("diagnosticsPage.statBoxTotalFailuresTitle")}
subtitle={`${metrics.totalFailures}`}
sx={{ width: "100%" }}
tooltip="Total number of failed job executions across all jobs"
/>
</Stack>
<Table headers={headers} data={jobs} />
</Stack>
);
};
@@ -0,0 +1,165 @@
import { Table, Pagination, ValueLabel } from "@/components/design-elements";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { Button } from "@/components/inputs";
import type { Header } from "@/components/design-elements/Table";
import { usePatch } from "@/hooks/UseApi";
import { useTranslation } from "react-i18next";
import { formatDateWithTz } from "@/utils/TimeUtils";
import { useAppSelector } from "@/hooks/AppHooks";
import type { IIncident } from "@/types/incident";
export const IncidentTable = ({
incidents,
count,
page,
setPage,
rowsPerPage,
setRowsPerPage,
refetch,
}: {
incidents: IIncident[];
count: number;
page: number;
setPage: (page: number) => void;
rowsPerPage: number;
setRowsPerPage: (rowsPerPage: number) => void;
refetch: () => void;
}) => {
const { patch, loading: isPatching } = usePatch();
const { t } = useTranslation();
const uiTimezone = useAppSelector((state: any) => state.ui.timezone);
const getHeaders = (t: Function, uiTimezone: string) => {
const headers: Header<IIncident>[] = [
{
id: "name",
content: t("incidentsTableMonitorName"),
render: (row) => {
return row.monitorId.name || "N/A";
},
},
{
id: "start",
content: "Incident start",
render: (row) => {
return formatDateWithTz(
row.startedAt,
"ddd, MMMM D, YYYY, HH:mm A",
uiTimezone
);
},
},
{
id: "end",
content: "Incident end",
render: (row) => {
return row.endedAt
? formatDateWithTz(
row.endedAt,
"ddd, MMMM D, YYYY, HH:mm A",
uiTimezone
)
: "Ongoing";
},
},
{
id: "status",
content: "Current monitor status",
render: (row) => {
return (
<Typography textTransform={"capitalize"} color="textPrimary">
{row.monitorId.status}
</Typography>
);
},
},
{
id: "resolved",
content: "Resolved",
render: (row) => {
return (
<ValueLabel
value={row.resolved ? "positive" : "negative"}
text={row.resolved ? "Yes" : "No"}
/>
);
},
},
{
id: "resolutionType",
content: "Resolution type",
render: (row) => {
return row.resolutionType || "N/A";
},
},
{
id: "resolvedBy",
content: "Resolved by",
render: (row) => {
return row.resolvedBy?.email || "N/A";
},
},
{
id: "actions",
content: "Actions",
render: (row) => {
return row.resolved ? null : (
<Button
onClick={async (e) => {
e.stopPropagation();
await patch(`/incidents/${row._id}/resolve`, {
resolutionNote: "Resolved via UI",
});
refetch();
}}
variant="contained"
color="accent"
>
Resolve
</Button>
);
},
},
];
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={incidents}
onRowClick={(row) => {
alert(JSON.stringify(row, null, 2));
}}
/>
<Pagination
component="div"
count={count}
page={page}
rowsPerPage={rowsPerPage}
onPageChange={handlePageChange}
onRowsPerPageChange={handleRowsPerPageChange}
/>
</Box>
);
};
@@ -0,0 +1,121 @@
import Stack from "@mui/material/Stack";
import MenuItem from "@mui/material/MenuItem";
import { Select } from "@/components/inputs";
import { BasePage, InfoBox } from "@/components/design-elements";
import { IncidentTable } from "@/pages/incidents/IncidentTable";
import { HeaderRange } from "@/components/common/HeaderRange";
import { useTheme } from "@mui/material/styles";
import { useParams } from "react-router";
import { useState, useEffect } from "react";
import { useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import type { SelectChangeEvent } from "@mui/material/Select";
import type { IIncident } from "@/types/incident";
import type { IMonitor } from "@/types/monitor";
const IncidentsPage = () => {
const theme = useTheme();
const [selectedMonitorId, setSelectedMonitorId] = useState<string>("all");
const { id } = useParams<{ id: string }>();
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);
const [range, setRange] = useState("2h");
const [resolved, setResolved] = useState<boolean | null>(false);
const { response, isValidating, refetch } = useGet<
ApiResponse<{ count: number; incidents: IIncident[] }>
>(
`/incidents?page=${page}&rowsPerPage=${rowsPerPage}&range=${range}${
selectedMonitorId && selectedMonitorId !== "all"
? `&monitorId=${selectedMonitorId}`
: ""
}${resolved !== null ? `&resolved=${resolved}` : ""}`,
{},
{ keepPreviousData: true },
{ useTeamIdAsKey: true }
);
const incidents = response?.data?.incidents
? [...response.data.incidents].reverse()
: [];
const count = response?.data?.count || 0;
const { response: monitorResponse } = useGet<ApiResponse<IMonitor[]>>(
`/monitors`,
{},
{ keepPreviousData: true }
);
const monitors: IMonitor[] = monitorResponse?.data || [];
useEffect(() => {
if (id) {
setSelectedMonitorId(id);
}
}, [id]);
return (
<BasePage>
<InfoBox
title="Incident History"
description="View all past and ongoing incidents across your monitors. Analyze downtime patterns, incident duration, and resolution times to improve reliability."
/>
<Stack
direction={{ xs: "column", md: "row" }}
spacing={theme.spacing(8)}
justifyContent={"space-between"}
>
<Stack
direction={{ xs: "column", md: "row" }}
spacing={theme.spacing(8)}
>
<Select<string>
onChange={(e: SelectChangeEvent<string>) => {
setSelectedMonitorId(e.target.value);
}}
value={selectedMonitorId}
>
<MenuItem value="all">All monitors</MenuItem>
{monitors.map((monitor) => (
<MenuItem key={monitor._id} value={monitor._id}>
{monitor.name}
</MenuItem>
))}
</Select>
<Select<string>
onChange={(e: SelectChangeEvent<string>) => {
if (e.target.value === "resolved") {
setResolved(true);
} else if (e.target.value === "unresolved") {
setResolved(false);
} else {
setResolved(null);
}
}}
value={
resolved === null ? "all" : resolved ? "resolved" : "unresolved"
}
>
<MenuItem value={"all"}>All</MenuItem>
<MenuItem value={"resolved"}>Resolved</MenuItem>
<MenuItem value={"unresolved"}>Unresolved</MenuItem>
</Select>
</Stack>
<HeaderRange range={range} setRange={setRange} loading={isValidating} />
</Stack>
<IncidentTable
incidents={incidents}
rowsPerPage={rowsPerPage}
setRowsPerPage={setRowsPerPage}
page={page}
setPage={setPage}
count={count}
refetch={refetch}
/>
</BasePage>
);
};
export default IncidentsPage;
@@ -0,0 +1,62 @@
import { monitorSchemaInfra } from "@/validation/zod";
import { useGet, usePatch } from "@/hooks/UseApi";
import { InfraForm } from "@/pages/infrastructure/InfraForm";
import { useParams } from "react-router";
import type { ApiResponse } from "@/hooks/UseApi";
import humanInterval from "human-interval";
import { z } from "zod";
import { useNavigate } from "react-router";
import type { INotificationChannel } from "@/types/notification-channel";
import type { IMonitor } from "@/types/monitor";
const InfraConfigurePage = () => {
type FormValues = z.infer<typeof monitorSchemaInfra>;
type SubmitValues = Omit<FormValues, "interval"> & {
interval: number | undefined;
};
const { id } = useParams();
const navigate = useNavigate();
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
"/notification-channels"
);
const { response: monitorResponse } = useGet<ApiResponse<any>>(
`/monitors/${id}`
);
const monitor = monitorResponse?.data || null;
const notificationOptions = response?.data ?? [];
const { patch, loading, error } = usePatch<Partial<SubmitValues>, IMonitor>();
const onSubmit = async (data: FormValues) => {
let interval = humanInterval(data.interval);
if (!interval) interval = 180000;
const submitData = {
type: data.type,
secret: data.secret,
name: data.name,
notificationChannels: data.notificationChannels,
interval,
};
const result = await patch(`/monitors/${id}`, submitData);
if (result) {
navigate(`/infrastructure/${id}`);
} else {
console.error(error);
}
};
return (
<InfraForm
mode="configure"
initialData={{
...monitor,
}}
onSubmit={onSubmit}
notificationOptions={notificationOptions}
loading={loading}
/>
);
};
export default InfraConfigurePage;
@@ -0,0 +1,43 @@
import { InfraForm } from "@/pages/infrastructure/InfraForm";
import humanInterval from "human-interval";
import { z } from "zod";
import { monitorSchemaInfra } from "@/validation/zod";
import { useGet, usePost } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { useNavigate } from "react-router";
import type { INotificationChannel } from "@/types/notification-channel";
const InfraCreatePage = () => {
type FormValues = z.infer<typeof monitorSchemaInfra>;
type SubmitValues = Omit<FormValues, "interval"> & {
interval: number | undefined;
};
const navigate = useNavigate();
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
"/notification-channels"
);
const { post, loading, error } = usePost<SubmitValues, any>();
const onSubmit = async (data: FormValues) => {
let interval = humanInterval(data.interval);
if (!interval) interval = 60000;
const submitData = { ...data, interval };
const result = await post("/monitors", submitData);
if (result) {
navigate("/infrastructure");
} else {
console.error(error);
}
};
const notificationOptions = response?.data ?? [];
return (
<InfraForm
onSubmit={onSubmit}
notificationOptions={notificationOptions}
loading={loading}
/>
);
};
export default InfraCreatePage;
@@ -0,0 +1,126 @@
import { BasePage, StatBox } from "@/components/design-elements";
import { HeaderControls, HeaderRange } from "@/components/monitors";
import Stack from "@mui/material/Stack";
import prettyMilliseconds from "pretty-ms";
import { getStatusPalette } from "@/utils/MonitorUtils";
import { InfraDetailsGraphs } from "@/pages/infrastructure/InfraDetailsGraphs";
import { useGet, usePatch } from "@/hooks/UseApi";
import { useState } from "react";
import { useTheme } from "@mui/material/styles";
import { useParams } from "react-router";
import type { ApiResponse } from "@/hooks/UseApi";
import type { IMonitor, IMonitorWithMonitorStats } from "@/types/monitor";
import type { IInfraCheck } from "@/types/check";
import {
getFrequency,
getCores,
getAvgTemp,
getGbs,
getDiskTotalGbs,
getOsAndPlatform,
} from "@/pages/infrastructure/InfraUtils";
import { InfraDetailsGauges } from "./InfraDetailsGauges";
const GLOBAL_REFRESH = import.meta.env.VITE_APP_GLOBAL_REFRESH;
const InfraDetailsPage = () => {
const theme = useTheme();
const { id } = useParams();
const [range, setRange] = useState("2h");
const { response, isValidating, refetch } = useGet<
ApiResponse<IMonitorWithMonitorStats>
>(
`/monitors/${id}?embedChecks=true&range=${range}`,
{},
{ refreshInterval: GLOBAL_REFRESH, keepPreviousData: true }
);
const { patch, loading: isPatching } = usePatch<any, IMonitor>();
const monitor = response?.data?.monitor;
const stats = response?.data?.stats;
const checks = (response?.data?.checks || []) as IInfraCheck[];
const palette = getStatusPalette(monitor?.status || "initializing");
const streakDuration = stats?.currentStreakStartedAt
? Date.now() - stats?.currentStreakStartedAt
: 0;
const lastChecked = stats?.lastCheckTimestamp
? Date.now() - stats?.lastCheckTimestamp
: -1;
if (!monitor) {
return null;
}
return (
<BasePage>
<HeaderControls
monitor={monitor}
patch={patch}
isPatching={isPatching}
refetch={refetch}
path="/infrastructure"
/>
<Stack direction="row" gap={theme.spacing(8)} flexWrap={"wrap"}>
<StatBox
palette={palette}
title="Active for"
subtitle={prettyMilliseconds(streakDuration, {
secondsDecimalDigits: 0,
})}
/>
<StatBox
title="Last check"
subtitle={
lastChecked >= 0
? `${prettyMilliseconds(lastChecked, {
secondsDecimalDigits: 0,
})} ago`
: "N/A"
}
/>
<StatBox
title="Last response time"
subtitle={
stats?.lastResponseTime ? `${stats?.lastResponseTime} ms` : "N/A"
}
/>
<StatBox
title="CPU (physical)"
subtitle={getCores(checks[0]?.cpu?.physical_core)}
/>
<StatBox
title="CPU (logical)"
subtitle={getCores(checks[0]?.cpu?.logical_core)}
/>
<StatBox
title="CPU frequency"
subtitle={getFrequency(checks[0]?.cpu?.current_frequency)}
/>
<StatBox
title="Avg CPU temp"
subtitle={getAvgTemp(checks[0]?.cpu?.temperature)}
/>
<StatBox
title="Memory"
subtitle={getGbs(checks[0]?.memory?.total_bytes)}
/>
<StatBox title="Disk" subtitle={getDiskTotalGbs(checks[0]?.disk)} />
<StatBox title="OS" subtitle={getOsAndPlatform(checks[0]?.host)} />
</Stack>
{/* <Typography variant="h1">Infrastructure overview</Typography> */}
<InfraDetailsGauges checks={checks} />
<HeaderRange loading={isValidating} range={range} setRange={setRange} />
<InfraDetailsGraphs checks={checks} range={range} />
{/* <Typography variant="h1">Network</Typography>
<InfraDetailsNetGraphs checks={checks} range={range} /> */}
</BasePage>
);
};
export default InfraDetailsPage;
@@ -0,0 +1,84 @@
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { BaseChart } from "@/components/monitors/Chart";
import { Gauge } from "@/components/design-elements";
import { getGbs, getFrequency } from "./InfraUtils";
import type { IInfraCheck } from "@/types/check";
import { useTheme } from "@mui/material/styles";
import useMediaQuery from "@mui/material/useMediaQuery";
const InfraDetailGauge = ({
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>
);
};
export const InfraDetailsGauges = ({ checks }: { checks: IInfraCheck[] }) => {
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
return (
<Stack
direction={isSmall ? "column" : "row"}
spacing={theme.spacing(8)}
alignItems={"center"}
>
<InfraDetailGauge
title="Memory Usage"
progress={(checks[0]?.memory.usage_percent || 0) * 100}
upperLabel="Used"
upperValue={getGbs(checks[0]?.memory.used_bytes)}
lowerLabel="Free"
lowerValue={getGbs(checks[0]?.memory.total_bytes)}
/>
<InfraDetailGauge
title="CPU Usage"
progress={(checks[0]?.cpu.usage_percent || 0) * 100}
upperLabel="Current frequency"
upperValue={getFrequency(checks[0]?.cpu.current_frequency)}
lowerLabel="Max Frequency"
lowerValue={getFrequency(checks[0]?.cpu.frequency)}
/>
{checks[0]?.disk?.map((disk, idx) => {
return (
<InfraDetailGauge
key={disk.device + idx}
title={`Disk ${idx} usage`}
progress={(disk.usage_percent || 0) * 100}
upperLabel="Used"
upperValue={getGbs(disk.used_bytes)}
lowerLabel="Free"
lowerValue={getGbs(disk.total_bytes)}
/>
);
})}
</Stack>
);
};
@@ -0,0 +1,86 @@
import Grid from "@mui/material/Grid";
import { HistogramInfrastructure } from "@/components/monitors";
import type { IInfraCheck } from "@/types/check";
import { useMemo } from "react";
import { useTheme } from "@mui/material/styles";
import useMediaQuery from "@mui/material/useMediaQuery";
const getChartConfigs = (theme: any, checks: IInfraCheck[]) => {
return [
{
type: "memory",
dataKeys: ["memory.usage_percent"],
strokeColor: theme.palette.accent.main,
gradientStartColor: theme.palette.accent.main,
yDomain: [0, 1],
idx: null,
},
{
type: "cpu",
dataKeys: ["cpu.used_percent"],
strokeColor: theme.palette.success.main,
gradientStartColor: theme.palette.success.main,
yDomain: [0, 1],
idx: null,
},
{
type: "temp",
dataKeys: ["avg_temp"],
strokeColor: theme.palette.error.main,
gradientStartColor: theme.palette.error.main,
yDomain: [0, 150],
idx: null,
},
...(checks[0]?.disk?.map((_, idx) => ({
type: "disk",
dataKeys: [`disk[${idx}].usage_percent`],
strokeColor: theme.palette.warning.main,
gradientStartColor: theme.palette.warning.main,
yDomain: [0, 1],
idx,
})) || []),
];
};
export const InfraDetailsGraphs = ({
checks,
range,
}: {
checks: IInfraCheck[];
range: string;
}) => {
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const chartConfigs = useMemo(
() => getChartConfigs(theme, checks),
[theme, checks]
);
return (
<Grid container spacing={theme.spacing(8)}>
{chartConfigs.map((config) => {
return (
<Grid
size={isSmall ? 12 : 6}
key={`${config.type}-${config.idx ?? ""}`}
>
<HistogramInfrastructure
range={range}
title={config.type}
idx={config.idx}
key={`${config.type}-${config.idx ?? ""}`}
checks={checks}
xKey="_id"
yDomain={config.yDomain}
dataKeys={config.dataKeys}
gradient={true}
gradientStartColor={config.gradientStartColor}
gradientEndColor="#ffffff"
strokeColor={config.strokeColor}
/>
</Grid>
);
})}
</Grid>
);
};
@@ -0,0 +1,124 @@
import Stack from "@mui/material/Stack";
import MenuItem from "@mui/material/MenuItem";
import Grid from "@mui/material/Grid";
import { HistogramInfrastructure } from "@/components/monitors";
import { Select } from "@/components/inputs";
import type { IInfraCheck } from "@/types/check";
import { useMemo, useState, useEffect } from "react";
import { useTheme } from "@mui/material/styles";
import useMediaQuery from "@mui/material/useMediaQuery";
const getChartConfigs = (
theme: any,
checks: IInfraCheck[],
selectedInterface: string
) => {
const idx = checks[0]?.net.findIndex((i) => i.name === selectedInterface);
if (idx === -1) return [];
return [
{
type: "Bytes received",
dataKeys: [`net[${idx}].bytes_recv`],
strokeColor: theme.palette.accent.main,
gradientStartColor: theme.palette.accent.main,
yDomain: [0, 1],
idx: null,
},
{
type: "Bytes sent",
dataKeys: [`net[${idx}].bytes_sent`],
strokeColor: theme.palette.success.main,
gradientStartColor: theme.palette.success.main,
yDomain: [0, 1],
idx: null,
},
{
type: "Packets received",
dataKeys: [`net[${idx}].packets_recv`],
strokeColor: theme.palette.warning.main,
gradientStartColor: theme.palette.warning.main,
yDomain: [0, 1],
idx: null,
},
{
type: "Packets sent",
dataKeys: [`net[${idx}].packets_sent`],
strokeColor: theme.palette.error.main,
gradientStartColor: theme.palette.error.main,
yDomain: [0, 1],
idx: null,
},
];
};
export const InfraDetailsNetGraphs = ({
checks,
range,
}: {
checks: IInfraCheck[];
range: string;
}) => {
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const [selectedInterface, setSelectedInterface] = useState<string>("");
const chartConfigs = useMemo(
() => getChartConfigs(theme, checks, selectedInterface),
[theme, checks, selectedInterface]
);
useEffect(() => {
if (checks[0]) {
const firstNonLoopback = checks[0].net.find(
(iface) => iface.name !== "lo"
);
setSelectedInterface(firstNonLoopback?.name || "");
}
}, [checks]);
return (
<Stack gap={theme.spacing(8)}>
<Grid container spacing={theme.spacing(8)}>
<Grid size={4}>
<Select
fullWidth
value={selectedInterface}
onChange={(e) => setSelectedInterface(e.target.value)}
>
{checks[0]?.net.map((iface) => {
return (
<MenuItem key={iface.name} value={iface.name}>
{iface.name}
</MenuItem>
);
})}
</Select>
</Grid>
<Grid size={8} />
{chartConfigs.map((config) => {
return (
<Grid
size={isSmall ? 12 : 6}
key={`${config.type}-${config.idx ?? ""}`}
>
<HistogramInfrastructure
range={range}
title={config.type}
idx={config.idx}
key={`${config.type}-${config.idx ?? ""}`}
checks={checks}
xKey="_id"
yDomain={config.yDomain}
dataKeys={config.dataKeys}
gradient={true}
gradientStartColor={config.gradientStartColor}
gradientEndColor="#ffffff"
strokeColor={config.strokeColor}
/>
</Grid>
);
})}
</Grid>
</Stack>
);
};
@@ -0,0 +1,293 @@
import Stack from "@mui/material/Stack";
import {
TextInput,
Button,
RadioWithDescription,
AutoComplete,
} from "@/components/inputs";
import RadioGroup from "@mui/material/RadioGroup";
import { ConfigBox, BasePage } from "@/components/design-elements";
import { Trash2 } from "lucide-react";
import { Typography } from "@mui/material";
import { useEffect, useState, useRef } from "react";
import { useTranslation } from "react-i18next";
import { monitorSchemaInfra } from "@/validation/zod";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
useForm,
Controller,
useWatch,
type SubmitHandler,
} from "react-hook-form";
import { useTheme } from "@mui/material/styles";
import { useInitForm } from "@/hooks/forms/UseInitInfraForm";
type FormValues = z.infer<typeof monitorSchemaInfra>;
export const InfraForm = ({
mode = "create",
initialData,
onSubmit,
notificationOptions,
loading,
}: {
mode?: "create" | "configure";
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
notificationOptions: any[];
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const urlInputRef = useRef<HTMLInputElement>(null);
const [selectedProtocol, setSelectedProtocol] = useState<string>("https");
const {
handleSubmit,
control,
setValue,
reset,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(monitorSchemaInfra) as any,
defaultValues: defaults,
mode: "onChange",
});
const url = useWatch({ control, name: "url" });
useEffect(() => {
reset(defaults);
if (defaults.url.startsWith("http://")) {
setSelectedProtocol("http");
}
}, [initialData, reset, defaults]);
useEffect(() => {
if (!url) {
setValue("url", `${selectedProtocol}://`);
}
const hasProtocol = /^(http|https):\/\//i.test(url);
if (hasProtocol) {
const newUrl = url.replace(
/^(http|https):\/\//i,
`${selectedProtocol}://`
);
if (newUrl !== url) setValue("url", newUrl);
} else {
setValue("url", `${selectedProtocol}://${url}`);
}
}, [selectedProtocol, setValue, url]);
useEffect(() => {
const input = urlInputRef.current;
if (input) {
const len = input.value.length;
input.setSelectionRange(len, len);
}
}, [selectedProtocol]);
const notificationChannels = useWatch({
control,
name: "notificationChannels",
});
return (
<BasePage component={"form"} onSubmit={handleSubmit(onSubmit)}>
<ConfigBox
title={t("settingsGeneralSettings")}
subtitle={t(`pageSpeedConfigureSettingsDescription`)}
rightContent={
<Stack gap={theme.spacing(8)}>
<RadioGroup
value={selectedProtocol}
sx={{ gap: theme.spacing(6) }}
onChange={(e) => {
setSelectedProtocol(e.target.value);
}}
>
<RadioWithDescription
value="https"
label="HTTPS"
description=""
/>
<RadioWithDescription
value="http"
label={"HTTP"}
description={""}
/>
</RadioGroup>
<Controller
disabled={mode === "configure"}
name="url"
control={control}
render={({ field }) => (
<TextInput
inputRef={urlInputRef}
{...field}
onFocus={(e) => {
const input = e.target;
setTimeout(() => {
input.setSelectionRange(
input.value.length,
input.value.length
);
}, 0);
}}
type="text"
fieldLabel={t("url")}
fullWidth
error={!!errors.url}
helperText={errors.url ? errors.url.message : ""}
/>
)}
/>
<Controller
name="name"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("displayName")}
fullWidth
error={!!errors.name}
helperText={errors.name ? errors.name.message : ""}
/>
)}
/>
<Controller
name="secret"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("infrastructureAuthorizationSecretLabel")}
fullWidth
error={!!errors.secret}
helperText={errors.secret ? errors.secret.message : ""}
/>
)}
/>
</Stack>
}
/>
<ConfigBox
title={t("createMonitorPage.incidentConfigTitle")}
subtitle={t("createMonitorPage.incidentConfigDescriptionV2")}
rightContent={
<Controller
name="n"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="number"
fieldLabel={t("createMonitorPage.incidentConfigStatusCheckNumber")}
fullWidth
error={!!errors.n}
helperText={errors.n ? errors.n.message : ""}
onChange={(e) => {
const target = e.target as HTMLInputElement;
field.onChange(target.valueAsNumber);
}}
/>
)}
/>
}
/>
<ConfigBox
title={t("notificationConfig.title")}
subtitle={t("notificationConfig.description")}
rightContent={
<Stack>
<Controller
name="notificationChannels"
control={control}
defaultValue={[]}
render={({ field }) => (
<AutoComplete
multiple
options={notificationOptions}
getOptionLabel={(option) => option.name}
value={notificationOptions.filter((o: any) =>
(field.value || []).includes(o._id)
)}
onChange={(_, newValue) => {
field.onChange(newValue.map((o: any) => o._id));
}}
/>
)}
/>
<Stack gap={theme.spacing(2)} mt={theme.spacing(2)}>
{notificationChannels.map((notificationId) => {
const option = notificationOptions.find(
(o: any) => o._id === notificationId
);
if (!option) return null;
return (
<Stack
width={"100%"}
justifyContent={"space-between"}
direction="row"
key={notificationId}
>
<Typography>{option.name}</Typography>
<Trash2
size={20}
strokeWidth={1.5}
onClick={() => {
const updated = notificationChannels.filter(
(id) => id !== notificationId
);
setValue("notificationChannels", updated);
}}
style={{ cursor: "pointer" }}
/>
</Stack>
);
})}
</Stack>
</Stack>
}
/>
<ConfigBox
title={t("createMonitorPage.intervalTitle")}
subtitle="How often to check the URL"
rightContent={
<Controller
name="interval"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("createMonitorPage.intervalDescription")}
fullWidth
error={!!errors.interval}
helperText={errors.interval ? errors.interval.message : ""}
/>
)}
/>
}
/>
<Stack direction="row" justifyContent="flex-end">
<Button
loading={loading}
type="submit"
variant="contained"
color="accent"
>
{t("settingsSave")}
</Button>
</Stack>
</BasePage>
);
};
@@ -0,0 +1,102 @@
import {
MonitorBasePageWithStates,
UpStatusBox,
DownStatusBox,
PausedStatusBox,
InfoBox,
} from "@/components/design-elements";
import { HeaderCreate } from "@/components/monitors";
import Stack from "@mui/material/Stack";
import { Dialog } from "@/components/inputs";
import { InfraMonitorsTable } from "./InfraMonitorsTable";
import { useTranslation } from "react-i18next";
import { useTheme } from "@mui/material/styles";
import { useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import type { IMonitor, IMonitorWithStats } from "@/types/monitor";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useState } from "react";
import { useDelete } from "@/hooks/UseApi";
const GLOBAL_REFRESH = import.meta.env.VITE_APP_GLOBAL_REFRESH;
const PageSpeedMonitorsPage = () => {
const theme = useTheme();
const { t } = useTranslation();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const [selectedMonitor, setSelectedMonitor] = useState<IMonitor | null>(null);
const isDialogOpen = Boolean(selectedMonitor);
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);
const { deleteFn } = useDelete();
const { response, loading, isValidating, error, refetch } = useGet<
ApiResponse<IMonitorWithStats>
>(
`/monitors?embedChecks=true&type=infrastructure&page=${page}&rowsPerPage=${rowsPerPage}`,
{},
{
refreshInterval: GLOBAL_REFRESH,
keepPreviousData: true,
dedupingInterval: 0,
},
{
useTeamIdAsKey: true,
}
);
const monitors: IMonitor[] = response?.data?.monitors ?? ([] as IMonitor[]);
const count = response?.data?.count || 0;
const upCount = response?.data?.upCount || 0;
const downCount = response?.data?.downCount || 0;
const pausedCount = response?.data?.pausedCount || 0;
const handleConfirm = async () => {
await deleteFn(`/monitors/${selectedMonitor?._id}`);
setSelectedMonitor(null);
refetch();
};
const handleCancel = () => {
setSelectedMonitor(null);
};
return (
<MonitorBasePageWithStates
loading={isValidating}
error={error}
items={monitors}
page="infrastructure"
actionLink="/infrastructure/create"
>
<InfoBox
title="Server Health Monitoring"
description="Keep track of your servers' vital statistics including CPU usage, memory, disk space, and network performance. Receive alerts when resources run low."
/>
<HeaderCreate isLoading={loading} path="/infrastructure/create" />
<Stack direction={isSmall ? "column" : "row"} gap={theme.spacing(8)}>
<UpStatusBox n={upCount} />
<DownStatusBox n={downCount} />
<PausedStatusBox n={pausedCount} />
</Stack>
<InfraMonitorsTable
monitors={monitors}
refetch={refetch}
setSelectedMonitor={setSelectedMonitor}
count={count}
page={page}
setPage={setPage}
rowsPerPage={rowsPerPage}
setRowsPerPage={setRowsPerPage}
/>
<Dialog
open={isDialogOpen}
title={t("deleteDialogTitle")}
content={t("deleteDialogDescription")}
onConfirm={handleConfirm}
onCancel={handleCancel}
/>
</MonitorBasePageWithStates>
);
};
export default PageSpeedMonitorsPage;
@@ -0,0 +1,202 @@
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { Table, Pagination, StatusLabel } from "@/components/design-elements";
import type { Header } from "@/components/design-elements/Table";
import { ActionsMenu } from "@/components/actions-menu";
import { Gauge } from "@/components/design-elements";
import { useTranslation } from "react-i18next";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useTheme } from "@mui/material/styles";
import { useNavigate } from "react-router-dom";
import { usePatch } from "@/hooks/UseApi";
import type { IMonitor } from "@/types/monitor";
import type { ActionMenuItem } from "@/components/actions-menu";
export const InfraMonitorsTable = ({
monitors,
refetch,
setSelectedMonitor,
count,
page,
setPage,
rowsPerPage,
setRowsPerPage,
}: {
monitors: IMonitor[];
refetch: Function;
setSelectedMonitor: Function;
count: number;
page: number;
setPage: (page: number) => void;
rowsPerPage: number;
setRowsPerPage: (rowsPerPage: number) => void;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const navigate = useNavigate();
const {
patch,
// loading: isPatching,
// error: postError,
} = usePatch<any, IMonitor>();
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);
};
const getActions = (monitor: IMonitor): ActionMenuItem[] => {
return [
{
id: 1,
label: "Open site",
action: () => {
window.open(monitor.url, "_blank", "noreferrer");
},
closeMenu: true,
},
{
id: 2,
label: "Details",
action: () => {
navigate(`${monitor._id}`);
},
},
{
id: 3,
label: "Incidents",
action: () => {
navigate(`/incidents/${monitor._id}`);
},
},
{
id: 4,
label: "Configure",
action: () => {
navigate(`/infrastructure/${monitor._id}/configure`);
},
},
// {
// id: 5,
// label: "Clone",
// action: () => {
// console.log("Open clone");
// },
// },
{
id: 6,
label: monitor.isActive ? "Pause" : "Resume",
action: async () => {
await patch(`/monitors/${monitor._id}/active`);
refetch();
},
closeMenu: true,
},
{
id: 7,
label: <Typography color={theme.palette.error.main}>Remove</Typography>,
action: () => {
setSelectedMonitor(monitor);
},
closeMenu: true,
},
];
};
const getHeaders = () => {
const headers: Header<IMonitor>[] = [
{
id: "name",
content: t("host"),
render: (row) => {
return row.name;
},
},
{
id: "status",
content: t("status"),
render: (row) => {
return <StatusLabel status={row.status} isActive={row.isActive} />;
},
},
{
id: "cpu",
content: t("cpu"),
render: (row) => {
const cpuUsage =
(row.latestChecks?.[0]?.system?.cpu?.usage_percent || 0) * 100;
return <Gauge progress={cpuUsage} />;
},
},
{
id: "memory",
content: t("memory"),
render: (row) => {
const memoryUsage =
(row.latestChecks?.[0]?.system?.memory?.usage_percent || 0) * 100;
return <Gauge progress={memoryUsage} />;
},
},
{
id: "disk",
content: t("disk"),
render: (row) => {
const totalDiskUsage = row.latestChecks?.[0]?.system?.disk.reduce(
(acc, disk) => acc + disk.usage_percent,
0
);
const diskCount = row.latestChecks?.[0]?.system?.disk.length || 1;
const diskUsage = ((totalDiskUsage || 0) / diskCount) * 100;
return <Gauge progress={diskUsage} />;
},
},
{
id: "actions",
content: t("actions"),
render: (row) => {
return <ActionsMenu items={getActions(row)} />;
},
},
];
return headers;
};
let headers = getHeaders();
if (isSmall) {
headers = headers.filter((h) => h.id !== "histogram");
}
return (
<Box>
<Table
headers={headers}
data={monitors}
onRowClick={(row) => {
navigate(`/infrastructure/${row._id}`);
}}
/>
<Pagination
component="div"
count={count}
page={page}
rowsPerPage={rowsPerPage}
onPageChange={handlePageChange}
onRowsPerPageChange={handleRowsPerPageChange}
/>
</Box>
);
};
@@ -0,0 +1,49 @@
import type { IDiskInfo, IHostInfo } from "@/types/check";
export const getFrequency = (frequency: number): string => {
if (!frequency) return "N/A";
const ghz = (frequency / 1000).toFixed(2);
return `${ghz} GHz`;
};
export const getCores = (cores: number) => {
if (!cores) return "N/A";
if (cores === 1) return `${cores} core`;
return `${cores} cores`;
};
export const getAvgTemp = (temps: number[]): string => {
if (!temps || temps.length === 0) return "N/A";
const avgTemp = temps.reduce((a, b) => a + b, 0) / temps.length;
return `${avgTemp.toFixed(2)} °C`;
};
export const getGbs = (bytes: number): string => {
if (!bytes) {
return "N/A";
}
if (bytes === 0) {
return "0 GB";
}
const GB = bytes / (1024 * 1024 * 1024);
const MB = bytes / (1024 * 1024);
if (GB >= 1) {
return GB.toFixed(2) + " GB";
} else {
return MB.toFixed(2) + " MB";
}
};
export const getDiskTotalGbs = (disk: IDiskInfo[]): string => {
const totalBytes =
disk?.reduce((acc, disk) => acc + (disk.total_bytes || 0), 0) || 0;
return getGbs(totalBytes);
};
export const getOsAndPlatform = (hostInfo: IHostInfo): string => {
const os = hostInfo?.pretty_name || hostInfo?.os || "N/A";
const platform = hostInfo?.platform || "N/A";
return `${os} (${platform})`;
};
@@ -0,0 +1,157 @@
import { HeaderCreate } from "@/components/notification-channels/HeaderCreate";
import { BasePageWithStates, InfoBox } from "@/components/design-elements";
import { ActionsMenu } from "@/components/actions-menu";
import { Table } from "@/components/design-elements";
import Typography from "@mui/material/Typography";
import { useTheme } from "@mui/material/styles";
import { Dialog } from "@/components/inputs";
import { useState } from "react";
import { usePatch, useGet, useDelete } from "@/hooks/UseApi";
import { useNavigate } from "react-router";
import type { Header } from "@/components/design-elements/Table";
import { useTranslation } from "react-i18next";
import type { ApiResponse } from "@/hooks/UseApi";
import type { IMaintenance } from "@/types/maintenance";
import type { ActionMenuItem } from "@/components/actions-menu";
const MaintenancePage = () => {
const theme = useTheme();
const { t } = useTranslation();
const [selectedMaintenance, setSelectedMaintenance] =
useState<IMaintenance | null>(null);
const open = Boolean(selectedMaintenance);
const { patch, loading: isPausing } = usePatch<{}, any>();
const { response, isValidating, refetch } = useGet<ApiResponse<any>>(
"/maintenance",
{},
{}
);
const { deleteFn, loading: isDeleting } = useDelete<any>();
const maintenance = response?.data || [];
const navigate = useNavigate();
const handleConfirm = async () => {
if (!selectedMaintenance) return;
const res = await deleteFn(`/maintenance/${selectedMaintenance._id}`);
if (res) {
setSelectedMaintenance(null);
refetch();
}
};
const handleCancel = () => {
setSelectedMaintenance(null);
};
const getActions = (maintenance: IMaintenance): ActionMenuItem[] => {
return [
{
id: 1,
label: "Configure",
action: () => {
navigate(`/maintenance/${maintenance._id}/configure`);
},
closeMenu: true,
},
{
id: 2,
label: maintenance.isActive ? "Disable" : "Enable",
action: async () => {
const res = await patch(`/maintenance/${maintenance._id}/active`, {});
if (res) {
refetch();
}
},
closeMenu: true,
},
{
id: 7,
label: <Typography color={theme.palette.error.main}>Remove</Typography>,
action: async () => {
setSelectedMaintenance(maintenance);
},
closeMenu: true,
},
];
};
const getHeaders = () => {
const headers: Header<IMaintenance>[] = [
{
id: "name",
content: "Name",
render: (row) => {
return <Typography>{row?.name}</Typography>;
},
},
{
id: "active",
content: "Active",
render: (row) => {
const active = row.isActive ? "Yes" : "No";
return <Typography>{active}</Typography>;
},
},
{
id: "repeat",
content: "Repeat",
render: (row) => {
const active = row.repeat ? row.repeat : "No";
return <Typography textTransform={"capitalize"}>{active}</Typography>;
},
},
{
id: "actions",
content: t("actions"),
render: (row) => {
return <ActionsMenu items={getActions(row)} />;
},
},
];
return headers;
};
const headers = getHeaders();
return (
<BasePageWithStates
page="Maintenance windows"
loading={isValidating}
error={null}
items={maintenance}
bullets={t("maintenanceWindow.fallback.checks", { returnObjects: true })}
actionLink="/maintenance/create"
actionButtonText={t("createMaintenanceWindow")}
>
<InfoBox
title="Scheduled Maintenance Periods"
description="Plan maintenance windows to temporarily pause monitoring checks. During maintenance, your monitors won't run checks or send notifications, preventing false alerts during planned downtime."
/>
<HeaderCreate
label={"Create a new maintenance window"}
isLoading={isValidating || isPausing || isDeleting}
path="/maintenance/create"
/>
<Table
headers={headers}
data={maintenance}
onRowClick={(row: IMaintenance) => {
navigate(`/maintenance/${row._id}/configure`);
}}
/>
<Dialog
title={t("createNotifications.dialogDeleteTitle")}
content={t("createNotifications.dialogDeleteContent")}
open={open}
onConfirm={handleConfirm}
onCancel={handleCancel}
/>
</BasePageWithStates>
);
};
export default MaintenancePage;
@@ -0,0 +1,38 @@
import { MaintenanceForm } from "@/pages/maintenance/MaintenanceForm";
import { useParams } from "react-router";
import { useNavigate } from "react-router";
import { z } from "zod";
import { usePatch, useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { maintenanceSchema } from "@/validation/zod";
import type { IMonitor } from "@/types/monitor";
type FormValues = z.infer<typeof maintenanceSchema>;
const MaintenanceConfigPage = () => {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const { patch, loading: isPatching } = usePatch<FormValues, any>();
const { response, loading } = useGet<ApiResponse<any>>(`/maintenance/${id}`);
const { response: monitorsResponse, loading: monitorsLoading } =
useGet<ApiResponse<IMonitor[]>>("/monitors");
const maintenance = response?.data;
const monitors = monitorsResponse?.data || [];
const onSubmit = async (data: FormValues) => {
const res = await patch(`/maintenance/${id}`, data);
if (res) {
navigate(-1);
}
};
return (
<MaintenanceForm
monitorOptions={monitors}
initialData={maintenance}
onSubmit={onSubmit}
loading={loading || isPatching || monitorsLoading}
/>
);
};
export default MaintenanceConfigPage;
@@ -0,0 +1,37 @@
import { MaintenanceForm } from "@/pages/maintenance/MaintenanceForm";
import { useNavigate } from "react-router";
import { z } from "zod";
import { usePost, useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { maintenanceSchema } from "@/validation/zod";
import type { IMonitor } from "@/types/monitor";
import type { IMaintenance } from "@/types/maintenance";
type FormValues = z.infer<typeof maintenanceSchema>;
const MaintenanceCreatePage = () => {
const navigate = useNavigate();
const { post, loading } = usePost<FormValues, IMaintenance>();
const { response, loading: monitorsLoading } =
useGet<ApiResponse<IMonitor[]>>("/monitors");
const monitors = response?.data || [];
console.log(monitors);
const onSubmit = async (data: FormValues) => {
const res = await post("/maintenance", data);
if (res) {
navigate(-1);
}
};
return (
<MaintenanceForm
monitorOptions={monitors}
onSubmit={onSubmit}
loading={loading || monitorsLoading}
/>
);
};
export default MaintenanceCreatePage;
@@ -0,0 +1,229 @@
import Stack from "@mui/material/Stack";
import { Button, DateTimePicker } from "@/components/inputs";
import { ConfigBox, BasePage, InfoBox } from "@/components/design-elements";
import { TextInput, Select, AutoComplete } from "@/components/inputs";
import MenuItem from "@mui/material/MenuItem";
import Typography from "@mui/material/Typography";
import dayjs from "dayjs";
import type { Dayjs } from "dayjs";
import { useTheme } from "@mui/material/styles";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslation } from "react-i18next";
import { z } from "zod";
import { MaintenanceRepeats } from "@/types/maintenance";
import { maintenanceSchema } from "@/validation/zod";
import { useForm, Controller, type SubmitHandler } from "react-hook-form";
import { useEffect } from "react";
import { useInitForm } from "@/hooks/forms/UseInitMaintenanceForm";
import type { IMonitor } from "@/types/monitor";
type FormValues = z.infer<typeof maintenanceSchema>;
export const MaintenanceForm = ({
monitorOptions,
initialData,
onSubmit,
loading,
}: {
monitorOptions: IMonitor[];
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const {
handleSubmit,
control,
reset,
getValues,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(maintenanceSchema),
defaultValues: defaults,
mode: "onChange",
});
useEffect(() => {
reset(defaults);
}, [initialData, reset, defaults]);
const onError = (errors: any) => {
console.log(errors);
console.log(getValues());
};
return (
<BasePage component={"form"} onSubmit={handleSubmit(onSubmit, onError)}>
<InfoBox
title="About Maintenance Windows"
description="During maintenance windows, all monitoring is suspended for selected monitors. No network checks will be performed, preventing any status updates or notifications from being triggered. Your monitors will appear frozen at their last known status, and status pages will display a maintenance indicator. Once the maintenance window ends, monitoring automatically resumes, and alerts will trigger if issues are detected. Maintenance periods do not count against uptime calculations."
/>
<ConfigBox
title={t("createMaintenanceWindowPage.generalSettingsTitle")}
subtitle={t("createMaintenanceWindowPage.generalSettingsDescription")}
rightContent={
<Stack spacing={theme.spacing(8)}>
<Controller
name="name"
control={control}
render={({ field }) => (
<TextInput
{...field}
fieldLabel={t(
"createMaintenanceWindowPage.generalSettingsName"
)}
required
type="text"
placeholder={t(
"createMaintenanceWindowPage.generalSettingsNamePlaceholder"
)}
fullWidth
error={!!errors.name}
helperText={errors.name ? errors.name.message : ""}
/>
)}
/>
<Controller
name="repeat"
control={control}
render={({ field }) => (
<Select
value={field.value || ""}
fieldLabel={t(
"createMaintenanceWindowPage.generalSettingsRepeat"
)}
required
error={!!errors.repeat}
onChange={field.onChange}
fullWidth
>
{MaintenanceRepeats.map((option) => {
return (
<MenuItem key={option} value={option}>
<Typography textTransform={"capitalize"}>
{option}
</Typography>
</MenuItem>
);
})}
</Select>
)}
/>
</Stack>
}
/>
<ConfigBox
title={t("createMaintenanceWindowPage.timingSettingsTitle")}
subtitle={t("createMaintenanceWindowPage.timingSettingsDescription")}
rightContent={
<Stack spacing={theme.spacing(8)}>
<Controller
name="startTime"
control={control}
render={({ field }) => {
const value = field.value ? dayjs(field.value) : null;
return (
<>
<DateTimePicker
{...field}
fieldLabel="Start time"
required
value={value}
onChange={(val: Dayjs | null) =>
field.onChange(val?.toDate())
}
/>
{errors?.startTime?.message && (
<Typography color="error" variant="caption">
{errors.startTime.message}
</Typography>
)}
</>
);
}}
/>
<Controller
name="endTime"
control={control}
render={({ field }) => {
const value = field.value ? dayjs(field.value) : null;
return (
<>
<DateTimePicker
{...field}
fieldLabel="End time"
required
value={value}
onChange={(val: Dayjs | null) =>
field.onChange(val?.toDate())
}
/>
{errors?.endTime?.message && (
<Typography color="error" variant="caption">
{errors.endTime.message}
</Typography>
)}
</>
);
}}
/>
</Stack>
}
/>
<ConfigBox
title={t("createMaintenanceWindowPage.monitorsTitle")}
subtitle={t("createMaintenanceWindowPage.monitorsDescription")}
rightContent={
<Controller
name="monitors"
control={control}
defaultValue={[]}
render={({ field }) => {
const selectedMonitors = monitorOptions.filter((o: any) =>
(field.value || []).includes(o._id)
);
const count = selectedMonitors.length;
return (
<AutoComplete
multiple
fieldLabel="Monitors"
required
options={monitorOptions}
getOptionLabel={(option) => option.name}
value={selectedMonitors}
onChange={(_, newValue) => {
field.onChange(newValue.map((o: any) => o._id));
}}
renderInput={(params) => (
<TextInput
{...params}
placeholder={
count > 0 ? `${count} selected` : "Type to search"
}
/>
)}
/>
);
}}
/>
}
/>
<Stack direction="row" justifyContent="flex-end">
<Button
loading={loading}
type="submit"
variant="contained"
color="accent"
>
{t("settingsSave")}
</Button>
</Stack>
</BasePage>
);
};
@@ -0,0 +1,163 @@
import { HeaderCreate } from "@/components/notification-channels/HeaderCreate";
import Typography from "@mui/material/Typography";
import { BasePageWithStates, InfoBox } from "@/components/design-elements";
import { Table } from "@/components/design-elements";
import { ActionsMenu } from "@/components/actions-menu";
import { Dialog } from "@/components/inputs";
import { useState } from "react";
import { useTheme } from "@mui/material/styles";
import { useNavigate } from "react-router";
import type { ActionMenuItem } from "@/components/actions-menu";
import type { Header } from "@/components/design-elements/Table";
import type { INotificationChannel } from "@/types/notification-channel";
import { useGet, usePatch, useDelete } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { useTranslation } from "react-i18next";
const NotificationChannelsPage = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const theme = useTheme();
const [selectedChannel, setSelectedChannel] =
useState<INotificationChannel | null>(null);
const open = Boolean(selectedChannel);
const { response, isValidating, error, refetch } = useGet<
ApiResponse<INotificationChannel[]>
>("/notification-channels", {}, {});
const { patch, loading: pausing } = usePatch<{}, INotificationChannel>();
const { deleteFn, loading: deleting } =
useDelete<ApiResponse<INotificationChannel>>();
const notificationChannels = response?.data || [];
const handleConfirm = async () => {
if (!selectedChannel) return;
const res = await deleteFn(`/notification-channels/${selectedChannel._id}`);
if (res) {
setSelectedChannel(null);
refetch();
}
};
const handleCancel = () => {
setSelectedChannel(null);
};
const getActions = (channel: INotificationChannel): ActionMenuItem[] => {
return [
{
id: 1,
label: "Configure",
action: () => {
navigate(`/notification-channels/${channel._id}/configure`);
},
closeMenu: true,
},
{
id: 2,
label: channel.isActive ? "Disable" : "Enable",
action: async () => {
const res = await patch(
`/notification-channels/${channel._id}/active`,
{}
);
if (res) {
refetch();
}
},
closeMenu: true,
},
{
id: 7,
label: <Typography color={theme.palette.error.main}>Remove</Typography>,
action: async () => {
setSelectedChannel(channel);
},
closeMenu: true,
},
];
};
const getHeaders = () => {
const headers: Header<INotificationChannel>[] = [
{
id: "name",
content: "Name",
render: (row) => {
return <Typography>{row?.name}</Typography>;
},
},
{
id: "active",
content: "Active",
render: (row) => {
const active = row.isActive ? "Yes" : "No";
return <Typography>{active}</Typography>;
},
},
{
id: "type",
content: "Type",
render: (row) => {
return (
<Typography textTransform={"capitalize"}>{row?.type}</Typography>
);
},
},
{
id: "actions",
content: t("actions"),
render: (row) => {
return <ActionsMenu items={getActions(row)} />;
},
},
];
return headers;
};
const headers = getHeaders();
return (
<BasePageWithStates
page="Notification Channels"
bullets={
t("notifications.fallback.checks", { returnObjects: true }) as string[]
}
loading={isValidating}
error={error}
items={notificationChannels}
actionButtonText="Create a new notification channel"
actionLink="/notification-channels/create"
>
<InfoBox
title="Alert Destinations"
description="Configure where you want to receive alerts when monitors detect issues. Connect email, Slack, Discord, webhooks, and other channels to stay informed."
/>
<HeaderCreate
label={"Create a new notification channel"}
isLoading={isValidating || pausing || deleting}
path="/notification-channels/create"
/>
<Table
headers={headers}
data={notificationChannels}
onRowClick={(row) => {
navigate(`/notification-channels/${row._id}/configure`);
}}
/>
<Dialog
title={t("createNotifications.dialogDeleteTitle")}
content={t("createNotifications.dialogDeleteContent")}
open={open}
onConfirm={handleConfirm}
onCancel={handleCancel}
/>
</BasePageWithStates>
);
};
export default NotificationChannelsPage;
@@ -0,0 +1,40 @@
import { NotificationChannelsForm } from "./NotificationChannelsForm";
import { useParams } from "react-router";
import { useNavigate } from "react-router";
import { z } from "zod";
import { usePatch, useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { notificationChannelSchema } from "@/validation/zod";
import type { INotificationChannel } from "@/types/notification-channel";
type FormValues = z.infer<typeof notificationChannelSchema>;
const NotificationsChannelConfigPage = () => {
const navigate = useNavigate();
const { id } = useParams<{ id: string }>();
const { response, loading } = useGet<ApiResponse<INotificationChannel>>(
`/notification-channels/${id}`
);
const { patch, loading: updating } = usePatch<
FormValues,
INotificationChannel
>();
const notification = response?.data;
const onSubmit = async (data: FormValues) => {
const res = await patch(`/notification-channels/${id}`, data);
if (res) {
navigate(-1);
}
};
return (
<NotificationChannelsForm
initialData={notification}
onSubmit={onSubmit}
loading={loading || updating}
/>
);
};
export default NotificationsChannelConfigPage;
@@ -0,0 +1,24 @@
import { NotificationChannelsForm } from "./NotificationChannelsForm";
import { useNavigate } from "react-router";
import { z } from "zod";
import { usePost } from "@/hooks/UseApi";
import { notificationChannelSchema } from "@/validation/zod";
import type { INotificationChannel } from "@/types/notification-channel";
type FormValues = z.infer<typeof notificationChannelSchema>;
const NotificationsChannelCreatePage = () => {
const { post, loading } = usePost<FormValues, INotificationChannel>();
const navigate = useNavigate();
const onSubmit = async (data: FormValues) => {
const res = await post("/notification-channels", data);
if (res) {
navigate(-1);
}
};
return <NotificationChannelsForm onSubmit={onSubmit} loading={loading} />;
};
export default NotificationsChannelCreatePage;
@@ -0,0 +1,233 @@
import Stack from "@mui/material/Stack";
import { Button } from "@/components/inputs";
import { ConfigBox, BasePage } from "@/components/design-elements";
import { TextInput, Select } from "@/components/inputs";
import MenuItem from "@mui/material/MenuItem";
import { usePost } from "@/hooks/UseApi";
import { useToast } from "@/hooks/UseToast";
import { ChannelTypes } from "@/types/notification-channel";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslation } from "react-i18next";
import { z } from "zod";
import { notificationChannelSchema } from "@/validation/zod";
import { useForm, Controller, type SubmitHandler } from "react-hook-form";
import { useEffect } from "react";
import { useInitForm } from "@/hooks/forms/UseInitNotificationsChannelForm";
import { Typography } from "@mui/material";
import { useTheme } from "@mui/material/styles";
type FormValues = z.infer<typeof notificationChannelSchema>;
export const NotificationChannelsForm = ({
initialData,
onSubmit,
loading,
}: {
mode?: string;
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
loading: boolean;
}) => {
const { t } = useTranslation();
const { defaults } = useInitForm({ initialData: initialData });
const { post, loading: isPosting } = usePost();
const theme = useTheme();
const { toastSuccess } = useToast();
const {
handleSubmit,
control,
reset,
watch,
getValues,
trigger,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(notificationChannelSchema),
defaultValues: defaults,
mode: "onChange",
});
useEffect(() => {
reset(defaults);
}, [initialData, reset, defaults]);
const type = watch("type");
const onError = (errors: any) => {
console.log(errors);
console.log(getValues());
};
const handleTest = async () => {
const isValid = await trigger();
if (isValid) {
const res = await post("/notification-channels/test", getValues());
if (res) {
toastSuccess("Success");
}
}
};
return (
<BasePage component={"form"} onSubmit={handleSubmit(onSubmit, onError)}>
<ConfigBox
title={t("createNotifications.nameSettings.title")}
subtitle={t("createNotifications.nameSettings.description")}
rightContent={
<Controller
name="name"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("createNotifications.nameSettings.nameLabel")}
placeholder="e.g. Production Alerts"
fullWidth
error={!!errors.name}
helperText={errors.name ? errors.name.message : ""}
/>
)}
/>
}
/>
<ConfigBox
title={t("createNotifications.typeSettings.title")}
subtitle={t("createNotifications.typeSettings.description")}
rightContent={
<Controller
name="type"
control={control}
defaultValue={defaults.type}
render={({ field }) => {
return (
<Select
value={field.value}
fieldLabel={t("createNotifications.typeSettings.title")}
error={!!errors.type}
onChange={field.onChange}
>
{ChannelTypes.map((type: string) => {
return (
<MenuItem key={type} value={type}>
<Typography textTransform={"capitalize"}>
{type}
</Typography>
</MenuItem>
);
})}
</Select>
);
}}
/>
}
/>
<ConfigBox
title={type ? `${type} configuration` : "Config"}
subtitle={
type === "email"
? "Configure the email address where notifications will be sent"
: type === "webhook"
? "Configure the webhook URL endpoint where notifications will be sent"
: type === "slack"
? "Configure your Slack webhook URL. Create one in Slack: Settings & administration → Manage apps → Custom Integrations → Incoming Webhooks"
: type === "discord"
? "Configure your Discord webhook URL. Create one in Discord: Server Settings → Integrations → Webhooks → New Webhook"
: "Configure notification channel settings"
}
rightContent={
type === "email" ? (
<Controller
name="config.emailAddress"
control={control}
defaultValue={defaults.config.emailAddress}
render={({ field }) => {
return (
<TextInput
{...field}
type="text"
fieldLabel={t(
"createNotifications.emailSettings.description"
)}
placeholder="e.g. john@example.com"
fullWidth
error={!!errors.config?.emailAddress}
helperText={
errors.config?.emailAddress
? errors.config.emailAddress.message
: ""
}
/>
);
}}
/>
) : (
<Controller
name="config.url"
control={control}
defaultValue={defaults.config.url}
render={({ field }) => {
const getPlaceholder = () => {
switch (type) {
case "slack":
return "https://hooks.slack.com/services/YOUR/WEBHOOK/URL";
case "discord":
return "https://discord.com/api/webhooks/YOUR/WEBHOOK/URL";
case "webhook":
return "https://your-server.com/webhook";
default:
return "https://example.com/webhook";
}
};
return (
<TextInput
{...field}
type="text"
fieldLabel={
type
? `${
type.charAt(0).toUpperCase() + type.slice(1)
} webhook URL`
: "URL"
}
placeholder={getPlaceholder()}
fullWidth
error={!!errors.config?.url}
helperText={
errors.config?.url ? errors.config.url.message : ""
}
/>
);
}}
/>
)
}
/>
<Stack
direction="row"
justifyContent="flex-end"
spacing={theme.spacing(2)}
>
<Button
variant="contained"
color="accent"
onClick={handleTest}
loading={isPosting || loading}
>
Test
</Button>
<Button
loading={isPosting || loading}
type="submit"
variant="contained"
color="accent"
>
{t("settingsSave")}
</Button>
</Stack>
</BasePage>
);
};
@@ -0,0 +1,62 @@
import { monitorSchemaPageSpeed } from "@/validation/zod";
import { useGet, usePatch } from "@/hooks/UseApi";
import { PageSpeedForm } from "@/pages/pagespeed/PageSpeedForm";
import { useParams } from "react-router";
import type { ApiResponse } from "@/hooks/UseApi";
import humanInterval from "human-interval";
import { z } from "zod";
import { useNavigate } from "react-router";
import type { INotificationChannel } from "@/types/notification-channel";
import type { IMonitor } from "@/types/monitor";
const PageSpeedConfigurePage = () => {
type FormValues = z.infer<typeof monitorSchemaPageSpeed>;
type SubmitValues = Omit<FormValues, "interval"> & {
interval: number | undefined;
};
const { id } = useParams();
const navigate = useNavigate();
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
"/notification-channels"
);
const { response: monitorResponse } = useGet<ApiResponse<any>>(
`/monitors/${id}`
);
const monitor = monitorResponse?.data;
const notificationOptions = response?.data ?? [];
const { patch, loading, error } = usePatch<Partial<SubmitValues>, IMonitor>();
const onSubmit = async (data: FormValues) => {
let interval = humanInterval(data.interval);
if (!interval) interval = 180000;
const submitData = {
type: data.type,
name: data.name,
notificationChannels: data.notificationChannels,
interval,
};
console.log(submitData);
const result = await patch(`/monitors/${id}`, submitData);
if (result) {
navigate(`/pagespeed/${id}`);
} else {
console.error(error);
}
};
return (
<PageSpeedForm
mode="configure"
initialData={{
...monitor,
}}
onSubmit={onSubmit}
notificationOptions={notificationOptions}
loading={loading}
/>
);
};
export default PageSpeedConfigurePage;
@@ -0,0 +1,43 @@
import { PageSpeedForm } from "@/pages/pagespeed/PageSpeedForm";
import humanInterval from "human-interval";
import { z } from "zod";
import { monitorSchema } from "@/validation/zod";
import { useGet, usePost } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { useNavigate } from "react-router";
import type { INotificationChannel } from "@/types/notification-channel";
const UptimeCreatePage = () => {
type FormValues = z.infer<typeof monitorSchema>;
type SubmitValues = Omit<FormValues, "interval"> & {
interval: number | undefined;
};
const navigate = useNavigate();
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
"/notification-channels"
);
const { post, loading, error } = usePost<SubmitValues>();
const onSubmit = async (data: FormValues) => {
let interval = humanInterval(data.interval);
if (!interval) interval = 60000;
const submitData = { ...data, interval };
const result = await post("/monitors", submitData);
if (result) {
navigate("/pagespeed");
} else {
console.error(error);
}
};
const notificationOptions = response?.data ?? [];
return (
<PageSpeedForm
onSubmit={onSubmit}
notificationOptions={notificationOptions}
loading={loading}
/>
);
};
export default UptimeCreatePage;
@@ -0,0 +1,97 @@
import Stack from "@mui/material/Stack";
import { BasePage, StatBox } from "@/components/design-elements";
import { HeaderControls, HeaderRange } from "@/components/monitors";
import { HistogramPageSpeedScores } from "@/components/monitors/HistogramPageSpeedScores";
import { ChartPageSpeedReport } from "@/components/monitors/ChartPageSpeedReport";
import { ChartPageSpeedReportLegend } from "@/components/monitors/ChartPageSpeedReportLegend";
import { useState } from "react";
import { useParams } from "react-router";
import { useTheme } from "@mui/material/styles";
import { useGet, usePatch } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import type { IMonitor, IMonitorWithMonitorStats } from "@/types/monitor";
import { getStatusPalette } from "@/utils/MonitorUtils";
import prettyMilliseconds from "pretty-ms";
import useMediaQuery from "@mui/material/useMediaQuery";
const GLOBAL_REFRESH = import.meta.env.VITE_APP_GLOBAL_REFRESH;
const PageSpeedDetailsPage = () => {
const theme = useTheme();
const { id } = useParams();
const [range, setRange] = useState("2h");
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const { patch, loading: isPatching } = usePatch<any, IMonitor>();
const { response, isValidating, refetch } = useGet<
ApiResponse<IMonitorWithMonitorStats>
>(
`/monitors/${id}?embedChecks=true&range=${range}`,
{},
{ refreshInterval: GLOBAL_REFRESH, keepPreviousData: true }
);
const monitor = response?.data?.monitor;
const stats = response?.data?.stats;
const checks = response?.data?.checks || [];
console.log(checks);
const streakDuration = stats?.currentStreakStartedAt
? Date.now() - stats?.currentStreakStartedAt
: 0;
const lastChecked = stats?.lastCheckTimestamp
? Date.now() - stats?.lastCheckTimestamp
: -1;
if (!monitor) {
return null;
}
const palette = getStatusPalette(monitor?.status);
return (
<BasePage>
<HeaderControls
monitor={monitor}
patch={patch}
isPatching={isPatching}
refetch={refetch}
path="/pagespeed"
/>
<Stack direction="row" gap={theme.spacing(8)}>
<StatBox
palette={palette}
title="Active for"
subtitle={prettyMilliseconds(streakDuration, {
secondsDecimalDigits: 0,
})}
/>
<StatBox
title="Last check"
subtitle={
lastChecked >= 0
? `${prettyMilliseconds(lastChecked, {
secondsDecimalDigits: 0,
})} ago`
: "N/A"
}
/>
<StatBox
title="Last response time"
subtitle={
stats?.lastResponseTime ? `${stats?.lastResponseTime} ms` : "N/A"
}
/>
</Stack>
<HeaderRange loading={isValidating} range={range} setRange={setRange} />
<HistogramPageSpeedScores checks={checks} />
<Stack direction={isSmall ? "column" : "row"} gap={theme.spacing(10)}>
<ChartPageSpeedReport latestCheck={checks?.[0]} />
<ChartPageSpeedReportLegend latestCheck={checks?.[0]} />
</Stack>
</BasePage>
);
};
export default PageSpeedDetailsPage;
@@ -0,0 +1,279 @@
import Stack from "@mui/material/Stack";
import {
TextInput,
Button,
RadioWithDescription,
AutoComplete,
} from "@/components/inputs";
import RadioGroup from "@mui/material/RadioGroup";
import { ConfigBox, BasePage } from "@/components/design-elements";
import { Trash2 } from "lucide-react";
import { Typography } from "@mui/material";
import { useEffect, useState, useRef } from "react";
import { useTranslation } from "react-i18next";
import { monitorSchemaPageSpeed } from "@/validation/zod";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
useForm,
Controller,
useWatch,
type SubmitHandler,
} from "react-hook-form";
import { useTheme } from "@mui/material/styles";
import { useInitForm } from "@/hooks/forms/UseInitPageSpeedForm";
type FormValues = z.infer<typeof monitorSchemaPageSpeed>;
export const PageSpeedForm = ({
mode = "create",
initialData,
onSubmit,
notificationOptions,
loading,
}: {
mode?: "create" | "configure";
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
notificationOptions: any[];
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const urlInputRef = useRef<HTMLInputElement>(null);
const [selectedProtocol, setSelectedProtocol] = useState<string>("https");
const {
handleSubmit,
control,
setValue,
reset,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(monitorSchemaPageSpeed) as any,
defaultValues: defaults,
mode: "onChange",
});
const url = useWatch({ control, name: "url" });
useEffect(() => {
reset(defaults);
if (defaults.url.startsWith("http://")) {
setSelectedProtocol("http");
}
}, [initialData, reset, defaults]);
useEffect(() => {
if (!url) {
setValue("url", `${selectedProtocol}://`);
}
const hasProtocol = /^(http|https):\/\//i.test(url);
if (hasProtocol) {
const newUrl = url.replace(
/^(http|https):\/\//i,
`${selectedProtocol}://`
);
if (newUrl !== url) setValue("url", newUrl);
} else {
setValue("url", `${selectedProtocol}://${url}`);
}
}, [selectedProtocol, setValue, url]);
useEffect(() => {
const input = urlInputRef.current;
if (input) {
const len = input.value.length;
input.setSelectionRange(len, len);
}
}, [selectedProtocol]);
const notificationChannels = useWatch({
control,
name: "notificationChannels",
});
return (
<BasePage component={"form"} onSubmit={handleSubmit(onSubmit)}>
<ConfigBox
title={t("settingsGeneralSettings")}
subtitle={t(`pageSpeedConfigureSettingsDescription`)}
rightContent={
<Stack gap={theme.spacing(8)}>
<RadioGroup
value={selectedProtocol}
sx={{ gap: theme.spacing(6) }}
onChange={(e) => {
setSelectedProtocol(e.target.value);
}}
>
<RadioWithDescription
value="https"
label="HTTPS"
description=""
/>
<RadioWithDescription
value="http"
label={"HTTP"}
description={""}
/>
</RadioGroup>
<Controller
disabled={mode === "configure"}
name="url"
control={control}
render={({ field }) => (
<TextInput
inputRef={urlInputRef}
{...field}
onFocus={(e) => {
const input = e.target;
setTimeout(() => {
input.setSelectionRange(
input.value.length,
input.value.length
);
}, 0);
}}
type="text"
fieldLabel={t("url")}
fullWidth
error={!!errors.url}
helperText={errors.url ? errors.url.message : ""}
/>
)}
/>
<Controller
name="name"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("displayName")}
fullWidth
error={!!errors.name}
helperText={errors.name ? errors.name.message : ""}
/>
)}
/>
</Stack>
}
/>
<ConfigBox
title={t("createMonitorPage.incidentConfigTitle")}
subtitle={t("createMonitorPage.incidentConfigDescriptionV2")}
rightContent={
<Controller
name="n"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="number"
fieldLabel={t("createMonitorPage.incidentConfigStatusCheckNumber")}
fullWidth
error={!!errors.n}
helperText={errors.n ? errors.n.message : ""}
onChange={(e) => {
const target = e.target as HTMLInputElement;
field.onChange(target.valueAsNumber);
}}
/>
)}
/>
}
/>
<ConfigBox
title={t("notificationConfig.title")}
subtitle={t("notificationConfig.description")}
rightContent={
<Stack>
<Controller
name="notificationChannels"
control={control}
defaultValue={[]}
render={({ field }) => (
<AutoComplete
multiple
options={notificationOptions}
getOptionLabel={(option) => option.name}
value={notificationOptions.filter((o: any) =>
(field.value || []).includes(o._id)
)}
onChange={(_, newValue) => {
field.onChange(newValue.map((o: any) => o._id));
}}
/>
)}
/>
<Stack gap={theme.spacing(2)} mt={theme.spacing(2)}>
{notificationChannels.map((notificationId) => {
const option = notificationOptions.find(
(o: any) => o._id === notificationId
);
if (!option) return null;
return (
<Stack
width={"100%"}
justifyContent={"space-between"}
direction="row"
key={notificationId}
>
<Typography>{option.name}</Typography>
<Trash2
size={20}
strokeWidth={1.5}
onClick={() => {
const updated = notificationChannels.filter(
(id) => id !== notificationId
);
setValue("notificationChannels", updated);
}}
style={{ cursor: "pointer" }}
/>
</Stack>
);
})}
</Stack>
</Stack>
}
/>
<ConfigBox
title={t("createMonitorPage.intervalTitle")}
subtitle="How often to check the URL"
rightContent={
<Controller
name="interval"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("createMonitorPage.intervalDescription")}
fullWidth
error={!!errors.interval}
helperText={errors.interval ? errors.interval.message : ""}
/>
)}
/>
}
/>
<Stack direction="row" justifyContent="flex-end">
<Button
loading={loading}
type="submit"
variant="contained"
color="accent"
>
{t("settingsSave")}
</Button>
</Stack>
</BasePage>
);
};
@@ -0,0 +1,186 @@
import Stack from "@mui/material/Stack";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { Table, Pagination, StatusLabel } from "@/components/design-elements";
import { HistogramPageSpeed } from "@/components/monitors";
import type { Header } from "@/components/design-elements/Table";
import { ActionsMenu } from "@/components/actions-menu";
import { useTranslation } from "react-i18next";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useTheme } from "@mui/material/styles";
import { useNavigate } from "react-router-dom";
import { usePatch } from "@/hooks/UseApi";
import type { IMonitor } from "@/types/monitor";
import type { ActionMenuItem } from "@/components/actions-menu";
export const PageSpeedMonitorTable = ({
monitors,
refetch,
setSelectedMonitor,
count,
page,
setPage,
rowsPerPage,
setRowsPerPage,
}: {
monitors: IMonitor[];
refetch: Function;
setSelectedMonitor: Function;
count: number;
page: number;
setPage: (page: number) => void;
rowsPerPage: number;
setRowsPerPage: (rowsPerPage: number) => void;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const navigate = useNavigate();
const {
patch,
// loading: isPatching,
// error: postError,
} = usePatch<any, IMonitor>();
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);
};
const getActions = (monitor: IMonitor): ActionMenuItem[] => {
return [
{
id: 1,
label: "Open site",
action: () => {
window.open(monitor.url, "_blank", "noreferrer");
},
closeMenu: true,
},
{
id: 2,
label: "Details",
action: () => {
navigate(`${monitor._id}`);
},
},
{
id: 3,
label: "Incidents",
action: () => {
navigate(`/incidents/${monitor._id}`);
},
},
{
id: 4,
label: "Configure",
action: () => {
navigate(`/pagespeed/${monitor._id}/configure`);
},
},
// {
// id: 5,
// label: "Clone",
// action: () => {
// console.log("Open clone");
// },
// },
{
id: 6,
label: monitor.isActive ? "Pause" : "Resume",
action: async () => {
await patch(`/monitors/${monitor._id}/active`);
refetch();
},
closeMenu: true,
},
{
id: 7,
label: <Typography color={theme.palette.error.main}>Remove</Typography>,
action: () => {
setSelectedMonitor(monitor);
},
closeMenu: true,
},
];
};
const getHeaders = () => {
const headers: Header<IMonitor>[] = [
{
id: "name",
content: t("host"),
render: (row) => {
return row.name;
},
},
{
id: "status",
content: t("status"),
render: (row) => {
return <StatusLabel status={row.status} isActive={row.isActive} />;
},
},
{
id: "histogram",
content: "PageSpeed score",
render: (row) => {
return (
<Stack alignItems={"center"}>
<HistogramPageSpeed
checks={row.latestChecks}
status={row.status}
/>
</Stack>
);
},
},
{
id: "actions",
content: t("actions"),
render: (row) => {
return <ActionsMenu items={getActions(row)} />;
},
},
];
return headers;
};
let headers = getHeaders();
if (isSmall) {
headers = headers.filter((h) => h.id !== "histogram");
}
return (
<Box>
<Table
headers={headers}
data={monitors}
onRowClick={(row) => {
navigate(`/pagespeed/${row._id}`);
}}
/>
<Pagination
component="div"
count={count}
page={page}
rowsPerPage={rowsPerPage}
onPageChange={handlePageChange}
onRowsPerPageChange={handleRowsPerPageChange}
/>
</Box>
);
};
@@ -0,0 +1,102 @@
import {
MonitorBasePageWithStates,
UpStatusBox,
DownStatusBox,
PausedStatusBox,
InfoBox,
} from "@/components/design-elements";
import { HeaderCreate } from "@/components/monitors";
import Stack from "@mui/material/Stack";
import { Dialog } from "@/components/inputs";
import { PageSpeedMonitorTable } from "./PageSpeedMonitorTable";
import { useTranslation } from "react-i18next";
import { useTheme } from "@mui/material/styles";
import { useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import type { IMonitor, IMonitorWithStats } from "@/types/monitor";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useState } from "react";
import { useDelete } from "@/hooks/UseApi";
const GLOBAL_REFRESH = import.meta.env.VITE_APP_GLOBAL_REFRESH;
const PageSpeedMonitorsPage = () => {
const theme = useTheme();
const { t } = useTranslation();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const [selectedMonitor, setSelectedMonitor] = useState<IMonitor | null>(null);
const isDialogOpen = Boolean(selectedMonitor);
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);
const { deleteFn } = useDelete();
const { response, loading, isValidating, error, refetch } = useGet<
ApiResponse<IMonitorWithStats>
>(
`/monitors?embedChecks=true&type=pagespeed&page=${page}&rowsPerPage=${rowsPerPage}`,
{},
{
refreshInterval: GLOBAL_REFRESH,
keepPreviousData: true,
dedupingInterval: 0,
},
{
useTeamIdAsKey: true,
}
);
const monitors: IMonitor[] = response?.data?.monitors ?? ([] as IMonitor[]);
const count = response?.data?.count || 0;
const upCount = response?.data?.upCount || 0;
const downCount = response?.data?.downCount || 0;
const pausedCount = response?.data?.pausedCount || 0;
const handleConfirm = async () => {
await deleteFn(`/monitors/${selectedMonitor?._id}`);
setSelectedMonitor(null);
refetch();
};
const handleCancel = () => {
setSelectedMonitor(null);
};
return (
<MonitorBasePageWithStates
loading={isValidating}
error={error}
items={monitors}
page="pageSpeed"
actionLink="/pagespeed/create"
>
<InfoBox
title="Website Performance Tracking"
description="Measure how fast your websites load and identify performance bottlenecks. Track Core Web Vitals and get actionable insights to improve user experience."
/>
<HeaderCreate isLoading={loading} path="/pagespeed/create" />
<Stack direction={isSmall ? "column" : "row"} gap={theme.spacing(8)}>
<UpStatusBox n={upCount} />
<DownStatusBox n={downCount} />
<PausedStatusBox n={pausedCount} />
</Stack>
<PageSpeedMonitorTable
monitors={monitors}
refetch={refetch}
setSelectedMonitor={setSelectedMonitor}
count={count}
page={page}
setPage={setPage}
rowsPerPage={rowsPerPage}
setRowsPerPage={setRowsPerPage}
/>
<Dialog
open={isDialogOpen}
title={t("deleteDialogTitle")}
content={t("deleteDialogDescription")}
onConfirm={handleConfirm}
onCancel={handleCancel}
/>
</MonitorBasePageWithStates>
);
};
export default PageSpeedMonitorsPage;
+48
View File
@@ -0,0 +1,48 @@
import { BasePage, InfoBox } from "@/components/design-elements";
import { ProfileForm } from "@/pages/profile/ProfileForm";
import { useState, useEffect } from "react";
import type { IUser } from "@/types/user";
import type { ApiResponse } from "@/hooks/UseApi";
import { useGet, usePatch } from "@/hooks/UseApi";
import { z } from "zod";
import { profileSchema } from "@/validation/zod";
type FormValues = z.infer<typeof profileSchema>;
const Profile = () => {
const [user, setUser] = useState<Partial<IUser> | null>(null);
const { response, loading } = useGet<ApiResponse<any>>(`/profile`, {}, {});
useEffect(() => {
if (response?.data) setUser(response.data);
}, [response]);
const { patch, loading: isPatching } = usePatch<FormValues, Partial<IUser>>();
const onSubmit = async (data: FormValues) => {
const res = await patch(`/profile`, data);
if (res) {
setUser(res.data);
}
};
const initialData = {
firstName: user?.firstName || "",
lastName: user?.lastName || "",
};
return (
<BasePage>
<InfoBox
title="View and edit your profile"
description="You can set your name and password here"
/>
<ProfileForm
user={user}
onSubmit={onSubmit}
loading={loading || isPatching}
initialData={initialData}
/>
</BasePage>
);
};
export default Profile;
+151
View File
@@ -0,0 +1,151 @@
import Stack from "@mui/material/Stack";
import { TextInput } from "@/components/inputs";
import { Button } from "@/components/inputs";
import { useForm, Controller } from "react-hook-form";
import type { Resolver, SubmitHandler } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect } from "react";
import { z } from "zod";
import { useTranslation } from "react-i18next";
import { useTheme } from "@mui/material/styles";
import { useInitForm } from "@/hooks/forms/UseInitProfileForm";
import type { IUser } from "@/types/user";
import { profileSchema } from "@/validation/zod";
type FormData = z.infer<typeof profileSchema>;
export const ProfileForm = ({
user,
initialData,
onSubmit,
loading,
}: {
user: Partial<IUser> | null;
hasUser?: boolean;
initialData?: Partial<FormData>;
onSubmit: SubmitHandler<FormData>;
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const resolver = zodResolver(profileSchema) as unknown as Resolver<FormData>;
const {
handleSubmit,
control,
reset,
formState: { errors },
} = useForm<FormData>({
resolver,
defaultValues: {
firstName: "",
lastName: "",
password: undefined,
confirmPassword: undefined,
},
});
useEffect(() => {
reset(defaults);
}, [initialData, reset, defaults]);
return (
<Stack
component="form"
padding={theme.spacing(8)}
gap={theme.spacing(12)}
onSubmit={handleSubmit(onSubmit)}
maxWidth={400}
sx={{
width: {
sm: "80%",
md: "70%",
lg: "65%",
xl: "65%",
},
}}
>
{/* Can add control later */}
<TextInput
value={user?.email || ""}
disabled
fieldLabel={t("auth.common.inputs.email.label")}
fullWidth
placeholder={t("auth.common.inputs.email.placeholder")}
/>
<Controller
name="firstName"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
fieldLabel={t("auth.common.inputs.firstName.label")}
fullWidth
placeholder={t("auth.common.inputs.firstName.placeholder")}
error={!!errors.firstName}
helperText={errors.firstName ? errors.firstName.message : ""}
/>
)}
/>
<Controller
name="lastName"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
fieldLabel={t("auth.common.inputs.lastName.label")}
fullWidth
placeholder={t("auth.common.inputs.lastName.placeholder")}
error={!!errors.lastName}
helperText={errors.lastName ? errors.lastName.message : ""}
/>
)}
/>
<Controller
name="password"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
type="password"
fieldLabel={t("auth.common.inputs.password.label")}
fullWidth
error={!!errors.password}
helperText={errors.password ? errors.password.message : ""}
/>
)}
/>
<Controller
name="confirmPassword"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
type="password"
fieldLabel={t("auth.common.inputs.passwordConfirm.label")}
fullWidth
error={!!errors.confirmPassword}
helperText={
errors.confirmPassword ? errors.confirmPassword.message : ""
}
/>
)}
/>
<Button
variant="contained"
loading={loading}
color="accent"
type="submit"
sx={{ width: "100%", alignSelf: "center", fontWeight: 700 }}
>
Update profile
</Button>
</Stack>
);
};
+27
View File
@@ -0,0 +1,27 @@
import { AuthBasePage } from "@/components/auth";
import { RecoveryForm } from "./RecoveryForm";
import { recoverySchema } from "@/validation/zod";
import { z } from "zod";
import { usePost } from "@/hooks/UseApi";
import { useToast } from "@/hooks/UseToast";
type FormData = z.infer<typeof recoverySchema>;
const Recovery = () => {
const { post, loading } = usePost<FormData>();
const { showToast } = useToast();
const onSubmit = async (data: FormData) => {
await post("/recovery", data);
showToast("If the email exists, a recovery link has been sent");
};
return (
<AuthBasePage title="Enter your email to recover your account">
<RecoveryForm onSubmit={onSubmit} loading={loading} />
</AuthBasePage>
);
};
export default Recovery;
@@ -0,0 +1,89 @@
import Stack from "@mui/material/Stack";
import { TextInput } from "@/components/inputs";
import { Button } from "@/components/inputs";
import { useForm, Controller } from "react-hook-form";
import type { SubmitHandler } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect } from "react";
import { z } from "zod";
import { useTranslation } from "react-i18next";
import { useTheme } from "@mui/material/styles";
import { useInitForm } from "@/hooks/forms/UseInitRegisterForm";
import { recoverySchema } from "@/validation/zod";
type FormData = z.infer<typeof recoverySchema>;
export const RecoveryForm = ({
initialData,
onSubmit,
loading,
}: {
initialData?: Partial<FormData>;
onSubmit: SubmitHandler<FormData>;
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const {
handleSubmit,
control,
reset,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(recoverySchema),
defaultValues: {
email: "",
},
});
useEffect(() => {
reset(defaults);
}, [initialData, reset, defaults]);
return (
<Stack
component="form"
padding={theme.spacing(8)}
gap={theme.spacing(12)}
onSubmit={handleSubmit(onSubmit)}
maxWidth={400}
sx={{
width: {
sm: "80%",
md: "70%",
lg: "65%",
xl: "65%",
},
}}
>
<Controller
name="email"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
fieldLabel={t("auth.common.inputs.email.label")}
fullWidth
placeholder={t("auth.common.inputs.email.placeholder")}
error={!!errors.email}
helperText={errors.email ? errors.email.message : ""}
/>
)}
/>
<Button
variant="contained"
loading={loading}
color="accent"
type="submit"
sx={{ width: "100%", alignSelf: "center", fontWeight: 700 }}
>
Request recovery email
</Button>
</Stack>
);
};
+54
View File
@@ -0,0 +1,54 @@
import { AuthBasePage } from "@/components/auth";
import { useParams } from "react-router";
import { ResetForm } from "@/pages/recovery/ResetForm";
import { resetSchema } from "@/validation/zod";
import { z } from "zod";
import { usePost } from "@/hooks/UseApi";
import { useToast } from "@/hooks/UseToast";
import { useNavigate } from "react-router";
import { useAppDispatch } from "@/hooks/AppHooks";
import {
setAuthenticated,
setUser,
setSelectedTeamId,
logout,
} from "@/features/authSlice";
type FormData = z.infer<typeof resetSchema>;
const Reset = () => {
const dispatch = useAppDispatch();
const navigate = useNavigate();
const { post, loading } = usePost<{ password: string; token: string }>();
const { toastSuccess } = useToast();
const { id: token } = useParams<{ id: string }>();
const onSubmit = async (data: FormData) => {
const result = await post(`/recovery/reset`, {
password: data.password,
token: token || "",
});
const user = result?.data || null;
if (!user) {
dispatch(logout());
navigate("/login");
return;
}
toastSuccess("Password reset successful!");
dispatch(setAuthenticated(true));
dispatch(setUser(user));
dispatch(setSelectedTeamId(user.teams[0]?.id || null));
navigate("/");
};
return (
<AuthBasePage title="Set a new password">
<ResetForm onSubmit={onSubmit} loading={loading} />
</AuthBasePage>
);
};
export default Reset;
+109
View File
@@ -0,0 +1,109 @@
import Stack from "@mui/material/Stack";
import { TextInput } from "@/components/inputs";
import { Button } from "@/components/inputs";
import { useForm, Controller } from "react-hook-form";
import type { SubmitHandler } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect } from "react";
import { z } from "zod";
import { useTranslation } from "react-i18next";
import { useTheme } from "@mui/material/styles";
import { useInitForm } from "@/hooks/forms/UseInitResetForm";
import { resetSchema } from "@/validation/zod";
type FormData = z.infer<typeof resetSchema>;
export const ResetForm = ({
initialData,
onSubmit,
loading,
}: {
hasUser?: boolean;
initialData?: Partial<FormData>;
onSubmit: SubmitHandler<FormData>;
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const {
handleSubmit,
control,
reset,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(resetSchema),
defaultValues: {
password: "",
confirmPassword: "",
},
});
useEffect(() => {
reset(defaults);
}, [initialData, reset, defaults]);
return (
<Stack
component="form"
padding={theme.spacing(8)}
gap={theme.spacing(12)}
onSubmit={handleSubmit(onSubmit)}
maxWidth={400}
sx={{
width: {
sm: "80%",
md: "70%",
lg: "65%",
xl: "65%",
},
}}
>
<Controller
name="password"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
type="password"
fieldLabel={t("auth.common.inputs.password.label")}
fullWidth
placeholder="••••••••••"
error={!!errors.password}
helperText={errors.password ? errors.password.message : ""}
/>
)}
/>
<Controller
name="confirmPassword"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
type="password"
fieldLabel={t("auth.common.inputs.passwordConfirm.label")}
fullWidth
placeholder={t("auth.common.inputs.passwordConfirm.placeholder")}
error={!!errors.confirmPassword}
helperText={
errors.confirmPassword ? errors.confirmPassword.message : ""
}
/>
)}
/>
<Button
variant="contained"
loading={loading}
color="accent"
type="submit"
sx={{ width: "100%", alignSelf: "center", fontWeight: 700 }}
>
Submit new password
</Button>
</Stack>
);
};
+69
View File
@@ -0,0 +1,69 @@
import Stack from "@mui/material/Stack";
import { BasePage, ConfigBox } from "@/components/design-elements";
import { AutoComplete, Select, LanguageSelector } from "@/components/inputs";
import MenuItem from "@mui/material/MenuItem";
import Typography from "@mui/material/Typography";
import { useTheme } from "@mui/material/styles";
import { useEffect, useState } from "react";
import { setTimezone, setMode } from "@/features/uiSlice";
import { useAppSelector, useAppDispatch } from "@/hooks/AppHooks";
import timezones from "@/utils/timezones.json";
import type { ITimeZone } from "@/types/timezone";
import type { SelectChangeEvent } from "@mui/material/Select";
const SettingsPage = () => {
const theme = useTheme();
const dispatch = useAppDispatch();
const timezone = useAppSelector((state) => state.ui.timezone);
const mode = useAppSelector((state) => state.ui.mode);
const [selectedTimezone, setSelectedTimezone] = useState<ITimeZone | null>(
null
);
useEffect(() => {
const tz = timezones.find((tz) => tz._id === timezone);
setSelectedTimezone(tz || null);
}, [timezone]);
return (
<BasePage>
<ConfigBox
title="UI Settings"
subtitle="Configure time zone, UI mode, and language preferences"
rightContent={
<Stack spacing={theme.spacing(8)}>
<Stack spacing={theme.spacing(2)}>
<Typography>Time zone</Typography>
<AutoComplete
value={selectedTimezone}
options={timezones as ITimeZone[]}
getOptionLabel={(option) => option.name}
onChange={(_, timezone: ITimeZone) => {
dispatch(setTimezone(timezone._id));
}}
/>
</Stack>
<Stack spacing={theme.spacing(2)}>
<Typography>UI Mode</Typography>
<Select
value={mode}
onChange={(e: SelectChangeEvent<string>) => {
dispatch(setMode(e.target.value));
}}
>
<MenuItem value="light">Light</MenuItem>
<MenuItem value="dark">Dark</MenuItem>
</Select>
</Stack>
<Stack spacing={theme.spacing(2)}>
<Typography>Language</Typography>
<LanguageSelector />
</Stack>
</Stack>
}
/>
</BasePage>
);
};
export default SettingsPage;
@@ -0,0 +1,46 @@
import { StatusPageForm } from "@/pages/status-page/StatusPageForm";
import { useParams } from "react-router";
import { useNavigate } from "react-router";
import { z } from "zod";
import { usePatch, useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { statusPageSchema } from "@/validation/zod";
import type { IMonitor } from "@/types/monitor";
import type { IStatusPageWithMonitors } from "@/types/status-page";
type FormValues = z.infer<typeof statusPageSchema>;
const StatusPageConfigPage = () => {
const navigate = useNavigate();
const { id } = useParams();
const { patch, loading } = usePatch<FormValues, IStatusPageWithMonitors>();
const { response, isValidating } =
useGet<ApiResponse<IMonitor[]>>("/monitors");
const { response: statusPageResponse } = useGet<ApiResponse<any>>(
`/status-pages/${id}`
);
const monitors = response?.data || [];
const initialData = statusPageResponse?.data;
initialData.monitors =
initialData?.monitors?.map((monitor: IMonitor) => monitor?._id) || [];
const onSubmit = async (data: FormValues) => {
const res = await patch(`/status-pages/${id}`, data);
if (res) {
navigate(-1);
}
};
return (
<StatusPageForm
initialData={initialData}
monitorOptions={monitors}
onSubmit={onSubmit}
loading={loading || isValidating}
/>
);
};
export default StatusPageConfigPage;
@@ -0,0 +1,36 @@
import { StatusPageForm } from "@/pages/status-page/StatusPageForm";
import { useNavigate } from "react-router";
import { z } from "zod";
import { usePost, useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { statusPageSchema } from "@/validation/zod";
import type { IMonitor } from "@/types/monitor";
type FormValues = z.infer<typeof statusPageSchema>;
const StatusPageCreatePage = () => {
const navigate = useNavigate();
const { post, loading } = usePost<FormValues, IMonitor[]>();
const { response, isValidating } =
useGet<ApiResponse<IMonitor[]>>("/monitors");
const monitors = response?.data || [];
const onSubmit = async (data: FormValues) => {
const res = await post("/status-pages", data);
if (res) {
navigate(-1);
}
};
return (
<StatusPageForm
monitorOptions={monitors}
onSubmit={onSubmit}
loading={loading || isValidating}
/>
);
};
export default StatusPageCreatePage;
@@ -0,0 +1,42 @@
import Stack from "@mui/material/Stack";
import { StatusHeader } from "@/components/status-pages/StatusHeader";
import { StatusPageRow } from "@/components/status-pages/StatusPageRow";
import { BasePage } from "@/components/design-elements";
import { useTheme } from "@mui/material/styles";
import type { IMonitor } from "@/types/monitor";
import { useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { useParams } from "react-router";
import type { IStatusPageWithMonitors } from "@/types/status-page";
import { NameHeader } from "@/components/status-pages/NameHeader";
const GLOBAL_REFRESH = import.meta.env.VITE_APP_GLOBAL_REFRESH;
const StatusPages = () => {
const theme = useTheme();
const { id } = useParams();
const { response } = useGet<ApiResponse<IStatusPageWithMonitors>>(
`/status-pages/${id}`,
{},
{ refreshInterval: GLOBAL_REFRESH, keepPreviousData: true }
);
const statusPage = response?.data;
const monitors: IMonitor[] = statusPage?.monitors || [];
if (!statusPage) {
return null;
}
return (
<BasePage alignItems={"center"}>
<Stack minWidth={"66vw"} spacing={theme.spacing(8)}>
<NameHeader statusPage={statusPage} />
<StatusHeader statusPage={statusPage} />
{monitors?.map((monitor: IMonitor) => {
return <StatusPageRow key={monitor?._id} monitor={monitor} />;
})}
</Stack>
</BasePage>
);
};
export default StatusPages;
@@ -0,0 +1,213 @@
import Stack from "@mui/material/Stack";
import { Button, FormControlLabel } from "@/components/inputs";
import { ConfigBox, BasePage } from "@/components/design-elements";
import { TextInput, AutoComplete, Checkbox } from "@/components/inputs";
import Typography from "@mui/material/Typography";
import { Trash2 } from "lucide-react";
import { useTheme } from "@mui/material/styles";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslation } from "react-i18next";
import { z } from "zod";
import { statusPageSchema } from "@/validation/zod";
import {
useForm,
Controller,
useWatch,
type SubmitHandler,
} from "react-hook-form";
import { useEffect } from "react";
import { useInitForm } from "@/hooks/forms/UseInitStatusPageForm";
import type { IMonitor } from "@/types/monitor";
type FormValues = z.infer<typeof statusPageSchema>;
export const StatusPageForm = ({
initialData,
monitorOptions,
onSubmit,
loading,
}: {
mode?: string;
monitorOptions: IMonitor[];
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
loading: boolean;
}) => {
const { t } = useTranslation();
const { defaults } = useInitForm({ initialData: initialData });
const theme = useTheme();
const {
handleSubmit,
control,
reset,
setValue,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(statusPageSchema),
defaultValues: defaults,
mode: "onChange",
});
useEffect(() => {
reset(defaults);
}, [initialData, reset, defaults]);
const onError = (errors: any) => {
console.log(errors);
};
const monitors = useWatch({
control,
name: "monitors",
});
return (
<BasePage component={"form"} onSubmit={handleSubmit(onSubmit, onError)}>
<ConfigBox
title={t("createStatusPage.basicConfigTitle")}
subtitle={t("createStatusPage.basicConfigDescription")}
rightContent={
<Stack gap={theme.spacing(8)}>
<Controller
name="name"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("createStatusPage.nameConfigLabel")}
fullWidth
error={!!errors.name}
helperText={errors.name ? errors.name.message : ""}
/>
)}
/>
<Controller
name="description"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("createStatusPage.descriptionConfigLabel")}
fullWidth
error={!!errors.description}
helperText={
errors.description ? errors.description.message : ""
}
/>
)}
/>
</Stack>
}
/>
<ConfigBox
title={t("createStatusPage.urlConfigTitle")}
subtitle={t("createStatusPage.urlConfigDescription")}
rightContent={
<Controller
name="url"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("createStatusPage.urlConfigTitle")}
fullWidth
error={!!errors.url}
helperText={errors.url ? errors.url.message : ""}
/>
)}
/>
}
/>
<ConfigBox
title={t("createStatusPage.accessConfigTitle")}
subtitle={t("createStatusPage.accessConfigDescription")}
rightContent={
<Controller
name="isPublished"
control={control}
render={({ field }) => (
<FormControlLabel
label={t("createStatusPage.publishedConfigLabel")}
control={
<Checkbox
{...field}
checked={field.value}
onChange={(e) => field.onChange(e.target.checked)}
/>
}
/>
)}
/>
}
/>
<ConfigBox
title={t("createMaintenanceWindowPage.monitorsTitle")}
subtitle={t("createMaintenanceWindowPage.monitorsDescription")}
rightContent={
<Stack>
<Controller
name="monitors"
control={control}
defaultValue={[]}
render={({ field }) => (
<AutoComplete
multiple
options={monitorOptions}
getOptionLabel={(option) => option.name}
value={monitorOptions.filter((o: any) =>
(field.value || []).includes(o._id)
)}
onChange={(_, newValue) => {
field.onChange(newValue.map((o: any) => o._id));
}}
/>
)}
/>
<Stack gap={theme.spacing(2)} mt={theme.spacing(2)}>
{monitors.map((monitorId) => {
const option = monitorOptions.find((o) => o._id === monitorId);
if (!option) return null;
return (
<Stack
width={"100%"}
justifyContent={"space-between"}
direction="row"
key={monitorId}
>
<Typography>{option.name}</Typography>
<Trash2
size={20}
strokeWidth={1.5}
onClick={() => {
const updated = monitors.filter(
(id) => id !== monitorId
);
setValue("monitors", updated);
}}
style={{ cursor: "pointer" }}
/>
</Stack>
);
})}
</Stack>
</Stack>
}
/>
<Stack direction="row" justifyContent="flex-end">
<Button
loading={loading}
type="submit"
variant="contained"
color="accent"
>
{t("settingsSave")}
</Button>
</Stack>
</BasePage>
);
};
@@ -0,0 +1,42 @@
import Stack from "@mui/material/Stack";
import { StatusHeader } from "@/components/status-pages/StatusHeader";
import { StatusPageRow } from "@/components/status-pages/StatusPageRow";
import { BasePage } from "@/components/design-elements";
import { useTheme } from "@mui/material/styles";
import type { IMonitor } from "@/types/monitor";
import { useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { useParams } from "react-router";
import type { IStatusPageWithMonitors } from "@/types/status-page";
import { NameHeader } from "@/components/status-pages/NameHeader";
const GLOBAL_REFRESH = import.meta.env.VITE_APP_GLOBAL_REFRESH;
const StatusPages = () => {
const theme = useTheme();
const { url } = useParams();
const { response } = useGet<ApiResponse<IStatusPageWithMonitors>>(
`/status-pages/public/${url}`,
{},
{ refreshInterval: GLOBAL_REFRESH, keepPreviousData: true }
);
const statusPage = response?.data;
const monitors: IMonitor[] = statusPage?.monitors || [];
if (!statusPage) {
return null;
}
return (
<BasePage alignItems={"center"} paddingTop={theme.spacing(20)}>
<Stack minWidth={"66vw"} spacing={theme.spacing(8)}>
<NameHeader statusPage={statusPage} />
<StatusHeader statusPage={statusPage} />
{monitors?.map((monitor: IMonitor) => {
return <StatusPageRow key={monitor?._id} monitor={monitor} />;
})}
</Stack>
</BasePage>
);
};
export default StatusPages;
Whitespace-only changes.
@@ -0,0 +1,147 @@
import { HeaderCreate } from "@/components/notification-channels/HeaderCreate";
import Typography from "@mui/material/Typography";
import { BasePageWithStates, InfoBox } from "@/components/design-elements";
import { Table } from "@/components/design-elements";
import { ActionsMenu } from "@/components/actions-menu";
import { Dialog } from "@/components/inputs";
import { useState } from "react";
import { useTheme } from "@mui/material/styles";
import { useNavigate } from "react-router";
import type { ActionMenuItem } from "@/components/actions-menu";
import type { Header } from "@/components/design-elements/Table";
import type { IStatusPage } from "@/types/status-page";
import { useGet, useDelete } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { useTranslation } from "react-i18next";
const StatusPages = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const theme = useTheme();
const [selectedStatusPage, setSelectedStatusPage] =
useState<IStatusPage | null>(null);
const open = Boolean(selectedStatusPage);
const { response, isValidating, error, refetch } = useGet<
ApiResponse<IStatusPage[]>
>("/status-pages", {}, {});
const statusPages = response?.data || [];
const { deleteFn, loading: deleting } = useDelete<any>();
const getActions = (statusPage: IStatusPage): ActionMenuItem[] => {
return [
{
id: 1,
label: "Configure",
action: () => {
navigate(`/status-pages/${statusPage._id}/configure`);
},
closeMenu: true,
},
{
id: 7,
label: <Typography color={theme.palette.error.main}>Remove</Typography>,
action: async () => {
setSelectedStatusPage(statusPage);
},
closeMenu: true,
},
];
};
const getHeaders = () => {
const headers: Header<IStatusPage>[] = [
{
id: "name",
content: "Name",
render: (row) => {
return <Typography>{row?.name}</Typography>;
},
},
{
id: "published",
content: "Published",
render: (row) => {
const published = row.isPublished ? "Yes" : "No";
return <Typography>{published}</Typography>;
},
},
{
id: "url",
content: "Public URL",
render: (row) => {
return (
<Typography textTransform={"capitalize"}>{row?.url}</Typography>
);
},
},
{
id: "actions",
content: t("actions"),
render: (row) => {
return <ActionsMenu items={getActions(row)} />;
},
},
];
return headers;
};
const headers = getHeaders();
const handleConfirm = async () => {
if (!selectedStatusPage) return;
const res = await deleteFn(`/status-pages/${selectedStatusPage._id}`);
if (res) {
setSelectedStatusPage(null);
refetch();
}
};
const handleCancel = () => {
setSelectedStatusPage(null);
};
return (
<BasePageWithStates
page="Status Pages"
loading={false}
bullets={
t("statusPage.fallback.checks", { returnObjects: true }) as string[]
}
error={error}
items={statusPages}
actionButtonText="Create a new status page"
actionLink="/status-pages/create"
>
<InfoBox
title="Public Status Pages"
description="Create beautiful, branded status pages to keep your users informed about service health. Share real-time status updates and incident reports with your customers."
/>
<HeaderCreate
label={"Create a new Status Page"}
isLoading={isValidating || deleting}
path="/status-pages/create"
/>
<Table
headers={headers}
data={statusPages}
onRowClick={(row) => {
navigate(`/status-pages/${row._id}`);
}}
/>
<Dialog
title={t("createStatusPage.dialogDeleteTitle")}
content={t("createStatusPage.dialogDeleteContent")}
open={open}
onConfirm={handleConfirm}
onCancel={handleCancel}
/>
</BasePageWithStates>
);
};
export default StatusPages;
+95
View File
@@ -0,0 +1,95 @@
import { BasePage } from "@/components/design-elements";
import Typography from "@mui/material/Typography";
import Stack from "@mui/material/Stack";
import { Table } from "@/components/design-elements";
import { HeaderCreate } from "@/components/teams/HeaderCreate";
import type { Header } from "@/components/design-elements/Table";
import { useNavigate } from "react-router";
import { useTheme } from "@mui/material/styles";
import { useParams } from "react-router";
import { useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import type { ITeamMember } from "@/types/team-member";
const TeamDetailsPage = () => {
const theme = useTheme();
const navigate = useNavigate();
const { id } = useParams();
const { response } = useGet<ApiResponse<any>>(`/teams/${id}`);
const { response: teamMembersResponse } = useGet<ApiResponse<any>>(
`/team-members?teamId=${id}`
);
const team = response?.data;
// Get all team members
const teamMembers = teamMembersResponse?.data;
const getHeaders = () => {
const headers: Header<ITeamMember>[] = [
{
id: "name",
content: "Name",
render: (row) => {
return row?.userId?.firstName + " " + row?.userId?.lastName;
},
},
{
id: "role",
content: "Role",
render: (row) => {
return row?.roleId?.name;
},
},
{
id: "permissions",
content: "Permissions",
render: (row) => {
return (
<Stack>
{row?.roleId?.permissions.map((permission) => (
<Typography key={permission}>{permission}</Typography>
))}
</Stack>
);
},
},
];
return headers;
};
const headers = getHeaders();
return (
<BasePage>
<Stack>
<Stack alignItems="baseline" direction="row" gap={theme.spacing(2)}>
<Typography variant="h2">{"Name:"} </Typography>
<Typography>{team?.name}</Typography>
</Stack>
<Stack alignItems="baseline" direction="row" gap={theme.spacing(2)}>
<Typography variant="h2">{"Description:"} </Typography>
<Typography>{team?.description}</Typography>
</Stack>
</Stack>
<HeaderCreate
label="Add new team member"
path={`/teams/${id}/member/create`}
isLoading={false}
/>
<Typography variant="h2" marginTop={theme.spacing(4)}>
Team Members
</Typography>
<Table
headers={headers}
data={teamMembers || []}
onRowClick={(row) => {
navigate(`/teams/${id}/member/${row._id}/configure`);
}}
/>
</BasePage>
);
};
export default TeamDetailsPage;
@@ -0,0 +1,84 @@
import { TeamMemberForm } from "./TeamMemberForm";
import { Button } from "@/components/inputs";
import { Dialog } from "@/components/inputs";
import { useState } from "react";
import { useGet, usePatch } from "@/hooks/UseApi";
import { useParams } from "react-router";
import type { ApiResponse } from "@/hooks/UseApi";
import { useNavigate } from "react-router";
import { useDelete } from "@/hooks/UseApi";
import { useTranslation } from "react-i18next";
import { mutate } from "swr";
const TeamMemberConfig = () => {
const [dialogOpen, setDialogOpen] = useState<boolean>(false);
const { deleteFn, loading: deleting } = useDelete();
const navigate = useNavigate();
const { t } = useTranslation();
const { id, memberId } = useParams();
const { patch, loading } = usePatch();
const { response } = useGet<ApiResponse<any>>("/team-members");
const { response: rolesResponse } =
useGet<ApiResponse<any>>("/roles?type=team");
const teamMembers = response?.data || [];
const roles = rolesResponse?.data || [];
const user = teamMembers?.find((tm: any) => tm._id === memberId);
const onSubmit = async (data: any) => {
const roleId = data.roleId;
const res = await patch(`/team-members/${memberId}`, { roleId });
if (res) {
navigate(-1);
}
};
const handleConfirm = async () => {
await deleteFn(`/team-members/${id}`);
mutate("/teams/joined");
navigate(-1);
setDialogOpen(false);
};
const handleCancel = () => {
setDialogOpen(false);
};
return (
<>
<TeamMemberForm
mode="config"
initialData={{
userId: user?.userId?._id,
roleId: user?.roleId?._id,
teamId: user?.teamId,
}}
teamMembers={teamMembers}
roles={roles}
onSubmit={onSubmit}
loading={loading}
deleteButton={
<Button
variant="contained"
color="error"
onClick={() => setDialogOpen(true)}
disabled={deleting}
>
{t("delete")}
</Button>
}
breadcrumbOverride={["teams", id || "", "configure team member"]}
/>
<Dialog
open={dialogOpen}
title={"Are you sure?"}
content={"Delete team member"}
onConfirm={handleConfirm}
onCancel={handleCancel}
/>
</>
);
};
export default TeamMemberConfig;
@@ -0,0 +1,42 @@
import { TeamMemberForm } from "./TeamMemberForm";
import { useParams } from "react-router";
import { useGet, usePost } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { useNavigate } from "react-router";
import { mutate } from "swr";
const TeamMemberCreate = () => {
const navigate = useNavigate();
const { id } = useParams();
const { response } = useGet<ApiResponse<any>>("/team-members?type=org");
const { response: rolesResponse } =
useGet<ApiResponse<any>>("/roles?type=team");
const { post } = usePost<ApiResponse<any>>();
const teamMembers = response?.data || [];
const roles = rolesResponse?.data || [];
const onSubmit = async (data: any) => {
const res = await post("/team-members", { ...data });
if (res) {
mutate("/teams/joined");
navigate(-1);
}
};
return (
<TeamMemberForm
initialData={{
userId: teamMembers?.[0]?.userId?._id,
roleId: roles?.[0]?._id,
teamId: id,
}}
teamMembers={teamMembers}
roles={roles}
onSubmit={onSubmit}
loading={false}
breadcrumbOverride={["teams", id || "", "create team member"]}
/>
);
};
export default TeamMemberCreate;
+148
View File
@@ -0,0 +1,148 @@
import Typography from "@mui/material/Typography";
import Stack from "@mui/material/Stack";
import { Button } from "@/components/inputs";
import { ConfigBox, BasePage } from "@/components/design-elements";
import { Select } from "@/components/inputs";
import MenuItem from "@mui/material/MenuItem";
import { useTheme } from "@mui/material/styles";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslation } from "react-i18next";
import { z } from "zod";
import { teamMemberSchema } from "@/validation/zod";
import { useForm, Controller, type SubmitHandler } from "react-hook-form";
import { useEffect } from "react";
import { useInitForm } from "@/hooks/forms/UseInitTeamMemberForm";
type FormValues = z.infer<typeof teamMemberSchema>;
export const TeamMemberForm = ({
mode = "create",
initialData,
teamMembers = [],
roles = [],
onSubmit,
loading,
deleteButton,
breadcrumbOverride,
}: {
mode?: string;
initialData?: Partial<FormValues>;
teamMembers: any[];
roles: any[];
onSubmit: SubmitHandler<FormValues>;
loading: boolean;
deleteButton?: React.ReactNode;
breadcrumbOverride?: string[];
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const {
handleSubmit,
control,
reset,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(teamMemberSchema) as any,
defaultValues: defaults,
mode: "onChange",
});
useEffect(() => {
reset(defaults);
}, [initialData, reset, defaults]);
return (
<BasePage
component={"form"}
onSubmit={handleSubmit(onSubmit)}
breadcrumbOverride={breadcrumbOverride}
>
<ConfigBox
title="Team member"
subtitle="Team member selection"
rightContent={
<Controller
name="userId"
control={control}
render={({ field }) => {
return (
<Stack gap={theme.spacing(8)}>
<Select
disabled={mode !== "create"}
value={field.value}
fieldLabel="Team member"
error={!!errors.userId}
onChange={field.onChange}
>
{teamMembers.map((tm: any) => {
return (
<MenuItem key={tm._id} value={tm.userId?._id}>
{tm.userId?.firstName} {tm.userId?.lastName}
</MenuItem>
);
})}
</Select>
</Stack>
);
}}
/>
}
/>
<ConfigBox
title="Role"
subtitle="Choose your role for this new team. You will be the first member"
rightContent={
<Controller
name="roleId"
control={control}
render={({ field }) => {
const selectedRole = roles.find(
(role) => role._id === field.value
);
return (
<Stack gap={theme.spacing(8)}>
<Select
value={field.value}
fieldLabel="Role"
error={!!errors.roleId}
onChange={field.onChange}
>
{roles.map((role: any) => {
return (
<MenuItem key={role._id} value={role._id}>
{role.name}
</MenuItem>
);
})}
</Select>
<Stack>
<Typography variant={"h2"} mb={theme.spacing(4)}>
Included permissions:
</Typography>
{selectedRole?.permissions?.map((perm: string) => (
<Typography key={perm}>- {perm}</Typography>
))}
</Stack>
</Stack>
);
}}
/>
}
/>
<Stack direction="row" justifyContent="flex-end" gap={theme.spacing(4)}>
<Button
loading={loading}
type="submit"
variant="contained"
color="accent"
>
{t("settingsSave")}
</Button>
{deleteButton}
</Stack>
</BasePage>
);
};
+115
View File
@@ -0,0 +1,115 @@
import { BasePage, InfoBox } from "@/components/design-elements";
import { Table } from "@/components/design-elements";
import { HeaderCreate } from "@/components/teams/HeaderCreate";
import { ActionsMenu } from "@/components/actions-menu";
import { Dialog } from "@/components/inputs";
import { useNavigate } from "react-router";
import { useTranslation } from "react-i18next";
import type { ActionMenuItem } from "@/components/actions-menu";
import type { Header } from "@/components/design-elements/Table";
import type { ApiResponse } from "@/hooks/UseApi";
import { useGet, useDelete } from "@/hooks/UseApi";
import type { ITeam } from "@/types/team";
import { useState } from "react";
import { mutate } from "swr";
const TeamsPage = () => {
const navigate = useNavigate();
const [selectedTeam, setSelectedTeam] = useState<ITeam | null>(null);
const isDialogOpen = Boolean(selectedTeam);
const { t } = useTranslation();
const { response, loading, refetch } = useGet<ApiResponse<any>>("/teams");
const { deleteFn } = useDelete();
const teams = response?.data || [];
const handleConfirm = async () => {
await deleteFn(`/teams/${selectedTeam?._id}`);
setSelectedTeam(null);
refetch();
mutate("/teams/joined");
};
const handleCancel = () => {
setSelectedTeam(null);
};
const getActions = (team: ITeam): ActionMenuItem[] => {
return [
{
id: 1,
label: "Configure",
action: () => {
navigate(`/teams/${team._id}/configure`);
},
closeMenu: true,
},
{
id: 2,
label: "Delete",
action: () => {
setSelectedTeam(team);
},
closeMenu: true,
},
];
};
const getHeaders = () => {
const headers: Header<ITeam>[] = [
{
id: "name",
content: "Team name",
render: (row) => {
return row.name;
},
},
{
id: "description",
content: "Team description",
render: (row) => {
return row.description;
},
},
{
id: "actions",
content: "Team description",
render: (row) => {
return <ActionsMenu items={getActions(row)} />;
},
},
];
return headers;
};
const headers = getHeaders();
return (
<BasePage>
<InfoBox
title="Team Collaboration"
description="Organize your monitoring workspace by creating teams. Control who can view and manage monitors, set up role-based permissions, and collaborate effectively."
/>
<HeaderCreate
label="Create new team"
isLoading={loading}
path="/teams/create"
/>
<Table
headers={headers}
data={teams}
onRowClick={(row) => {
navigate(`/teams/${row._id}`);
}}
/>
<Dialog
open={isDialogOpen}
title={t("deleteDialogTitle")}
content={t("deleteDialogDescription")}
onConfirm={handleConfirm}
onCancel={handleCancel}
/>
</BasePage>
);
};
export default TeamsPage;
+40
View File
@@ -0,0 +1,40 @@
import { TeamsForm } from "@/pages/teams/TeamsForm";
import { useNavigate, useParams } from "react-router";
import { z } from "zod";
import { teamSchema } from "@/validation/zod";
import { useGet, usePatch } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
const TeamsConfigPage = () => {
type FormValues = Omit<z.infer<typeof teamSchema>, "roleId">;
const navigate = useNavigate();
const { response } = useGet<ApiResponse<any>>("/roles?type=team");
const { patch, loading } = usePatch<FormValues, ApiResponse<any>>();
const { id } = useParams();
const { response: teamResponse } = useGet<ApiResponse<any>>(`/teams/${id}`);
const team = teamResponse?.data || null;
const roles = response?.data || [];
const onSubmit = async (data: FormValues) => {
const toSubmit = {
name: data.name,
description: data.description,
};
await patch(`/teams/${id}`, toSubmit);
navigate("/teams");
};
return (
<TeamsForm
mode="config"
initialData={{ ...team, roleId: roles[0]?._id }}
onSubmit={onSubmit}
loading={loading}
roles={roles}
/>
);
};
export default TeamsConfigPage;
+31
View File
@@ -0,0 +1,31 @@
import { TeamsForm } from "@/pages/teams/TeamsForm";
import { useNavigate } from "react-router";
import { z } from "zod";
import { teamSchema } from "@/validation/zod";
import { useGet, usePost } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { mutate } from "swr";
const TeamsCreatePage = () => {
type FormValues = z.infer<typeof teamSchema>;
const { response } = useGet<ApiResponse<any>>("/roles?type=team");
const { post, loading } = usePost<FormValues>();
const navigate = useNavigate();
const onSubmit = async (data: FormValues) => {
await post("/teams", data);
mutate("/teams/joined");
navigate("/teams");
};
return (
<TeamsForm
onSubmit={onSubmit}
loading={loading}
roles={response?.data || []}
/>
);
};
export default TeamsCreatePage;
+154
View File
@@ -0,0 +1,154 @@
import Typography from "@mui/material/Typography";
import Stack from "@mui/material/Stack";
import { Button } from "@/components/inputs";
import { ConfigBox, BasePage } from "@/components/design-elements";
import { TextInput, Select } from "@/components/inputs";
import MenuItem from "@mui/material/MenuItem";
import { useTheme } from "@mui/material/styles";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslation } from "react-i18next";
import { z } from "zod";
import { teamSchema } from "@/validation/zod";
import { useForm, Controller, type SubmitHandler } from "react-hook-form";
import { useEffect } from "react";
import { useInitForm } from "@/hooks/forms/UseInitTeamsForm";
type FormValues = z.infer<typeof teamSchema>;
export const TeamsForm = ({
mode = "create",
initialData,
roles = [],
onSubmit,
loading,
}: {
mode?: string;
initialData?: Partial<FormValues>;
roles: any[];
onSubmit: SubmitHandler<FormValues>;
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const {
handleSubmit,
control,
setValue,
reset,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(teamSchema) as any,
defaultValues: defaults,
mode: "onChange",
});
useEffect(() => {
reset(defaults);
}, [initialData, reset, defaults]);
useEffect(() => {
setValue("roleId", roles[0]?._id || "");
}, [roles, setValue]);
return (
<BasePage component={"form"} onSubmit={handleSubmit(onSubmit)}>
<ConfigBox
title={t("createTeamsPage.basicInfoTitle")}
subtitle={t("createTeamsPage.basicInfoSubtitle")}
rightContent={
<Stack gap={theme.spacing(8)}>
<Controller
name="name"
control={control}
render={({ field }) => (
<TextInput
{...field}
fieldLabel={t("createTeamsPage.basicInfoName")}
required
type="text"
fullWidth
error={!!errors.name}
helperText={errors.name ? errors.name.message : ""}
/>
)}
/>
<Controller
name="description"
control={control}
render={({ field }) => (
<TextInput
{...field}
fieldLabel={t("createTeamsPage.basicInfoDescription")}
type="text"
fullWidth
error={!!errors.description}
helperText={
errors.description ? errors.description.message : ""
}
/>
)}
/>
</Stack>
}
/>
{mode === "create" && (
<ConfigBox
title="Role"
subtitle="Choose your role for this new team. You will be the first member"
rightContent={
<Controller
name="roleId"
control={control}
defaultValue={""} // important!
render={({ field }) => {
const selectedRole = roles.find(
(role) => role._id === field.value
);
return (
<Stack gap={theme.spacing(8)}>
<Select
value={field.value}
fieldLabel="Role"
required
error={!!errors.roleId}
onChange={field.onChange}
>
{roles.map((role: any) => {
return (
<MenuItem key={role._id} value={role._id}>
{role.name}
</MenuItem>
);
})}
</Select>
<Stack>
<Typography variant={"h2"} mb={theme.spacing(4)}>
Included permissions:
</Typography>
{selectedRole?.permissions?.map((perm: string) => (
<Typography key={perm}>- {perm}</Typography>
))}
</Stack>
</Stack>
);
}}
/>
}
/>
)}
<Stack direction="row" justifyContent="flex-end">
<Button
loading={loading}
type="submit"
variant="contained"
color="accent"
>
{t("settingsSave")}
</Button>
</Stack>
</BasePage>
);
};
+94
View File
@@ -0,0 +1,94 @@
import { Table, Pagination, StatusLabel } from "@/components/design-elements";
import Box from "@mui/material/Box";
import type { Header } from "@/components/design-elements/Table";
import type { ICheck, IChecksWithCount } from "@/types/check";
import type { ApiResponse } from "@/hooks/UseApi";
import type { MonitorStatus } from "@/types/monitor";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useGet } from "@/hooks/UseApi";
import { formatDateWithTz } from "@/utils/TimeUtils";
import { useAppSelector } from "@/hooks/AppHooks";
const getHeaders = (t: Function, uiTimezone: string) => {
const headers: Header<ICheck>[] = [
{
id: "status",
content: t("status"),
render: (row) => {
return <StatusLabel status={row.status as MonitorStatus} />;
},
},
{
id: "date",
content: t("date&Time"),
render: (row) => {
return formatDateWithTz(
row.createdAt,
"ddd, MMMM D, YYYY, HH:mm A",
uiTimezone
);
},
},
{
id: "statusCode",
content: t("statusCode"),
render: (row) => {
return row.httpStatusCode || "N/A";
},
},
];
return headers;
};
export const CheckTable = ({ monitorId }: { monitorId: string }) => {
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(5);
const { t } = useTranslation();
const uiTimezone = useAppSelector((state: any) => state.ui.timezone);
const headers = getHeaders(t, uiTimezone);
const { response, error } = useGet<ApiResponse<IChecksWithCount>>(
`/monitors/${monitorId}/checks?page=${page}&rowsPerPage=${rowsPerPage}`,
{},
{ keepPreviousData: true }
);
const checks = response?.data?.checks || [];
const count = response?.data?.count || 0;
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);
};
if (error) {
console.error(error);
}
return (
<Box>
<Table headers={headers} data={checks} />
<Pagination
component="div"
count={count}
page={page}
rowsPerPage={rowsPerPage}
onPageChange={handlePageChange}
onRowsPerPageChange={handleRowsPerPageChange}
/>
</Box>
);
};
+184
View File
@@ -0,0 +1,184 @@
import Stack from "@mui/material/Stack";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { Table, Pagination, StatusLabel } from "@/components/design-elements";
import { HistogramResponseTime } from "@/components/monitors";
import type { Header } from "@/components/design-elements/Table";
import { ActionsMenu } from "@/components/actions-menu";
import { useTranslation } from "react-i18next";
import { useTheme } from "@mui/material/styles";
import { useNavigate } from "react-router-dom";
import { usePatch } from "@/hooks/UseApi";
import type { IMonitor } from "@/types/monitor";
import type { ActionMenuItem } from "@/components/actions-menu";
export const MonitorTable = ({
monitors,
refetch,
setSelectedMonitor,
count,
page,
setPage,
rowsPerPage,
setRowsPerPage,
}: {
monitors: IMonitor[];
refetch: Function;
setSelectedMonitor: Function;
count: number;
page: number;
setPage: (page: number) => void;
rowsPerPage: number;
setRowsPerPage: (rowsPerPage: number) => void;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const navigate = useNavigate();
const {
patch,
// loading: isPatching,
// error: postError,
} = usePatch<any, IMonitor>();
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);
};
const getActions = (monitor: IMonitor): ActionMenuItem[] => {
return [
{
id: 1,
label: "Open site",
action: () => {
window.open(monitor.url, "_blank", "noreferrer");
},
closeMenu: true,
},
{
id: 2,
label: "Details",
action: () => {
navigate(`${monitor._id}`);
},
},
{
id: 3,
label: "Incidents",
action: () => {
navigate(`/incidents/${monitor._id}`);
},
},
{
id: 4,
label: "Configure",
action: () => {
navigate(`/uptime/${monitor._id}/configure`);
},
},
// {
// id: 5,
// label: "Clone",
// action: () => {
// console.log("Open clone");
// },
// },
{
id: 6,
label: monitor.isActive ? "Pause" : "Resume",
action: async () => {
await patch(`/monitors/${monitor._id}/active`);
refetch();
},
closeMenu: true,
},
{
id: 7,
label: <Typography color={theme.palette.error.main}>Remove</Typography>,
action: () => {
setSelectedMonitor(monitor);
},
closeMenu: true,
},
];
};
const getHeaders = () => {
const headers: Header<IMonitor>[] = [
{
id: "name",
content: t("host"),
render: (row) => {
return row.name;
},
},
{
id: "status",
content: t("status"),
render: (row) => {
return <StatusLabel status={row.status} isActive={row.isActive} />;
},
},
{
id: "histogram",
content: t("responseTime"),
render: (row) => {
return (
<Stack alignItems={{ xs: "flex-start", md: "center" }}>
<HistogramResponseTime checks={row.latestChecks} />
</Stack>
);
},
},
{
id: "type",
content: t("type"),
render: (row) => {
return row.type;
},
},
{
id: "actions",
content: t("actions"),
render: (row) => {
return <ActionsMenu items={getActions(row)} />;
},
},
];
return headers;
};
const headers = getHeaders();
return (
<Box>
<Table
headers={headers}
data={monitors}
onRowClick={(row) => {
navigate(`/uptime/${row._id}`);
}}
/>
<Pagination
component="div"
count={count}
page={page}
rowsPerPage={rowsPerPage}
onPageChange={handlePageChange}
onRowsPerPageChange={handleRowsPerPageChange}
/>
</Box>
);
};
@@ -0,0 +1,62 @@
import { monitorSchema } from "@/validation/zod";
import { useGet, usePatch } from "@/hooks/UseApi";
import { UptimeForm } from "@/pages/uptime/UptimeForm";
import { useParams } from "react-router";
import type { ApiResponse } from "@/hooks/UseApi";
import humanInterval from "human-interval";
import { z } from "zod";
import { useNavigate } from "react-router";
import type { INotificationChannel } from "@/types/notification-channel";
import type { IMonitor } from "@/types/monitor";
const UptimeConfigurePage = () => {
type FormValues = z.infer<typeof monitorSchema>;
type SubmitValues = Omit<FormValues, "interval"> & {
interval: number | undefined;
};
const { id } = useParams();
const navigate = useNavigate();
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
"/notification-channels"
);
const { response: monitorResponse } = useGet<ApiResponse<IMonitor>>(
`/monitors/${id}`
);
const monitor = monitorResponse?.data || {};
const notificationOptions = response?.data ?? [];
const { patch, loading, error } = usePatch<Partial<SubmitValues>, IMonitor>();
const onSubmit = async (data: FormValues) => {
let interval = humanInterval(data.interval);
if (!interval) interval = 60000;
const submitData = {
type: data.type,
name: data.name,
n: data.n,
notificationChannels: data.notificationChannels,
interval,
};
const result = await patch(`/monitors/${id}`, submitData);
if (result) {
navigate(`/uptime/${id}`);
} else {
console.error(error);
}
};
return (
<UptimeForm
mode="configure"
initialData={{
...monitor,
}}
onSubmit={onSubmit}
notificationOptions={notificationOptions}
loading={loading}
/>
);
};
export default UptimeConfigurePage;
+43
View File
@@ -0,0 +1,43 @@
import { UptimeForm } from "./UptimeForm";
import humanInterval from "human-interval";
import { z } from "zod";
import { monitorSchema } from "@/validation/zod";
import { useGet, usePost } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { useNavigate } from "react-router";
import type { INotificationChannel } from "@/types/notification-channel";
const UptimeCreatePage = () => {
type FormValues = z.infer<typeof monitorSchema>;
type SubmitValues = Omit<FormValues, "interval"> & {
interval: number | undefined;
};
const navigate = useNavigate();
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
"/notification-channels"
);
const { post, loading, error } = usePost<SubmitValues>();
const onSubmit = async (data: FormValues) => {
let interval = humanInterval(data.interval);
if (!interval) interval = 60000;
const submitData = { ...data, interval };
const result = await post("/monitors", submitData);
if (result) {
navigate("/uptime");
} else {
console.error(error);
}
};
const notificationOptions = response?.data ?? [];
return (
<UptimeForm
onSubmit={onSubmit}
notificationOptions={notificationOptions}
loading={loading}
/>
);
};
export default UptimeCreatePage;
+162
View File
@@ -0,0 +1,162 @@
import { BasePage, StatBox } from "@/components/design-elements";
import {
HeaderControls,
HeaderRange,
HistogramStatus,
ChartAvgResponse,
ChartResponseTime,
} from "@/components/monitors";
import Stack from "@mui/material/Stack";
import { CheckTable } from "@/pages/uptime/CheckTable";
import type { IMonitor, IMonitorWithMonitorStats } from "@/types/monitor";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useTheme } from "@mui/material/styles";
import { useParams } from "react-router";
import { useGet, usePatch, type ApiResponse } from "@/hooks/UseApi";
import { useState } from "react";
import { getStatusPalette } from "@/utils/MonitorUtils";
import prettyMilliseconds from "pretty-ms";
const GLOBAL_REFRESH = import.meta.env.VITE_APP_GLOBAL_REFRESH;
const UptimeDetailsPage = () => {
const { id } = useParams();
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
// Local state
const [range, setRange] = useState("2h");
const { response, isValidating, error, refetch } = useGet<
ApiResponse<IMonitorWithMonitorStats>
>(
`/monitors/${id}?embedChecks=true&range=${range}`,
{},
{ refreshInterval: GLOBAL_REFRESH, keepPreviousData: true }
);
const {
response: upResponse,
isValidating: upIsValidating,
error: upError,
} = useGet<ApiResponse<IMonitorWithMonitorStats>>(
`/monitors/${id}?embedChecks=true&range=${range}&status=up`,
{},
{ keepPreviousData: true }
);
const {
response: downResponse,
error: downError,
isValidating: downIsValidating,
} = useGet<ApiResponse<IMonitorWithMonitorStats>>(
`/monitors/${id}?embedChecks=true&range=${range}&status=down`,
{},
{ keepPreviousData: true }
);
const {
patch,
loading: isPatching,
error: postError,
} = usePatch<any, IMonitor>();
const monitor = response?.data?.monitor;
if (!monitor) {
return null;
}
const stats = response?.data?.stats || null;
const avgResponseTime = stats?.avgResponseTime || 0;
const maxResponseTime = stats?.maxResponseTime || 0;
const streakDuration = stats?.currentStreakStartedAt
? Date.now() - stats?.currentStreakStartedAt
: 0;
const lastChecked = stats?.lastCheckTimestamp
? Date.now() - stats?.lastCheckTimestamp
: -1;
const checks = response?.data?.checks || [];
const upChecks = upResponse?.data?.checks
? [...upResponse.data.checks].reverse()
: [];
const downChecks = downResponse?.data?.checks
? [...downResponse.data.checks].reverse()
: [];
const palette = getStatusPalette(monitor?.status);
if (error || upError || downError || postError) {
console.error("Error fetching monitor data:", {
error,
upError,
downError,
postError,
});
}
return (
<BasePage>
<HeaderControls
monitor={monitor}
patch={patch}
isPatching={isPatching}
refetch={refetch}
path="/uptime"
/>
<Stack direction="row" gap={theme.spacing(8)}>
<StatBox
palette={palette}
title="Active for"
subtitle={prettyMilliseconds(streakDuration, {
secondsDecimalDigits: 0,
})}
/>
<StatBox
title="Last check"
subtitle={
lastChecked >= 0
? `${prettyMilliseconds(lastChecked, {
secondsDecimalDigits: 0,
})} ago`
: "N/A"
}
/>
<StatBox
title="Last response time"
subtitle={
stats?.lastResponseTime ? `${stats?.lastResponseTime} ms` : "N/A"
}
/>
</Stack>
<HeaderRange
loading={isValidating || upIsValidating || downIsValidating}
range={range}
setRange={setRange}
/>
<Stack direction={isSmall ? "column" : "row"} gap={theme.spacing(8)}>
<HistogramStatus
title="Uptime"
status={"up"}
checks={upChecks}
range={range}
/>
<HistogramStatus
title="Incidents"
checks={downChecks}
status={"down"}
range={range}
/>
<ChartAvgResponse avg={avgResponseTime} max={maxResponseTime} />
</Stack>
<ChartResponseTime checks={checks} range={range} />
<CheckTable monitorId={monitor?._id} />
</BasePage>
);
};
export default UptimeDetailsPage;
+306
View File
@@ -0,0 +1,306 @@
import Stack from "@mui/material/Stack";
import {
TextInput,
Button,
AutoComplete,
RadioWithDescription,
} from "@/components/inputs";
import { ConfigBox, BasePage } from "@/components/design-elements";
import RadioGroup from "@mui/material/RadioGroup";
import FormControl from "@mui/material/FormControl";
import { Trash2 } from "lucide-react";
import { Typography } from "@mui/material";
import { useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { monitorSchema } from "@/validation/zod";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
useForm,
Controller,
useWatch,
type SubmitHandler,
} from "react-hook-form";
import { useTheme } from "@mui/material/styles";
import { useInitForm } from "@/hooks/forms/UseInitMonitorFrom";
type FormValues = z.infer<typeof monitorSchema>;
export const UptimeForm = ({
mode = "create",
initialData,
onSubmit,
notificationOptions,
loading,
}: {
mode?: "create" | "configure";
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
notificationOptions: any[];
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const urlInputRef = useRef<HTMLInputElement>(null);
const {
handleSubmit,
control,
setValue,
reset,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(monitorSchema) as any,
defaultValues: defaults,
mode: "onChange",
});
useEffect(() => {
reset(defaults);
}, [initialData, reset, defaults]);
const selectedType = useWatch({
control,
name: "type",
});
const url = useWatch({ control, name: "url" });
const notificationChannels = useWatch({
control,
name: "notificationChannels",
});
useEffect(() => {
if (!selectedType) return;
if (selectedType !== "http" && selectedType !== "https") {
setValue("url", "");
return;
}
if (selectedType !== "http" && selectedType !== "https") return;
if (!url) {
setValue("url", `${selectedType}://`);
return;
}
const hasProtocol = /^(http|https):\/\//i.test(url);
if (hasProtocol) {
const newUrl = url.replace(/^(http|https):\/\//i, `${selectedType}://`);
if (newUrl !== url) setValue("url", newUrl);
} else {
setValue("url", `${selectedType}://${url}`);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedType, setValue]);
useEffect(() => {
const input = urlInputRef.current;
if (input) {
const len = input.value.length;
input.setSelectionRange(len, len);
}
}, [selectedType]);
return (
<BasePage component={"form"} onSubmit={handleSubmit(onSubmit)}>
{mode === "create" && (
<ConfigBox
title={t("distributedUptimeCreateChecks")}
subtitle={t("distributedUptimeCreateChecksDescription")}
rightContent={
<Controller
name="type"
control={control}
render={({ field }) => (
<FormControl error={!!errors.type}>
<RadioGroup {...field} sx={{ gap: theme.spacing(6) }}>
<RadioWithDescription
value="https"
label="HTTPS"
description="Use HTTPS to monitor your website or API endpoint.
"
/>
<RadioWithDescription
value="http"
label={"HTTP"}
description={
"Use HTTP to monitor your website or API endpoint."
}
/>
<RadioWithDescription
value="ping"
label={t("pingMonitoring")}
description={t("pingMonitoringDescription")}
/>
</RadioGroup>
</FormControl>
)}
/>
}
/>
)}
<ConfigBox
title={t("settingsGeneralSettings")}
subtitle={t(`uptimeGeneralInstructions.${selectedType}`)}
rightContent={
<Stack gap={theme.spacing(8)}>
<Controller
disabled={mode === "configure"}
name="url"
control={control}
render={({ field }) => (
<TextInput
inputRef={urlInputRef}
{...field}
onFocus={(e) => {
const input = e.target;
setTimeout(() => {
input.setSelectionRange(
input.value.length,
input.value.length
);
}, 0);
}}
type="text"
fieldLabel={t("url")}
fullWidth
error={!!errors.url}
helperText={errors.url ? errors.url.message : ""}
/>
)}
/>
<Controller
name="name"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("displayName")}
fullWidth
error={!!errors.name}
helperText={errors.name ? errors.name.message : ""}
/>
)}
/>
</Stack>
}
/>
<ConfigBox
title={t("createMonitorPage.incidentConfigTitle")}
subtitle={t("createMonitorPage.incidentConfigDescriptionV2")}
rightContent={
<Controller
name="n"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="number"
fieldLabel={t("createMonitorPage.incidentConfigStatusCheckNumber")}
fullWidth
error={!!errors.n}
helperText={errors.n ? errors.n.message : ""}
onChange={(e) => {
const target = e.target as HTMLInputElement;
field.onChange(target.valueAsNumber);
}}
/>
)}
/>
}
/>
<ConfigBox
title={t("notificationConfig.title")}
subtitle={t("notificationConfig.description")}
rightContent={
<Stack>
<Controller
name="notificationChannels"
control={control}
defaultValue={[]}
render={({ field }) => (
<AutoComplete
multiple
fieldLabel={`You have ${notificationOptions.length} available notification ${notificationOptions.length === 1 ? 'channel' : 'channels'}`}
options={notificationOptions}
getOptionLabel={(option) => option.name}
value={notificationOptions.filter((o: any) =>
(field.value || []).includes(o._id)
)}
onChange={(_, newValue) => {
field.onChange(newValue.map((o: any) => o._id));
}}
/>
)}
/>
<Stack gap={theme.spacing(2)} mt={theme.spacing(2)}>
{notificationChannels.map((notificationId) => {
const option = notificationOptions.find(
(o: any) => o._id === notificationId
);
if (!option) return null;
return (
<Stack
width={"100%"}
justifyContent={"space-between"}
direction="row"
key={notificationId}
>
<Typography>{option.name}</Typography>
<Trash2
size={20}
strokeWidth={1.5}
onClick={() => {
const updated = notificationChannels.filter(
(id) => id !== notificationId
);
setValue("notificationChannels", updated);
}}
style={{ cursor: "pointer" }}
/>
</Stack>
);
})}
</Stack>
</Stack>
}
/>
<ConfigBox
title={t("createMonitorPage.intervalTitle")}
subtitle="How often to check the URL"
rightContent={
<Controller
name="interval"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("createMonitorPage.intervalDescription")}
fullWidth
error={!!errors.interval}
helperText={errors.interval ? errors.interval.message : ""}
/>
)}
/>
}
/>
<Stack direction="row" justifyContent="flex-end">
<Button
loading={loading}
type="submit"
variant="contained"
color="accent"
>
{t("settingsSave")}
</Button>
</Stack>
</BasePage>
);
};
+104
View File
@@ -0,0 +1,104 @@
import {
MonitorBasePageWithStates,
UpStatusBox,
DownStatusBox,
PausedStatusBox,
InfoBox,
} from "@/components/design-elements";
import { HeaderCreate } from "@/components/monitors";
import Stack from "@mui/material/Stack";
import { Dialog } from "@/components/inputs";
import { MonitorTable } from "@/pages/uptime/MonitorTable";
import { useTranslation } from "react-i18next";
import { useTheme } from "@mui/material/styles";
import { useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import type { IMonitor, IMonitorWithStats } from "@/types/monitor";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useState } from "react";
import { useDelete } from "@/hooks/UseApi";
const GLOBAL_REFRESH = import.meta.env.VITE_APP_GLOBAL_REFRESH;
const UptimeMonitors = () => {
const theme = useTheme();
const { t } = useTranslation();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const [selectedMonitor, setSelectedMonitor] = useState<IMonitor | null>(null);
const isDialogOpen = Boolean(selectedMonitor);
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);
const { deleteFn } = useDelete();
const { response, loading, isValidating, error, refetch } = useGet<
ApiResponse<IMonitorWithStats>
>(
`/monitors?embedChecks=true&type=http&type=https&type=ping&page=${page}&rowsPerPage=${rowsPerPage}`,
{},
{
refreshInterval: GLOBAL_REFRESH,
keepPreviousData: true,
dedupingInterval: 0,
},
{
useTeamIdAsKey: true,
}
);
const monitors: IMonitor[] = response?.data?.monitors ?? ([] as IMonitor[]);
const count = response?.data?.count || 0;
const upCount = response?.data?.upCount || 0;
const downCount = response?.data?.downCount || 0;
const pausedCount = response?.data?.pausedCount || 0;
const handleConfirm = async () => {
await deleteFn(`/monitors/${selectedMonitor?._id}`);
setSelectedMonitor(null);
refetch();
};
const handleCancel = () => {
setSelectedMonitor(null);
};
return (
<MonitorBasePageWithStates
loading={isValidating}
error={error}
items={monitors}
page="uptime"
actionLink="/uptime/create"
>
<InfoBox
title="Website & API Uptime Monitoring"
description="Monitor your websites and APIs to ensure they're always accessible. Get instant alerts when your services go down and track uptime history over time."
/>
<HeaderCreate isLoading={loading} path="/uptime/create" />
<Stack direction={isSmall ? "column" : "row"} gap={theme.spacing(8)}>
<UpStatusBox n={upCount} />
<DownStatusBox n={downCount} />
<PausedStatusBox n={pausedCount} />
</Stack>
<MonitorTable
monitors={monitors}
refetch={refetch}
setSelectedMonitor={setSelectedMonitor}
count={count}
page={page}
setPage={setPage}
rowsPerPage={rowsPerPage}
setRowsPerPage={setRowsPerPage}
/>
<Dialog
open={isDialogOpen}
title={t("deleteDialogTitle")}
content={t("deleteDialogDescription")}
onConfirm={handleConfirm}
onCancel={handleCancel}
/>
</MonitorBasePageWithStates>
);
};
export default UptimeMonitors;