Merge branch 'fix/form-cleanup' into feat/saas

This commit is contained in:
Alex Holliday committed 2025-12-29 18:32:18 +00:00
commit a250bf38aa
62 files changed
+701 -710

No files matched your search

+55 -28
View File
@@ -1,39 +1,66 @@
import { monitorSchemaInfra } from "@/validation/zod";
import ms from "ms";
import { useMemo } from "react";
import type {
FormValues,
SubmitValues,
} from "@/pages/infrastructure/InfraForm";
import type { IMonitor } from "@/types/monitor";
import humanInterval from "human-interval";
import { z } from "zod";
export const useInitForm = ({
initialData,
}: {
initialData: Partial<z.infer<typeof monitorSchemaInfra>> | undefined;
initialData: IMonitor | undefined;
}) => {
return useMemo(() => {
let humanInterval = "1 minute";
if (initialData?.interval) {
const parsed = Number(initialData.interval);
if (!isNaN(parsed)) {
humanInterval = ms(parsed, { long: true });
}
}
type InfraValues = z.infer<typeof monitorSchemaInfra>;
const defaults: InfraValues = {
type: "infrastructure",
url: initialData?.url || "",
secret: initialData?.secret || "",
n: initialData?.n || 3,
notificationChannels: initialData?.notificationChannels || [],
name: initialData?.name || "",
interval: humanInterval,
rejectUnauthorized: true,
thresholds: initialData?.thresholds ?? {
cpu: 100,
memory: 100,
disk: 100,
temperature: 100,
},
const apiToForm = (apiData: IMonitor): FormValues => {
const formData: FormValues = {
type: apiData.type,
url: apiData.url,
secret: apiData.secret,
n: apiData.n,
notificationChannels: apiData.notificationChannels,
name: apiData.name,
interval: ms(apiData.interval, { long: true }),
rejectUnauthorized: apiData.rejectUnauthorized,
thresholds: apiData.thresholds,
};
return formData;
};
return { defaults };
const formToApi = (formData: FormValues): SubmitValues => {
const submitData: SubmitValues = {
type: formData.type,
url: formData.url,
secret: formData.secret,
n: formData.n,
notificationChannels: formData.notificationChannels,
name: formData.name,
interval: humanInterval(formData.interval),
rejectUnauthorized: formData.rejectUnauthorized,
thresholds: formData.thresholds,
};
return submitData;
};
const defaults: FormValues = initialData
? apiToForm(initialData)
: {
type: "infrastructure",
url: "",
secret: "",
n: 3,
notificationChannels: [],
name: "",
interval: "1 minute",
rejectUnauthorized: true,
thresholds: {
cpu: 100,
memory: 100,
disk: 100,
temperature: 100,
},
};
return { defaults, apiToForm, formToApi };
}, [initialData]);
};
@@ -1,14 +1,13 @@
import { maintenanceSchema } from "@/validation/zod";
import { useMemo } from "react";
import type { FormValues } from "@/pages/maintenance/MaintenanceForm";
import { z } from "zod";
export const useInitForm = ({
initialData,
}: {
initialData: Partial<z.infer<typeof maintenanceSchema>> | undefined;
initialData: Partial<FormValues> | undefined;
}) => {
return useMemo(() => {
const defaults: z.infer<typeof maintenanceSchema> = {
const defaults: FormValues = {
name: initialData?.name || "",
repeat: initialData?.repeat || "no repeat",
startTime: initialData?.startTime
+45 -22
View File
@@ -1,32 +1,55 @@
import { monitorSchema } from "@/validation/zod";
import ms from "ms";
import { useMemo } from "react";
import humanInterval from "human-interval";
import type { FormValues, SubmitValues } from "@/pages/uptime/UptimeForm";
import type { IMonitor } from "@/types/monitor";
import ms from "ms";
import { z } from "zod";
export const useInitForm = ({
initialData,
}: {
initialData: Partial<z.infer<typeof monitorSchema>> | undefined;
initialData: IMonitor | undefined;
}) => {
return useMemo(() => {
let humanInterval = "1 minute";
if (initialData?.interval) {
const parsed = Number(initialData.interval);
if (!isNaN(parsed)) {
humanInterval = ms(parsed, { long: true });
}
}
const defaults: z.infer<typeof monitorSchema> = {
type: initialData?.type || "https",
url: initialData?.url || "",
port: initialData?.port || 80,
n: initialData?.n || 3,
notificationChannels: initialData?.notificationChannels || [],
name: initialData?.name || "",
interval: humanInterval,
rejectUnauthorized: initialData?.rejectUnauthorized ?? true,
const apiToForm = (apiData: IMonitor): FormValues => {
return {
type: apiData.type,
url: apiData.url,
port: apiData.port,
n: apiData.n,
notificationChannels: apiData.notificationChannels,
name: apiData.name,
interval: ms(apiData.interval, { long: true }),
rejectUnauthorized: apiData.rejectUnauthorized,
};
};
return { defaults };
const formToApi = (formData: FormValues): SubmitValues => {
const submitData: SubmitValues = {
type: formData.type,
url: formData.url,
port: formData.type === "port" ? formData.port : undefined,
n: formData.n,
notificationChannels: formData.notificationChannels,
name: formData.name,
interval: humanInterval(formData.interval),
rejectUnauthorized: formData.rejectUnauthorized,
};
return submitData;
};
const defaults: FormValues = initialData
? apiToForm(initialData)
: {
type: "https",
url: "",
port: 80,
n: 3,
notificationChannels: [],
name: "",
interval: "1 minute",
rejectUnauthorized: true,
};
return { defaults, apiToForm, formToApi };
}, [initialData]);
};
@@ -1,4 +1,4 @@
import { notificationChannelSchema } from "@/validation/zod";
import { notificationChannelSchema } from "@/validation";
import { useMemo } from "react";
import { z } from "zod";
+42 -20
View File
@@ -1,31 +1,53 @@
import { monitorSchemaPageSpeed } from "@/validation/zod";
import humanInterval from "human-interval";
import type { IMonitor } from "@/types/monitor";
import ms from "ms";
import { useMemo } from "react";
import type { FormValues, SubmitValues } from "@/pages/pagespeed/PageSpeedForm";
import { z } from "zod";
export const useInitForm = ({
initialData,
}: {
initialData: Partial<z.infer<typeof monitorSchemaPageSpeed>> | undefined;
initialData: IMonitor | undefined;
}) => {
return useMemo(() => {
let humanInterval = "3 minutes";
if (initialData?.interval) {
const parsed = Number(initialData.interval);
if (!isNaN(parsed)) {
humanInterval = ms(parsed, { long: true });
}
}
const defaults: z.infer<typeof monitorSchemaPageSpeed> = {
type: "pagespeed",
url: initialData?.url || "",
n: initialData?.n || 3,
notificationChannels: initialData?.notificationChannels || [],
name: initialData?.name || "",
interval: humanInterval,
rejectUnauthorized: true,
const apiToForm = (apiData: IMonitor): FormValues => {
console.log(JSON.stringify(apiData));
return {
type: apiData.type,
url: apiData.url,
n: apiData.n,
notificationChannels: apiData.notificationChannels,
name: apiData.name,
interval: ms(apiData.interval, { long: true }),
rejectUnauthorized: apiData.rejectUnauthorized,
};
};
return { defaults };
const formToApi = (form: FormValues): SubmitValues => {
const submitData: SubmitValues = {
type: form.type,
url: form.url,
n: form.n,
notificationChannels: form.notificationChannels,
name: form.name,
interval: humanInterval(form.interval),
rejectUnauthorized: form.rejectUnauthorized,
};
return submitData;
};
const defaults: FormValues = initialData
? apiToForm(initialData)
: {
type: "pagespeed",
url: "",
n: 3,
notificationChannels: [],
name: "",
interval: "3 minutes",
rejectUnauthorized: true,
};
return { defaults, formToApi };
}, [initialData]);
};
@@ -1,4 +1,4 @@
import { profileSchema } from "@/validation/zod";
import { profileSchema } from "@/validation";
import { useMemo } from "react";
import { z } from "zod";
@@ -1,14 +1,13 @@
import { recoverySchema } from "@/validation/zod";
import { useMemo } from "react";
import type { FormValues } from "@/pages/recovery/RecoveryForm";
import { z } from "zod";
export const useInitForm = ({
initialData,
}: {
initialData: Partial<z.infer<typeof recoverySchema>> | undefined;
initialData: FormValues | undefined;
}) => {
return useMemo(() => {
const defaults: z.infer<typeof recoverySchema> = {
const defaults: FormValues = {
email: initialData?.email || "",
};
return { defaults };
+1 -1
View File
@@ -1,4 +1,4 @@
import { resetSchema } from "@/validation/zod";
import { resetSchema } from "@/validation";
import { useMemo } from "react";
import { z } from "zod";
@@ -1,11 +1,12 @@
import { systemSettingsSchema } from "@/validation/zod";
import { systemSettingsSchema } from "@/validation";
import { useMemo } from "react";
import type { FormValues } from "@/pages/settings/SettingsForm";
import { z } from "zod";
export const useInitForm = ({
initialData,
}: {
initialData: Partial<z.infer<typeof systemSettingsSchema>> | undefined;
initialData: Partial<FormValues> | undefined;
}) => {
return useMemo(() => {
const defaults: z.infer<typeof systemSettingsSchema> = {
@@ -1,14 +1,12 @@
import { statusPageSchema } from "@/validation/zod";
import { useMemo } from "react";
import { z } from "zod";
import type { FormValues } from "@/pages/status-page/StatusPageForm";
export const useInitForm = ({
initialData,
}: {
initialData: Partial<z.infer<typeof statusPageSchema>> | undefined;
initialData: Partial<FormValues> | undefined;
}) => {
return useMemo(() => {
const defaults: z.infer<typeof statusPageSchema> = {
const defaults: FormValues = {
name: initialData?.name || "",
description: initialData?.description || "",
url: initialData?.url || Math.floor(Math.random() * 1000000).toFixed(0),
@@ -1,4 +1,4 @@
import { teamMemberSchema } from "@/validation/zod";
import { teamMemberSchema } from "@/validation";
import { useMemo } from "react";
import { z } from "zod";
+1 -1
View File
@@ -1,4 +1,4 @@
import { teamSchema } from "@/validation/zod";
import { teamSchema } from "@/validation";
import { useMemo } from "react";
import { z } from "zod";
+1 -1
View File
@@ -8,7 +8,7 @@ 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 { inviteSchema } from "@/validation";
import { z } from "zod";
import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
@@ -1,21 +1,14 @@
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 "@/types/api";
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";
import type { SubmitValues } from "@/pages/infrastructure/InfraForm";
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[]>>(
@@ -29,20 +22,12 @@ const InfraConfigurePage = () => {
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,
thresholds: data.thresholds,
interval,
};
if (!monitor) {
return null;
}
const result = await patch(`/monitors/${id}`, submitData);
const onSubmit = async (data: SubmitValues) => {
const result = await patch(`/monitors/${id}`, data);
if (result) {
navigate(`/infrastructure/${id}`);
} else {
@@ -1,27 +1,19 @@
import { InfraForm } from "@/pages/infrastructure/InfraForm";
import humanInterval from "human-interval";
import { useNavigate } from "react-router";
import { z } from "zod";
import { monitorSchemaInfra } from "@/validation/zod";
import { useGet, usePost } from "@/hooks/UseApi";
import type { ApiResponse } from "@/types/api";
import type { INotificationChannel } from "@/types/notification-channel";
import type { SubmitValues } from "@/pages/infrastructure/InfraForm";
const InfraCreatePage = () => {
type FormValues = z.infer<typeof monitorSchemaInfra>;
type SubmitValues = Omit<FormValues, "interval"> & {
interval: number | undefined;
};
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
"/notification-channels"
);
const { post, loading, error } = usePost<SubmitValues, any>();
const navigate = useNavigate();
const onSubmit = async (data: FormValues) => {
let interval = humanInterval(data.interval);
if (!interval) interval = 60000;
const submitData = { ...data, interval };
const result = await post("/monitors", submitData);
const onSubmit = async (data: SubmitValues) => {
const result = await post("/monitors", data);
if (result) {
navigate("/infrastructure");
} else {
+16 -8
View File
@@ -13,7 +13,7 @@ import { Typography } from "@mui/material";
import { useEffect, useState, useRef } from "react";
import { useTranslation } from "react-i18next";
import { monitorSchemaInfra } from "@/validation/zod";
import { monitorSchemaInfra } from "@/validation";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
@@ -24,8 +24,12 @@ import {
} from "react-hook-form";
import { useTheme } from "@mui/material/styles";
import { useInitForm } from "@/hooks/forms/UseInitInfraForm";
import type { IMonitor } from "@/types/monitor";
type FormValues = z.infer<typeof monitorSchemaInfra>;
export type FormValues = z.infer<typeof monitorSchemaInfra>;
export type SubmitValues = Omit<FormValues, "interval"> & {
interval: number | undefined;
};
export const InfraForm = ({
mode = "create",
@@ -35,14 +39,14 @@ export const InfraForm = ({
loading,
}: {
mode?: "create" | "configure";
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
initialData?: IMonitor;
onSubmit: SubmitHandler<SubmitValues>;
notificationOptions: any[];
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const { defaults, formToApi } = useInitForm({ initialData: initialData });
const urlInputRef = useRef<HTMLInputElement>(null);
const [selectedProtocol, setSelectedProtocol] = useState<string>("https");
@@ -97,8 +101,12 @@ export const InfraForm = ({
name: "notificationChannels",
});
const submitForm = (formData: FormValues) => {
onSubmit(formToApi(formData));
};
return (
<BasePage component={"form"} onSubmit={handleSubmit(onSubmit)}>
<BasePage component={"form"} onSubmit={handleSubmit(submitForm)}>
<ConfigBox
title={t("monitors.common.form.general.title")}
subtitle={t(`monitors.infrastructure.form.general.description`)}
@@ -303,7 +311,7 @@ export const InfraForm = ({
)}
/>
<Stack gap={theme.spacing(2)} mt={theme.spacing(2)}>
{notificationChannels.map((notificationId) => {
{notificationChannels.map((notificationId: string) => {
const option = notificationOptions.find(
(o: any) => o._id === notificationId
);
@@ -321,7 +329,7 @@ export const InfraForm = ({
strokeWidth={1.5}
onClick={() => {
const updated = notificationChannels.filter(
(id) => id !== notificationId
(id: string) => id !== notificationId
);
setValue("notificationChannels", updated);
}}
@@ -24,7 +24,7 @@ import { useLimitReached } from "@/hooks/UsePlanEntitlements";
const GLOBAL_REFRESH = config.GLOBAL_REFRESH;
const PageSpeedMonitorsPage = () => {
const InfraMonitorsPage = () => {
const theme = useTheme();
const { t } = useTranslation();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
@@ -131,4 +131,4 @@ const PageSpeedMonitorsPage = () => {
);
};
export default PageSpeedMonitorsPage;
export default InfraMonitorsPage;
@@ -2,13 +2,10 @@ 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 "@/types/api";
import { maintenanceSchema } from "@/validation/zod";
import type { IMonitor } from "@/types/monitor";
type FormValues = z.infer<typeof maintenanceSchema>;
import type { FormValues } from "@/pages/maintenance/MaintenanceForm";
const MaintenanceConfigPage = () => {
const { id } = useParams<{ id: string }>();
@@ -1,14 +1,11 @@
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 "@/types/api";
import { maintenanceSchema } from "@/validation/zod";
import type { IMonitor } from "@/types/monitor";
import type { IMaintenance } from "@/types/maintenance";
type FormValues = z.infer<typeof maintenanceSchema>;
import type { FormValues } from "@/pages/maintenance/MaintenanceForm";
const MaintenanceCreatePage = () => {
const navigate = useNavigate();
@@ -12,13 +12,13 @@ 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 { maintenanceSchema } from "@/validation";
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 type FormValues = z.infer<typeof maintenanceSchema>;
export const MaintenanceForm = ({
monitorOptions,
@@ -2,13 +2,10 @@ 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 "@/types/api";
import { notificationChannelSchema } from "@/validation/zod";
import type { INotificationChannel } from "@/types/notification-channel";
type FormValues = z.infer<typeof notificationChannelSchema>;
import type { FormValues } from "./NotificationChannelsForm";
const NotificationsChannelConfigPage = () => {
const navigate = useNavigate();
@@ -1,12 +1,9 @@
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>;
import type { FormValues } from "./NotificationChannelsForm";
const NotificationsChannelCreatePage = () => {
const { post, loading } = usePost<FormValues, INotificationChannel>();
@@ -10,14 +10,14 @@ 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 { notificationChannelSchema } from "@/validation";
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 type FormValues = z.infer<typeof notificationChannelSchema>;
export const NotificationChannelsForm = ({
initialData,
@@ -79,6 +79,7 @@ export const NotificationChannelsForm = ({
<Controller
name="name"
control={control}
defaultValue={defaults.name}
render={({ field }) => (
<TextInput
{...field}
+7 -18
View File
@@ -1,21 +1,14 @@
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 "@/types/api";
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";
import type { SubmitValues } from "@/pages/pagespeed/PageSpeedForm";
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[]>>(
@@ -29,16 +22,12 @@ const PageSpeedConfigurePage = () => {
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,
};
const result = await patch(`/monitors/${id}`, submitData);
if (!monitor) {
return null;
}
const onSubmit = async (data: SubmitValues) => {
const result = await patch(`/monitors/${id}`, data);
if (result) {
navigate(`/pagespeed/${id}`);
} else {
+3 -12
View File
@@ -1,28 +1,19 @@
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 "@/types/api";
import { useNavigate } from "react-router";
import type { INotificationChannel } from "@/types/notification-channel";
import type { SubmitValues } from "@/pages/pagespeed/PageSpeedForm";
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);
const onSubmit = async (data: SubmitValues) => {
const result = await post("/monitors", data);
if (result) {
navigate("/pagespeed");
} else {
+17 -10
View File
@@ -13,7 +13,7 @@ import { Typography } from "@mui/material";
import { useEffect, useState, useRef } from "react";
import { useTranslation } from "react-i18next";
import { monitorSchemaPageSpeed } from "@/validation/zod";
import { monitorSchemaPageSpeed } from "@/validation";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
@@ -24,8 +24,15 @@ import {
} from "react-hook-form";
import { useTheme } from "@mui/material/styles";
import { useInitForm } from "@/hooks/forms/UseInitPageSpeedForm";
import type { IMonitor } from "@/types/monitor";
type FormValues = z.infer<typeof monitorSchemaPageSpeed>;
export type FormValues = z.infer<typeof monitorSchemaPageSpeed>;
export type SubmitValues = Omit<
z.infer<typeof monitorSchemaPageSpeed>,
"interval"
> & {
interval: number | undefined;
};
export const PageSpeedForm = ({
mode = "create",
@@ -35,14 +42,14 @@ export const PageSpeedForm = ({
loading,
}: {
mode?: "create" | "configure";
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
initialData?: IMonitor;
onSubmit: SubmitHandler<SubmitValues>;
notificationOptions: any[];
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const { defaults, formToApi } = useInitForm({ initialData: initialData });
const urlInputRef = useRef<HTMLInputElement>(null);
const [selectedProtocol, setSelectedProtocol] = useState<string>("https");
@@ -92,13 +99,13 @@ export const PageSpeedForm = ({
}
}, [selectedProtocol]);
const notificationChannels = useWatch({
control,
name: "notificationChannels",
});
const notificationChannels =
useWatch({ control, name: "notificationChannels" }) || [];
const submitForm = (data: FormValues) => onSubmit(formToApi(data) as any);
return (
<BasePage component={"form"} onSubmit={handleSubmit(onSubmit)}>
<BasePage component={"form"} onSubmit={handleSubmit(submitForm)}>
<ConfigBox
title={t("monitors.common.form.general.title")}
subtitle={t("monitors.pageSpeed.form.general.description")}
+1 -3
View File
@@ -5,12 +5,10 @@ import { useState, useEffect } from "react";
import type { IUser } from "@/types/user";
import type { ApiResponse } from "@/types/api";
import { useGet, usePatch, useGetOnDemand } from "@/hooks/UseApi";
import { z } from "zod";
import { profileSchema } from "@/validation/zod";
import { useTranslation } from "react-i18next";
import { useAppDispatch } from "@/hooks/AppHooks";
import { setUser as setUserGlobal } from "@/features/authSlice";
type FormValues = z.infer<typeof profileSchema>;
import type { FormValues } from "@/pages/profile/ProfileForm";
const Profile = () => {
const { t } = useTranslation();
+6 -6
View File
@@ -12,8 +12,8 @@ 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>;
import { profileSchema } from "@/validation";
export type FormValues = z.infer<typeof profileSchema>;
export const ProfileForm = ({
user,
@@ -23,21 +23,21 @@ export const ProfileForm = ({
}: {
user: Partial<IUser> | null;
hasUser?: boolean;
initialData?: Partial<FormData>;
onSubmit: SubmitHandler<FormData>;
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const resolver = zodResolver(profileSchema) as unknown as Resolver<FormData>;
const resolver = zodResolver(profileSchema) as Resolver<FormValues>;
const {
handleSubmit,
control,
reset,
formState: { errors },
} = useForm<FormData>({
} = useForm<FormValues>({
resolver,
defaultValues: {
firstName: "",
+3 -6
View File
@@ -2,19 +2,16 @@ import { AuthBasePage } from "@/components/auth";
import { useTranslation } from "react-i18next";
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>;
import type { FormValues } from "@/pages/recovery/RecoveryForm";
const Recovery = () => {
const { t } = useTranslation();
const { post, loading } = usePost<FormData>();
const { post, loading } = usePost<FormValues>();
const { showToast } = useToast();
const onSubmit = async (data: FormData) => {
const onSubmit = async (data: FormValues) => {
await post("/recovery", data);
showToast(t("common.toasts.recoveryEmailSent"));
};
+6 -6
View File
@@ -9,18 +9,18 @@ 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 { useInitForm } from "@/hooks/forms/UseInitRecoveryForm";
import { recoverySchema } from "@/validation/zod";
type FormData = z.infer<typeof recoverySchema>;
import { recoverySchema } from "@/validation";
export type FormValues = z.infer<typeof recoverySchema>;
export const RecoveryForm = ({
initialData,
onSubmit,
loading,
}: {
initialData?: Partial<FormData>;
onSubmit: SubmitHandler<FormData>;
initialData?: FormValues;
onSubmit: SubmitHandler<FormValues>;
loading: boolean;
}) => {
const { t } = useTranslation();
@@ -32,7 +32,7 @@ export const RecoveryForm = ({
control,
reset,
formState: { errors },
} = useForm<FormData>({
} = useForm<FormValues>({
resolver: zodResolver(recoverySchema),
defaultValues: {
email: "",
+2 -5
View File
@@ -3,8 +3,6 @@ import { AuthBasePage } from "@/components/auth";
import { useTranslation } from "react-i18next";
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";
@@ -15,8 +13,7 @@ import {
setSelectedTeamId,
logout,
} from "@/features/authSlice";
type FormData = z.infer<typeof resetSchema>;
import type { FormValues } from "@/pages/recovery/ResetForm";
const Reset = () => {
const { t } = useTranslation();
@@ -26,7 +23,7 @@ const Reset = () => {
const { toastSuccess } = useToast();
const { id: token } = useParams<{ id: string }>();
const onSubmit = async (data: FormData) => {
const onSubmit = async (data: FormValues) => {
const result = await post(`/recovery/reset`, {
password: data.password,
token: token || "",
+5 -5
View File
@@ -11,8 +11,8 @@ 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>;
import { resetSchema } from "@/validation";
export type FormValues = z.infer<typeof resetSchema>;
export const ResetForm = ({
initialData,
@@ -20,8 +20,8 @@ export const ResetForm = ({
loading,
}: {
hasUser?: boolean;
initialData?: Partial<FormData>;
onSubmit: SubmitHandler<FormData>;
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
loading: boolean;
}) => {
const { t } = useTranslation();
@@ -33,7 +33,7 @@ export const ResetForm = ({
control,
reset,
formState: { errors },
} = useForm<FormData>({
} = useForm<FormValues>({
resolver: zodResolver(resetSchema),
defaultValues: {
password: "",
+1 -4
View File
@@ -7,12 +7,9 @@ import {} from "react-i18next";
import { useAppSelector } from "@/hooks/AppHooks";
import { useGet, usePatch, usePost } from "@/hooks/UseApi";
import type { ApiResponse } from "@/types/api";
import { z } from "zod";
import { systemSettingsSchema } from "@/validation/zod";
import type { FormValues } from "@/pages/settings/SettingsForm";
const AdminSettingsPage = () => {
type FormValues = z.infer<typeof systemSettingsSchema>;
const user = useAppSelector((state) => state.auth.user);
const orgPermissions = user?.org?.permissions || [];
+2 -2
View File
@@ -6,14 +6,14 @@ import { ConfigBox } from "@/components/design-elements";
import { useTheme } from "@mui/material/styles";
import { useTranslation } from "react-i18next";
import { systemSettingsSchema } from "@/validation/zod";
import { systemSettingsSchema } from "@/validation";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm, Controller, type SubmitHandler } from "react-hook-form";
import { useInitForm } from "@/hooks/forms/UseInitSettingsForm";
import { useEffect } from "react";
type FormValues = z.infer<typeof systemSettingsSchema>;
export type FormValues = z.infer<typeof systemSettingsSchema>;
export const SettingsForm = ({
initialData,
@@ -2,14 +2,11 @@ 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 "@/types/api";
import { statusPageSchema } from "@/validation/zod";
import type { IMonitor } from "@/types/monitor";
import type { IStatusPageWithMonitors } from "@/types/status-page";
type FormValues = z.infer<typeof statusPageSchema>;
import type { FormValues } from "@/pages/status-page/StatusPageForm";
const StatusPageConfigPage = () => {
const navigate = useNavigate();
@@ -1,13 +1,10 @@
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 "@/types/api";
import { statusPageSchema } from "@/validation/zod";
import type { IMonitor } from "@/types/monitor";
type FormValues = z.infer<typeof statusPageSchema>;
import type { FormValues } from "@/pages/status-page/StatusPageForm";
const StatusPageCreatePage = () => {
const navigate = useNavigate();
@@ -9,7 +9,7 @@ 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 { statusPageSchema } from "@/validation";
import {
useForm,
Controller,
@@ -20,7 +20,7 @@ import { useEffect } from "react";
import { useInitForm } from "@/hooks/forms/UseInitStatusPageForm";
import type { IMonitor } from "@/types/monitor";
type FormValues = z.infer<typeof statusPageSchema>;
export type FormValues = z.infer<typeof statusPageSchema>;
export const StatusPageForm = ({
initialData,
+2 -1
View File
@@ -13,6 +13,7 @@ import { mutate } from "swr";
import type { IUser } from "@/types/user";
import { useAppDispatch } from "@/hooks/AppHooks";
import { setUser } from "@/features/authSlice";
import type { FormValues } from "@/pages/teams/TeamMemberForm";
const TeamMemberConfig = () => {
const [dialogOpen, setDialogOpen] = useState<boolean>(false);
@@ -20,7 +21,7 @@ const TeamMemberConfig = () => {
const navigate = useNavigate();
const { t } = useTranslation();
const { id, memberId } = useParams();
const { patch, loading } = usePatch();
const { patch, loading } = usePatch<Partial<FormValues>, any>();
const { get: getOnDemand } = useGetOnDemand<IUser>();
const dispatch = useAppDispatch();
const { response } = useGet<ApiResponse<any>>("/team-members");
+2 -1
View File
@@ -9,6 +9,7 @@ import { useGetOnDemand } from "@/hooks/UseApi";
import type { IUser } from "@/types/user";
import { useAppDispatch } from "@/hooks/AppHooks";
import { setUser } from "@/features/authSlice";
import type { FormValues } from "@/pages/teams/TeamMemberForm";
const TeamMemberCreate = () => {
const navigate = useNavigate();
const dispatch = useAppDispatch();
@@ -17,7 +18,7 @@ const TeamMemberCreate = () => {
const { response } = useGet<ApiResponse<any>>("/team-members?type=org");
const { response: rolesResponse } =
useGet<ApiResponse<any>>("/roles?type=team");
const { post } = usePost<ApiResponse<any>>();
const { post } = usePost<FormValues>();
const teamMembers = response?.data || [];
const roles = rolesResponse?.data || [];
+2 -2
View File
@@ -9,12 +9,12 @@ 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 { teamMemberSchema } from "@/validation";
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 type FormValues = z.infer<typeof teamMemberSchema>;
export const TeamMemberForm = ({
mode = "create",
+2 -4
View File
@@ -1,20 +1,18 @@
import { TeamsForm } from "@/pages/teams/TeamsForm";
import { useNavigate, useParams } from "react-router";
import { z } from "zod";
import { teamSchema } from "@/validation/zod";
import { useGet, usePatch, useGetOnDemand } from "@/hooks/UseApi";
import type { ApiResponse } from "@/types/api";
import type { IUser } from "@/types/user";
import { useAppDispatch } from "@/hooks/AppHooks";
import { setUser } from "@/features/authSlice";
import { mutate } from "swr";
import type { FormValues } from "@/pages/teams/TeamsForm";
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 { patch, loading } = usePatch<Partial<FormValues>, ApiResponse<any>>();
const { get: getOnDemand } = useGetOnDemand<IUser>();
const dispatch = useAppDispatch();
+1 -3
View File
@@ -1,17 +1,15 @@
import { TeamsForm } from "@/pages/teams/TeamsForm";
import { useNavigate } from "react-router";
import { z } from "zod";
import { teamSchema } from "@/validation/zod";
import { useGet, usePost, useGetOnDemand } from "@/hooks/UseApi";
import type { ApiResponse } from "@/types/api";
import { mutate } from "swr";
import type { IUser } from "@/types/user";
import { useAppDispatch } from "@/hooks/AppHooks";
import { setUser } from "@/features/authSlice";
import type { FormValues } from "@/pages/teams/TeamsForm";
const TeamsCreatePage = () => {
type FormValues = z.infer<typeof teamSchema>;
const { response } = useGet<ApiResponse<any>>("/roles?type=team");
const { post, loading } = usePost<FormValues>();
const navigate = useNavigate();
+2 -2
View File
@@ -9,12 +9,12 @@ 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 { teamSchema } from "@/validation";
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 type FormValues = z.infer<typeof teamSchema>;
export const TeamsForm = ({
mode = "create",
+9 -24
View File
@@ -1,21 +1,14 @@
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 "@/types/api";
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";
import type { SubmitValues } from "@/pages/uptime/UptimeForm";
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[]>>(
@@ -24,23 +17,17 @@ const UptimeConfigurePage = () => {
const { response: monitorResponse } = useGet<ApiResponse<IMonitor>>(
`/monitors/${id}`
);
const monitor = monitorResponse?.data || {};
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,
rejectUnauthorized: data.rejectUnauthorized,
};
const result = await patch(`/monitors/${id}`, submitData);
if (!monitor) {
return null;
}
const onSubmit = async (data: SubmitValues) => {
const result = await patch(`/monitors/${id}`, data);
if (result) {
navigate(`/uptime/${id}`);
} else {
@@ -50,9 +37,7 @@ const UptimeConfigurePage = () => {
return (
<UptimeForm
mode="configure"
initialData={{
...monitor,
}}
initialData={monitor}
onSubmit={onSubmit}
notificationOptions={notificationOptions}
loading={loading}
+3 -12
View File
@@ -1,28 +1,19 @@
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 "@/types/api";
import { useNavigate } from "react-router";
import type { INotificationChannel } from "@/types/notification-channel";
import type { SubmitValues } from "@/pages/uptime/UptimeForm";
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);
const onSubmit = async (data: SubmitValues) => {
const result = await post("/monitors", data);
if (result) {
navigate("/uptime");
} else {
+14 -7
View File
@@ -14,7 +14,7 @@ import { Typography } from "@mui/material";
import { useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { monitorSchema } from "@/validation/zod";
import { monitorSchema } from "@/validation";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
@@ -23,10 +23,14 @@ import {
useWatch,
type SubmitHandler,
} from "react-hook-form";
import type { IMonitor } from "@/types/monitor";
import { useTheme } from "@mui/material/styles";
import { useInitForm } from "@/hooks/forms/UseInitMonitorFrom";
type FormValues = z.infer<typeof monitorSchema>;
export type FormValues = z.infer<typeof monitorSchema>;
export type SubmitValues = Omit<z.infer<typeof monitorSchema>, "interval"> & {
interval: number | undefined;
};
export const UptimeForm = ({
mode = "create",
@@ -36,14 +40,14 @@ export const UptimeForm = ({
loading,
}: {
mode?: "create" | "configure";
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
initialData?: IMonitor;
onSubmit: SubmitHandler<SubmitValues>;
notificationOptions: any[];
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const { defaults, formToApi } = useInitForm({ initialData: initialData });
const urlInputRef = useRef<HTMLInputElement>(null);
const {
@@ -73,6 +77,10 @@ export const UptimeForm = ({
name: "notificationChannels",
});
const submitForm = (formData: FormValues) => {
onSubmit(formToApi(formData));
};
useEffect(() => {
if (!selectedType) return;
@@ -96,7 +104,6 @@ export const UptimeForm = ({
} else {
setValue("url", `${selectedType}://${url}`);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedType, setValue]);
useEffect(() => {
@@ -108,7 +115,7 @@ export const UptimeForm = ({
}, [selectedType]);
return (
<BasePage component={"form"} onSubmit={handleSubmit(onSubmit)}>
<BasePage component={"form"} onSubmit={handleSubmit(submitForm)}>
{mode === "create" && (
<ConfigBox
title={t("monitors.uptime.form.type.title")}
+8
View File
@@ -32,12 +32,20 @@ export interface IMonitor {
latestChecks: ICheck[];
n: number;
name: string;
port: number;
notificationChannels: string[];
status: MonitorStatus;
type: string;
updatedAt: string;
updatedBy: string;
url: string;
secret: string;
thresholds: {
cpu: number;
memory: number;
disk: number;
temperature: number;
};
__v: number;
_id: string;
}
+13 -1
View File
@@ -1,3 +1,15 @@
export * from "./zod";
export * from "./login";
export * from "./register";
export * from "./monitor";
export * from "./pagespeed";
export * from "./infra";
export * from "./utils";
export * from "./notification-channel";
export * from "./maintenance";
export * from "./team";
export * from "./system-settings";
export * from "./status-page";
export * from "./invite";
export * from "./recovery";
export * from "./reset";
export * from "./profile";
+74
View File
@@ -0,0 +1,74 @@
import { z } from "zod";
import { urlRegex, durationSchema } from "@/validation/utils";
export const monitorSchemaInfra = z.object({
type: z.string().min(1, "You must select an option"),
url: z.string().min(1, "URL is required").regex(urlRegex, "Invalid URL"),
secret: z.string().min(1, "Secret is required"),
n: z.coerce
.number({ message: "Number required" })
.min(1, "Minimum value is 1")
.max(25, "Maximum value is 25"),
notificationChannels: z.array(z.string()).optional().default([]),
name: z.string().min(1, "Display name is required"),
interval: durationSchema(60000),
rejectUnauthorized: z.boolean().default(true),
thresholds: z.object({
cpu: z.preprocess(
(val) => (typeof val === "number" ? String(val) : val),
z
.string()
.trim()
.min(1, { message: "CPU threshold is required" })
.refine((v) => /^-?\d+(\.\d+)?$/.test(v), {
message: "CPU must be a number",
})
.transform((v) => Number(v))
.refine((v) => v >= 0 && v <= 100, {
message: "CPU must be between 0 and 100",
})
),
memory: z.preprocess(
(val) => (typeof val === "number" ? String(val) : val),
z
.string()
.trim()
.min(1, { message: "Memory threshold is required" })
.refine((v) => /^-?\d+(\.\d+)?$/.test(v), {
message: "Memory must be a number",
})
.transform((v) => Number(v))
.refine((v) => v >= 0 && v <= 100, {
message: "Memory must be between 0 and 100",
})
),
disk: z.preprocess(
(val) => (typeof val === "number" ? String(val) : val),
z
.string()
.trim()
.min(1, { message: "Disk threshold is required" })
.refine((v) => /^-?\d+(\.\d+)?$/.test(v), {
message: "Disk must be a number",
})
.transform((v) => Number(v))
.refine((v) => v >= 0 && v <= 100, {
message: "Disk must be between 0 and 100",
})
),
temperature: z.preprocess(
(val) => (typeof val === "number" ? String(val) : val),
z
.string()
.trim()
.min(1, { message: "Temperature threshold is required" })
.refine((v) => /^-?\d+(\.\d+)?$/.test(v), {
message: "Temperature must be a number",
})
.transform((v) => Number(v))
.refine((v) => v >= -50 && v <= 150, {
message: "Temperature must be between -50 and 150",
})
),
}),
});
+9
View File
@@ -0,0 +1,9 @@
import { z } from "zod";
export const inviteSchema = z.object({
email: z.email("Invalid email address"),
teamId: z.string().min(1, "Team is required"),
teamRoleId: z.string().min(1, "Role is required"),
orgRoleId: z.string().optional(),
});
+29
View File
@@ -0,0 +1,29 @@
import { z } from "zod";
import { MaintenanceRepeats } from "@/types/maintenance";
export const maintenanceSchema = z
.object({
name: z.string().min(1, "Maintenance name is required"),
repeat: z.enum(MaintenanceRepeats),
startTime: z.date(),
endTime: z.date(),
monitors: z.array(z.string()),
})
.superRefine((data, ctx) => {
if (data.endTime <= data.startTime) {
ctx.addIssue({
code: "custom",
path: ["endTime"],
message: "End time must be after start time",
});
}
if (data.startTime === data.endTime) {
ctx.addIssue({
code: "custom",
path: ["endTime"],
message: "Start time and end time cannot be the same",
});
}
});
+42
View File
@@ -0,0 +1,42 @@
import { z } from "zod";
import { urlRegex, durationSchema } from "@/validation/utils";
export const monitorSchema = z
.object({
type: z.string().min(1, "You must select an option"),
url: z.string().min(1, "URL is required").regex(urlRegex, "Invalid URL"),
n: z.coerce
.number({ message: "Number required" })
.min(1, "Minimum value is 1")
.max(25, "Maximum value is 25"),
port: z.coerce.number().optional(),
notificationChannels: z.array(z.string()).optional().default([]),
name: z.string().min(1, "Display name is required"),
interval: durationSchema(10000),
rejectUnauthorized: z.boolean().default(true),
})
.superRefine((data, ctx) => {
if (data.type === "port") {
if (!data.port) {
ctx.addIssue({
code: "custom",
message: "Port is required for port monitoring",
path: ["port"],
});
}
if (isNaN(Number(data.port))) {
ctx.addIssue({
code: "custom",
message: "Port must be a number",
path: ["port"],
});
}
if (Number(data.port) < 1 || Number(data.port) > 65535) {
ctx.addIssue({
code: "custom",
message: "Port must be between 1 and 65535",
path: ["port"],
});
}
}
});
@@ -0,0 +1,44 @@
import { z } from "zod";
import { ChannelTypes } from "@/types/notification-channel";
import { urlRegex } from "@/validation/utils";
export const notificationChannelSchema = z
.object({
name: z.string().min(1, "Channel name is required"),
type: z.enum(ChannelTypes, { error: "Invalid channel type" }),
config: z.object({
url: z
.string()
.regex(urlRegex, "Invalid URL")
.or(z.literal(""))
.optional(),
emailAddress: z
.email("Invalid email address")
.or(z.literal(""))
.optional(),
}),
})
.superRefine((data, ctx) => {
const { type, config } = data;
if (!config.url && !config.emailAddress) {
ctx.addIssue({
code: "custom",
message: "Either a URL or an email address must be provided.",
path: ["config"],
});
}
if (type === "email" && !config.emailAddress) {
ctx.addIssue({
code: "custom",
message: "Email address is required for email-type channels.",
path: ["config", "emailAddress"],
});
} else if (type !== "email" && !config.url) {
ctx.addIssue({
code: "custom",
message: "URL is required for non-email-type channels.",
path: ["config", "url"],
});
}
});
+15
View File
@@ -0,0 +1,15 @@
import { z } from "zod";
import { urlRegex, durationSchema } from "@/validation/utils";
export const monitorSchemaPageSpeed = z.object({
type: z.string().min(1, "You must select an option"),
url: z.string().min(1, "URL is required").regex(urlRegex, "Invalid URL"),
n: z.coerce
.number({ message: "Number required" })
.min(1, "Minimum value is 1")
.max(25, "Maximum value is 25"),
notificationChannels: z.array(z.string()).optional().default([]),
name: z.string().min(1, "Display name is required"),
interval: durationSchema(180000),
rejectUnauthorized: z.boolean().default(true),
});
+41
View File
@@ -0,0 +1,41 @@
import { z } from "zod";
export const profileSchema = z
.object({
firstName: z
.string()
.min(1, { message: "First Name must be at least one char" })
.optional(),
lastName: z
.string()
.min(1, { message: "Last Name must be at least one char" })
.optional(),
password: z.preprocess(
(val) => (val === "" ? undefined : val),
z
.string()
.min(6, { message: "Password must be at least 6 characters" })
.optional()
),
confirmPassword: z.preprocess(
(val) => (val === "" ? undefined : val),
z
.string()
.min(6, { message: "Confirm Password must be at least 6 characters" })
.optional()
),
})
.refine(
(data) => {
if (!data.password && !data.confirmPassword) return true;
if (!data.password || !data.confirmPassword) return false;
return data.password === data.confirmPassword;
},
{
message: "Passwords must match",
path: ["confirmPassword"],
}
);
+6
View File
@@ -0,0 +1,6 @@
import { z } from "zod";
export const recoverySchema = z.object({
email: z.email({ message: "Invalid email address" }).trim().toLowerCase(),
});
+16
View File
@@ -0,0 +1,16 @@
import { z } from "zod";
export const resetSchema = z
.object({
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",
});
+14
View File
@@ -0,0 +1,14 @@
import { z } from "zod";
const statusPageUrlRegex = /^[A-Za-z0-9]+$/;
export const statusPageSchema = z.object({
name: z.string().min(1, "Status page name is required"),
description: z.string().optional(),
url: z
.string()
.min(1, "URL is required")
.regex(statusPageUrlRegex, "Invalid URL"),
isPublished: z.boolean().optional(),
monitors: z.array(z.string()),
});
+55
View File
@@ -0,0 +1,55 @@
import { z } from "zod";
import { optionalString } from "@/validation/utils";
export const systemSettingsSchema = z.object({
systemEmailHost: optionalString(
z.string().trim().min(1, { message: "SMTP host is required" }).max(255, {
message: "SMTP host must be 255 characters or fewer",
})
),
systemEmailPort: optionalString(
z
.union([z.number().int(), z.string().regex(/^\d+$/)])
.transform((val) => (typeof val === "string" ? Number(val) : val))
.refine(
(val) =>
val === undefined ||
(Number.isInteger(val) && val > 0 && val < 65536),
{
message: "Port must be a number between 1 and 65535",
}
)
),
systemEmailAddress: optionalString(
z.string().email({ message: "SMTP email must be valid" })
),
systemEmailPassword: optionalString(
z.string().max(255, {
message: "SMTP password must be 255 characters or fewer",
})
),
systemEmailUser: optionalString(
z.string().trim().max(255, {
message: "SMTP username must be 255 characters or fewer",
})
),
systemEmailConnectionHost: optionalString(
z.string().trim().max(255, {
message: "Connection host must be 255 characters or fewer",
})
),
systemEmailTLSServername: optionalString(
z.string().trim().max(255, {
message: "TLS server name must be 255 characters or fewer",
})
),
systemEmailSecure: z.boolean().optional(),
systemEmailPool: z.boolean().optional(),
systemEmailIgnoreTLS: z.boolean().optional(),
systemEmailRequireTLS: z.boolean().optional(),
systemEmailRejectUnauthorized: z.boolean().optional(),
checksRetentionDays: z.coerce
.number({ message: "Number required" })
.min(1, "Retention days must be at least 1")
.max(365, "Retention days cannot exceed 365 days"),
});
+14
View File
@@ -0,0 +1,14 @@
import { z } from "zod";
export const teamSchema = z.object({
name: z.string().min(1, "Team name is required"),
roleId: z.string().min(1, "Role is required"),
description: z.string().optional(),
});
export const teamMemberSchema = z.object({
userId: z.string().min(1, "User is required"),
roleId: z.string().min(1, "Role is required"),
teamId: z.string().min(1, "Team is required"),
});
+30
View File
@@ -0,0 +1,30 @@
import { z } from "zod";
import humanInterval from "human-interval";
import ms from "ms";
export const urlRegex =
/^(https?:\/\/)?(localhost|([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}|[a-zA-Z0-9-]+|(\d{1,3}\.){3}\d{1,3})(:\d{1,5})?(\/.*)?$/;
export const durationSchema = (minInterval: number) =>
z.string().superRefine((val, ctx) => {
const milis = humanInterval(val);
if (!milis || isNaN(milis)) {
ctx.addIssue({
code: "custom",
message: "Invalid duration format",
});
} else if (milis < minInterval) {
ctx.addIssue({
code: "custom",
message: `Minimum duration is ${ms(minInterval, { long: true })}`,
});
}
});
export const optionalString = <T extends z.ZodTypeAny>(schema: T) =>
z.preprocess(
(val) =>
val === "" || val === null || val === undefined ? undefined : val,
schema.optional()
);
-412
View File
@@ -1,412 +0,0 @@
import { z } from "zod";
import humanInterval from "human-interval";
import { ChannelTypes } from "@/types/notification-channel";
import { MaintenanceRepeats } from "@/types/maintenance";
const urlRegex =
/^(https?:\/\/)?(localhost|([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}|[a-zA-Z0-9-]+|(\d{1,3}\.){3}\d{1,3})(:\d{1,5})?(\/.*)?$/;
const durationSchema = z
.string()
.optional()
.superRefine((val, ctx) => {
if (!val || val.trim() === "") return;
const ms = humanInterval(val);
if (!ms || isNaN(ms)) {
ctx.addIssue({
code: "custom",
message: "Invalid duration format",
});
} else if (ms < 10000) {
ctx.addIssue({
code: "custom",
message: "Minimum duration is 10 seconds",
});
}
});
const durationSchemaPageSpeed = z
.string()
.optional()
.superRefine((val, ctx) => {
if (!val || val.trim() === "") return;
const ms = humanInterval(val);
if (!ms || isNaN(ms)) {
ctx.addIssue({
code: "custom",
message: "Invalid duration format",
});
} else if (ms < 180000) {
ctx.addIssue({
code: "custom",
message: "Minimum duration is 3 minutes",
});
}
});
const durationSchemaInfra = z
.string()
.optional()
.superRefine((val, ctx) => {
if (!val || val.trim() === "") return;
const ms = humanInterval(val);
if (!ms || isNaN(ms)) {
ctx.addIssue({
code: "custom",
message: "Invalid duration format",
});
} else if (ms < 60000) {
ctx.addIssue({
code: "custom",
message: "Minimum duration is 1 minute",
});
}
});
const optionalString = <T extends z.ZodTypeAny>(schema: T) =>
z.preprocess(
(val) =>
val === "" || val === null || val === undefined ? undefined : val,
schema.optional()
);
export const monitorSchema = z
.object({
type: z.string().min(1, "You must select an option"),
url: z.string().min(1, "URL is required").regex(urlRegex, "Invalid URL"),
n: z.coerce
.number({ message: "Number required" })
.min(1, "Minimum value is 1")
.max(25, "Maximum value is 25"),
port: z.coerce.number().optional(),
notificationChannels: z.array(z.string()).optional().default([]),
name: z.string().min(1, "Display name is required"),
interval: durationSchema,
rejectUnauthorized: z.boolean().default(true),
})
.superRefine((data, ctx) => {
if (data.type === "port") {
if (!data.port) {
ctx.addIssue({
code: "custom",
message: "Port is required for port monitoring",
path: ["port"],
});
}
if (isNaN(Number(data.port))) {
ctx.addIssue({
code: "custom",
message: "Port must be a number",
path: ["port"],
});
}
if (Number(data.port) < 1 || Number(data.port) > 65535) {
ctx.addIssue({
code: "custom",
message: "Port must be between 1 and 65535",
path: ["port"],
});
}
}
})
.transform((data) => {
if (data.type !== "port") {
return { ...data, port: undefined };
}
return data;
});
export const monitorSchemaPageSpeed = z.object({
type: z.string().min(1, "You must select an option"),
url: z.string().min(1, "URL is required").regex(urlRegex, "Invalid URL"),
n: z.coerce
.number({ message: "Number required" })
.min(1, "Minimum value is 1")
.max(25, "Maximum value is 25"),
notificationChannels: z.array(z.string()).optional().default([]),
name: z.string().min(1, "Display name is required"),
interval: durationSchemaPageSpeed,
rejectUnauthorized: z.boolean().default(true),
});
export const monitorSchemaInfra = z.object({
type: z.string().min(1, "You must select an option"),
url: z.string().min(1, "URL is required").regex(urlRegex, "Invalid URL"),
secret: z.string().min(1, "Secret is required"),
n: z.coerce
.number({ message: "Number required" })
.min(1, "Minimum value is 1")
.max(25, "Maximum value is 25"),
notificationChannels: z.array(z.string()).optional().default([]),
name: z.string().min(1, "Display name is required"),
interval: durationSchemaInfra,
rejectUnauthorized: z.boolean().default(true),
thresholds: z.object({
// Accept both strings and numbers from the form. Enforce required and ranges with clear messages.
cpu: z.preprocess(
(val) => (typeof val === "number" ? String(val) : val),
z
.string()
.trim()
.min(1, { message: "CPU threshold is required" })
.refine((v) => /^-?\d+(\.\d+)?$/.test(v), {
message: "CPU must be a number",
})
.transform((v) => Number(v))
.refine((v) => v >= 0 && v <= 100, {
message: "CPU must be between 0 and 100",
})
),
memory: z.preprocess(
(val) => (typeof val === "number" ? String(val) : val),
z
.string()
.trim()
.min(1, { message: "Memory threshold is required" })
.refine((v) => /^-?\d+(\.\d+)?$/.test(v), {
message: "Memory must be a number",
})
.transform((v) => Number(v))
.refine((v) => v >= 0 && v <= 100, {
message: "Memory must be between 0 and 100",
})
),
disk: z.preprocess(
(val) => (typeof val === "number" ? String(val) : val),
z
.string()
.trim()
.min(1, { message: "Disk threshold is required" })
.refine((v) => /^-?\d+(\.\d+)?$/.test(v), {
message: "Disk must be a number",
})
.transform((v) => Number(v))
.refine((v) => v >= 0 && v <= 100, {
message: "Disk must be between 0 and 100",
})
),
temperature: z.preprocess(
(val) => (typeof val === "number" ? String(val) : val),
z
.string()
.trim()
.min(1, { message: "Temperature threshold is required" })
.refine((v) => /^-?\d+(\.\d+)?$/.test(v), {
message: "Temperature must be a number",
})
.transform((v) => Number(v))
.refine((v) => v >= -50 && v <= 150, {
message: "Temperature must be between -50 and 150",
})
),
}),
});
export const teamSchema = z.object({
name: z.string().min(1, "Team name is required"),
roleId: z.string().min(1, "Role is required"),
description: z.string().optional(),
});
export const teamMemberSchema = z.object({
userId: z.string().min(1, "User is required"),
roleId: z.string().min(1, "Role is required"),
teamId: z.string().min(1, "Team is required"),
});
export const inviteSchema = z.object({
email: z.email("Invalid email address"),
teamId: z.string().min(1, "Team is required"),
teamRoleId: z.string().min(1, "Role is required"),
orgRoleId: z.string().optional(),
});
export const notificationChannelSchema = z
.object({
name: z.string().min(1, "Channel name is required"),
type: z.enum(ChannelTypes, { error: "Invalid channel type" }),
config: z.object({
url: z
.string()
.regex(urlRegex, "Invalid URL")
.or(z.literal(""))
.optional(),
emailAddress: z
.email("Invalid email address")
.or(z.literal(""))
.optional(),
}),
})
.superRefine((data, ctx) => {
const { type, config } = data;
if (!config.url && !config.emailAddress) {
ctx.addIssue({
code: "custom",
message: "Either a URL or an email address must be provided.",
path: ["config"],
});
}
if (type === "email" && !config.emailAddress) {
ctx.addIssue({
code: "custom",
message: "Email address is required for email-type channels.",
path: ["config", "emailAddress"],
});
} else if (type !== "email" && !config.url) {
ctx.addIssue({
code: "custom",
message: "URL is required for non-email-type channels.",
path: ["config", "url"],
});
}
});
export const maintenanceSchema = z
.object({
name: z.string().min(1, "Maintenance name is required"),
repeat: z.enum(MaintenanceRepeats),
startTime: z.date(),
endTime: z.date(),
monitors: z.array(z.string()),
})
.superRefine((data, ctx) => {
if (data.endTime <= data.startTime) {
ctx.addIssue({
code: "custom",
path: ["endTime"],
message: "End time must be after start time",
});
}
if (data.startTime === data.endTime) {
ctx.addIssue({
code: "custom",
path: ["endTime"],
message: "Start time and end time cannot be the same",
});
}
});
export const systemSettingsSchema = z.object({
systemEmailHost: optionalString(
z.string().trim().min(1, { message: "SMTP host is required" }).max(255, {
message: "SMTP host must be 255 characters or fewer",
})
),
systemEmailPort: optionalString(
z
.union([z.number().int(), z.string().regex(/^\d+$/)])
.transform((val) => (typeof val === "string" ? Number(val) : val))
.refine(
(val) =>
val === undefined ||
(Number.isInteger(val) && val > 0 && val < 65536),
{
message: "Port must be a number between 1 and 65535",
}
)
),
systemEmailAddress: optionalString(
z.string().email({ message: "SMTP email must be valid" })
),
systemEmailPassword: optionalString(
z.string().max(255, {
message: "SMTP password must be 255 characters or fewer",
})
),
systemEmailUser: optionalString(
z.string().trim().max(255, {
message: "SMTP username must be 255 characters or fewer",
})
),
systemEmailConnectionHost: optionalString(
z.string().trim().max(255, {
message: "Connection host must be 255 characters or fewer",
})
),
systemEmailTLSServername: optionalString(
z.string().trim().max(255, {
message: "TLS server name must be 255 characters or fewer",
})
),
systemEmailSecure: z.boolean().optional(),
systemEmailPool: z.boolean().optional(),
systemEmailIgnoreTLS: z.boolean().optional(),
systemEmailRequireTLS: z.boolean().optional(),
systemEmailRejectUnauthorized: z.boolean().optional(),
checksRetentionDays: z.coerce
.number({ message: "Number required" })
.min(1, "Retention days must be at least 1")
.max(365, "Retention days cannot exceed 365 days"),
});
const statusPageUrlRegex = /^[A-Za-z0-9]+$/;
export const statusPageSchema = z.object({
name: z.string().min(1, "Status page name is required"),
description: z.string().optional(),
url: z
.string()
.min(1, "URL is required")
.regex(statusPageUrlRegex, "Invalid URL"),
isPublished: z.boolean().optional(),
monitors: z.array(z.string()),
});
export const recoverySchema = z.object({
email: z.email({ message: "Invalid email address" }).trim().toLowerCase(),
});
export const resetSchema = z
.object({
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",
});
export const profileSchema = z
.object({
firstName: z
.string()
.min(1, { message: "First Name must be at least one char" })
.optional(),
lastName: z
.string()
.min(1, { message: "Last Name must be at least one char" })
.optional(),
password: z.preprocess(
(val) => (val === "" ? undefined : val),
z
.string()
.min(6, { message: "Password must be at least 6 characters" })
.optional()
),
confirmPassword: z.preprocess(
(val) => (val === "" ? undefined : val),
z
.string()
.min(6, { message: "Confirm Password must be at least 6 characters" })
.optional()
),
})
.refine(
(data) => {
if (!data.password && !data.confirmPassword) return true;
if (!data.password || !data.confirmPassword) return false;
return data.password === data.confirmPassword;
},
{
message: "Passwords must match",
path: ["confirmPassword"],
}
);