Remove business V2 logic

This commit is contained in:
Sajanpreet Singh committed 2025-12-04 10:31:45 -06:00
1 parent 1e3ee23120
commit 72bcc0d020
117 files changed
+1 -8794

No files matched your search

-136
View File
@@ -1,136 +0,0 @@
import { AuthBasePage } from "@/Components/v2/Auth";
import { Button } from "@/Components/v2/Inputs";
import Stack from "@mui/material/Stack";
import { TextInput, TextLink } from "@/Components/v2/Inputs";
import type { ApiResponse } from "@/Hooks/v2/UseApi";
import { zodResolver } from "@hookform/resolvers/zod";
import { usePost } from "@/Hooks/v2/UseApi";
import { useNavigate } from "react-router";
import { useTheme } from "@mui/material/styles";
import { useDispatch } from "react-redux";
import { setIsAuthenticated } from "@/Features/Auth/v2AuthSlice";
import { useTranslation } from "react-i18next";
import { z } from "zod";
import { useForm, Controller } from "react-hook-form";
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 = useDispatch();
const theme = useTheme();
const { post, loading } = usePost<FormData, ApiResponse>();
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(setIsAuthenticated({ authenticated: true }));
navigate("/v2/uptime");
} else {
dispatch(setIsAuthenticated({ authenticated: false }));
}
};
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}
label={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"
label={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="/forgot-password"
/>
<TextLink
text={t("auth.login.links.register")}
linkText={t("auth.login.links.registerLink")}
href="/register"
/>
</Stack>
</AuthBasePage>
);
};
export default Login;
-177
View File
@@ -1,177 +0,0 @@
import { AuthBasePage } from "@/Components/v2/Auth";
import { TextInput } from "@/Components/v2/Inputs";
import { Button } from "@/Components/v2/Inputs";
import Typography from "@mui/material/Typography";
import Stack from "@mui/material/Stack";
import type { ApiResponse } from "@/Hooks/v2/UseApi";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useTranslation } from "react-i18next";
import { useForm, Controller } from "react-hook-form";
import { useTheme } from "@mui/material/styles";
import { usePost } from "@/Hooks/v2/UseApi";
import { useNavigate } from "react-router";
const schema = z
.object({
email: z.email({ message: "Invalid email address" }),
firstName: z.string().min(1, { message: "First Name is required" }),
lastName: z.string().min(1, { message: "Last Name is required" }),
password: z.string().min(6, { message: "Password must be at least 6 characters" }),
confirmPassword: z
.string()
.min(6, { message: "Confirm Password must be at least 6 characters" }),
})
.refine((data) => data.password === data.confirmPassword, {
path: ["confirmPassword"],
message: "Passwords must match",
});
type FormData = z.infer<typeof schema>;
const Register = () => {
const { t } = useTranslation();
const theme = useTheme();
const navigate = useNavigate();
const { post, loading, error } = usePost<FormData, ApiResponse>();
const {
handleSubmit,
control,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
email: "",
password: "",
},
});
const onSubmit = async (data: FormData) => {
const result = await post("/auth/register", data);
if (result) {
navigate("/v2/uptime");
} else {
console.error("Login failed:", error);
}
};
return (
<AuthBasePage
title={t("auth.registration.welcome")}
subtitle={t("auth.registration.heading.user")}
>
<Stack
alignItems={"center"}
width={"100%"}
>
<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}
label={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="firstName"
control={control}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
label={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}
label={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"
label={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"
label={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 }}
>
Register
</Button>
{error && <Typography color="error">{error}</Typography>}
</Stack>
</Stack>
</AuthBasePage>
);
};
export default Register;
-93
View File
@@ -1,93 +0,0 @@
import { Table, Pagination } from "@/Components/v2/DesignElements";
import { StatusLabel } from "@/Components/v2/DesignElements";
import Box from "@mui/material/Box";
import type { Header } from "@/Components/v2/DesignElements/Table";
import type { Check } from "@/Types/Check";
import type { ApiResponse } from "@/Hooks/v2/UseApi";
import type { MonitorStatus } from "@/Types/Monitor";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useGet } from "@/Hooks/v2/UseApi";
import { formatDateWithTz } from "@/Utils/v2/TimeUtils";
import { useSelector } from "react-redux";
const getHeaders = (t: Function, uiTimezone: string) => {
const headers: Header<Check>[] = [
{
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 = useSelector((state: any) => state.ui.timezone);
const headers = getHeaders(t, uiTimezone);
const { response, error } = useGet<ApiResponse>(
`/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>
);
};
-43
View File
@@ -1,43 +0,0 @@
import { monitorSchema } from "@/Validation/v2/zod";
import { useGet, usePost } from "@/Hooks/v2/UseApi";
import { UptimeForm } from "@/Pages/v2/Uptime/UptimeForm";
import { useParams } from "react-router";
import type { ApiResponse } from "@/Hooks/v2/UseApi";
import humanInterval from "human-interval";
import { z } from "zod";
export const UptimeConfigurePage = () => {
type FormValues = z.infer<typeof monitorSchema>;
type SubmitValues = Omit<FormValues, "interval"> & { interval: number | undefined };
const { id } = useParams();
const { response } = useGet<ApiResponse>("/notification-channels");
const { response: monitorResponse } = useGet<ApiResponse>(`/monitors/${id}`);
const monitor = monitorResponse?.data || null;
const notificationOptions = response?.data ?? [];
const { post, loading, error } = usePost<SubmitValues, ApiResponse>();
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) {
console.log(result);
} else {
console.error(error);
}
};
return (
<UptimeForm
initialData={{
...monitor,
}}
onSubmit={onSubmit}
notificationOptions={notificationOptions}
loading={loading}
/>
);
};
-262
View File
@@ -1,262 +0,0 @@
import Stack from "@mui/material/Stack";
import { TextInput } from "@/Components/v2/Inputs/TextInput";
import { AutoCompleteInput } from "@/Components/v2/Inputs/AutoComplete";
import { ConfigBox, BasePage } from "@/Components/v2/DesignElements";
import RadioGroup from "@mui/material/RadioGroup";
import FormControl from "@mui/material/FormControl";
import { RadioWithDescription } from "@/Components/v2/Inputs/RadioInput";
import { Button } from "@/Components/v2/Inputs";
import DeleteOutlineRoundedIcon from "@mui/icons-material/DeleteOutlineRounded";
import { Typography } from "@mui/material";
import humanInterval from "human-interval";
import { useTranslation } from "react-i18next";
import { useForm, Controller, useWatch } from "react-hook-form";
import { z } from "zod";
import { monitorSchema } from "@/Validation/v2/zod";
import { useTheme } from "@mui/material/styles";
import { zodResolver } from "@hookform/resolvers/zod";
import { useGet, usePost } from "@/Hooks/v2/UseApi";
import type { ApiResponse } from "@/Hooks/v2/UseApi";
const UptimeCreatePage = () => {
const { t } = useTranslation();
const theme = useTheme();
type FormValues = z.infer<typeof monitorSchema>;
type SubmitValues = Omit<FormValues, "interval"> & { interval: number | undefined };
const {
handleSubmit,
control,
setValue,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(monitorSchema) as any,
defaultValues: {
type: "http",
url: "",
n: 3,
notificationChannels: [],
name: "",
interval: "1 minute",
},
mode: "onChange",
});
const { response } = useGet<ApiResponse>("/notification-channels");
const { post, loading, error } = usePost<SubmitValues>();
const selectedType = useWatch({
control,
name: "type",
});
const notificationChannels = useWatch({
control,
name: "notificationChannels",
});
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) {
console.log(result);
} else {
console.error(error);
}
};
const notificationOptions = response?.data ?? [];
return (
<form onSubmit={handleSubmit(onSubmit)}>
<BasePage>
<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="http"
label={"HTTP"}
description={"Use HTTP to monitor your website or API endpoint."}
/>
<RadioWithDescription
value="https"
label="HTTPS"
description="Use HTTPS 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
name="url"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
label={t("url")}
fullWidth
error={!!errors.url}
helperText={errors.url ? errors.url.message : ""}
/>
)}
/>
<Controller
name="name"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
label={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"
label={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={[]} // important!
render={({ field }) => (
<AutoCompleteInput
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>
<DeleteOutlineRoundedIcon
onClick={() => {
const updated = notificationChannels.filter(
(id) => id !== notificationId
);
setValue("notificationChannels", updated);
}}
sx={{ 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"
label={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>
</form>
);
};
export default UptimeCreatePage;
-157
View File
@@ -1,157 +0,0 @@
import { BasePage } from "@/Components/v2/DesignElements";
import { HeaderControls } from "@/Components/v2/Monitors/HeaderControls";
import Stack from "@mui/material/Stack";
import { StatBox } from "@/Components/v2/DesignElements";
import { HistogramStatus } from "@/Components/v2/Monitors/HistogramStatus";
import { ChartAvgResponse } from "@/Components/v2/Monitors/ChartAvgResponse";
import { ChartResponseTime } from "@/Components/v2/Monitors/ChartResponseTime";
import { HeaderRange } from "@/Components/v2/Monitors/HeaderRange";
import { CheckTable } from "@/Pages/v2/Uptime/CheckTable";
import type { IMonitor } from "@/Types/Monitor";
import { useMediaQuery } from "@mui/material";
import { useTheme } from "@mui/material/styles";
import { useParams } from "react-router";
import { useGet, usePatch, type ApiResponse } from "@/Hooks/v2/UseApi";
import { useState } from "react";
import { getStatusPalette } from "@/Utils/v2/MonitorUtils";
import prettyMilliseconds from "pretty-ms";
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>(
`/monitors/${id}?embedChecks=true&range=${range}`,
{},
{ refreshInterval: 30000, keepPreviousData: true }
);
const {
response: upResponse,
isValidating: upIsValidating,
error: upError,
} = useGet<ApiResponse>(
`/monitors/${id}?embedChecks=true&range=${range}&status=up`,
{},
{ keepPreviousData: true }
);
const {
response: downResponse,
error: downError,
isValidating: downIsValidating,
} = useGet<ApiResponse>(
`/monitors/${id}?embedChecks=true&range=${range}&status=down`,
{},
{ keepPreviousData: true }
);
const { patch, loading: isPatching, error: postError } = usePatch<ApiResponse>();
const monitor: IMonitor = 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}
/>
<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;
-158
View File
@@ -1,158 +0,0 @@
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { Table } from "@/Components/v2/DesignElements";
import { HistogramResponseTime } from "@/Components/v2/Monitors/HistogramResponseTime";
import type { Header } from "@/Components/v2/DesignElements/Table";
import { ActionsMenu } from "@/Components/v2/ActionsMenu";
import { StatusLabel } from "@/Components/v2/DesignElements";
import { useTranslation } from "react-i18next";
import { useMediaQuery } from "@mui/material";
import { useTheme } from "@mui/material/styles";
import { useNavigate } from "react-router-dom";
import { usePatch } from "@/Hooks/v2/UseApi";
import type { ApiResponse } from "@/Hooks/v2/UseApi";
import type { IMonitor } from "@/Types/Monitor";
import type { ActionMenuItem } from "@/Components/v2/ActionsMenu";
export const MonitorTable = ({
monitors,
refetch,
}: {
monitors: IMonitor[];
refetch: Function;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const navigate = useNavigate();
const {
patch,
// loading: isPatching,
// error: postError,
} = usePatch<ApiResponse>();
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(`/v2/incidents/${monitor._id}`);
},
},
{
id: 4,
label: "Configure",
action: () => {
console.log("Open 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: () => {
console.log("Open delete");
},
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={"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;
};
let headers = getHeaders();
if (isSmall) {
headers = headers.filter((h) => h.id !== "histogram");
}
return (
<Table
headers={headers}
data={monitors}
onRowClick={(row) => {
navigate(row._id);
}}
/>
);
};
-247
View File
@@ -1,247 +0,0 @@
import Stack from "@mui/material/Stack";
import { TextInput } from "@/Components/v2/Inputs/TextInput";
import { AutoCompleteInput } from "@/Components/v2/Inputs/AutoComplete";
import { ConfigBox, BasePage } from "@/Components/v2/DesignElements";
import RadioGroup from "@mui/material/RadioGroup";
import FormControl from "@mui/material/FormControl";
import { RadioWithDescription } from "@/Components/v2/Inputs/RadioInput";
import { Button } from "@/Components/v2/Inputs";
import DeleteOutlineRoundedIcon from "@mui/icons-material/DeleteOutlineRounded";
import { Typography } from "@mui/material";
import { useTranslation } from "react-i18next";
import { monitorSchema } from "@/Validation/v2/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/v2/useInitMonitorForm";
type FormValues = z.infer<typeof monitorSchema>;
export const UptimeForm = ({
initialData,
onSubmit,
notificationOptions,
loading,
}: {
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
notificationOptions: any[];
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const {
handleSubmit,
control,
setValue,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(monitorSchema) as any,
defaultValues: defaults,
mode: "onChange",
});
const selectedType = useWatch({
control,
name: "type",
});
const notificationChannels = useWatch({
control,
name: "notificationChannels",
});
return (
<BasePage
component={"form"}
onSubmit={handleSubmit(onSubmit)}
>
<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="http"
label={"HTTP"}
description={"Use HTTP to monitor your website or API endpoint."}
/>
<RadioWithDescription
value="https"
label="HTTPS"
description="Use HTTPS 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
name="url"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
label={t("url")}
fullWidth
error={!!errors.url}
helperText={errors.url ? errors.url.message : ""}
/>
)}
/>
<Controller
name="name"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
label={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"
label={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={[]} // important!
render={({ field }) => (
<AutoCompleteInput
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>
<DeleteOutlineRoundedIcon
onClick={() => {
const updated = notificationChannels.filter(
(id) => id !== notificationId
);
setValue("notificationChannels", updated);
}}
sx={{ 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"
label={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>
);
};
@@ -1,74 +0,0 @@
import {
BasePageWithStates,
UpStatusBox,
DownStatusBox,
PausedStatusBox,
} from "@/Components/v2/DesignElements";
import { HeaderCreate } from "@/Components/v2/Monitors";
import Stack from "@mui/material/Stack";
import { MonitorTable } from "@/Pages/v2/Uptime/MonitorTable";
import { useTheme } from "@mui/material/styles";
import { useGet } from "@/Hooks/v2/UseApi";
import type { ApiResponse } from "@/Hooks/v2/UseApi";
import type { IMonitor } from "@/Types/Monitor";
import { useMediaQuery } from "@mui/material";
const UptimeMonitors = () => {
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const { response, isValidating, error, refetch } = useGet<ApiResponse>(
"/monitors?embedChecks=true",
{},
{ refreshInterval: 30000, keepPreviousData: true }
);
const monitors: IMonitor[] = response?.data ?? ([] as IMonitor[]);
const monitorStatuses = monitors.reduce(
(acc, monitor) => {
if (monitor.status === "up") {
acc.up += 1;
} else if (monitor.status === "down") {
acc.down += 1;
} else if (monitor.isActive === false) {
acc.paused += 1;
}
return acc;
},
{
up: 0,
down: 0,
paused: 0,
}
);
return (
<BasePageWithStates
loading={isValidating}
error={error}
items={monitors}
page="uptime"
actionLink="create"
>
<HeaderCreate
isLoading={isValidating}
path="/v2/uptime/create"
/>
<Stack
direction={isSmall ? "column" : "row"}
gap={theme.spacing(8)}
>
<UpStatusBox n={monitorStatuses.up} />
<DownStatusBox n={monitorStatuses.down} />
<PausedStatusBox n={monitorStatuses.paused} />
</Stack>
<MonitorTable
monitors={monitors}
refetch={refetch}
/>
</BasePageWithStates>
);
};
export default UptimeMonitors;