Files
Checkmate/client/src/pages/infrastructure/InfraForm.tsx
T
2025-12-08 19:55:29 +00:00

360 lines
11 KiB
TypeScript

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("Threshold Alerts")}
subtitle={t("Set percentage thresholds to trigger incidents.")}
rightContent={
<Stack gap={theme.spacing(4)}>
<Controller
name="thresholds.cpu"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="number"
fieldLabel={t("CPU %")}
fullWidth
error={!!errors.thresholds?.cpu}
helperText={errors.thresholds?.cpu?.message ?? ""}
/>
)}
/>
<Controller
name="thresholds.memory"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="number"
fieldLabel={t("Memory %")}
fullWidth
error={!!errors.thresholds?.memory}
helperText={errors.thresholds?.memory?.message ?? ""}
/>
)}
/>
<Controller
name="thresholds.disk"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="number"
fieldLabel={t("Disk %")}
fullWidth
error={!!errors.thresholds?.disk}
helperText={errors.thresholds?.disk?.message ?? ""}
/>
)}
/>
<Controller
name="thresholds.temperature"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="number"
fieldLabel={t("Temperature °C")}
fullWidth
error={!!errors.thresholds?.temperature}
helperText={errors.thresholds?.temperature?.message ?? ""}
/>
)}
/>
</Stack>
}
/>
<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="primary"
>
{t("settingsSave")}
</Button>
</Stack>
</BasePage>
);
};