Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c27393942e | ||
|
|
d1077a1314 | ||
|
|
22bcb74653 | ||
|
|
78f5ce180b | ||
|
|
a9e9097a1f | ||
|
|
be1ca4ac28 |
No files matched your search
@@ -27,12 +27,14 @@ export const useStatusPageForm = ({
|
|||||||
companyName: data?.companyName || "",
|
companyName: data?.companyName || "",
|
||||||
url: data?.url || generateDefaultUrl(),
|
url: data?.url || generateDefaultUrl(),
|
||||||
timezone: data?.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone,
|
timezone: data?.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||||
|
type: data?.type || ["uptime"],
|
||||||
color: data?.color || "#4169E1",
|
color: data?.color || "#4169E1",
|
||||||
monitors: data?.monitors || [],
|
monitors: data?.monitors || [],
|
||||||
isPublished: data?.isPublished ?? false,
|
isPublished: data?.isPublished ?? false,
|
||||||
showCharts: data?.showCharts ?? true,
|
showCharts: data?.showCharts ?? true,
|
||||||
showUptimePercentage: data?.showUptimePercentage ?? true,
|
showUptimePercentage: data?.showUptimePercentage ?? true,
|
||||||
showAdminLoginLink: data?.showAdminLoginLink ?? false,
|
showAdminLoginLink: data?.showAdminLoginLink ?? false,
|
||||||
|
showInfrastructure: data?.showInfrastructure ?? false,
|
||||||
customCSS: data?.customCSS || "",
|
customCSS: data?.customCSS || "",
|
||||||
logo: transformLogo(data?.logo),
|
logo: transformLogo(data?.logo),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -302,49 +302,49 @@ const CreateMonitorPage = () => {
|
|||||||
>
|
>
|
||||||
<RadioWithDescription
|
<RadioWithDescription
|
||||||
value="http"
|
value="http"
|
||||||
label={t("pages.createMonitor.form.type.optionHttp")}
|
label={t("pages.common.monitors.monitorTypes.optionHttp")}
|
||||||
description={t(
|
description={t(
|
||||||
"pages.createMonitor.form.type.optionHttpDescription"
|
"pages.createMonitor.form.type.optionHttpDescription"
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<RadioWithDescription
|
<RadioWithDescription
|
||||||
value="ping"
|
value="ping"
|
||||||
label={t("pages.createMonitor.form.type.optionPing")}
|
label={t("pages.common.monitors.monitorTypes.optionPing")}
|
||||||
description={t(
|
description={t(
|
||||||
"pages.createMonitor.form.type.optionPingDescription"
|
"pages.createMonitor.form.type.optionPingDescription"
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<RadioWithDescription
|
<RadioWithDescription
|
||||||
value="docker"
|
value="docker"
|
||||||
label={t("pages.createMonitor.form.type.optionDocker")}
|
label={t("pages.common.monitors.monitorTypes.optionDocker")}
|
||||||
description={t(
|
description={t(
|
||||||
"pages.createMonitor.form.type.optionDockerDescription"
|
"pages.createMonitor.form.type.optionDockerDescription"
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<RadioWithDescription
|
<RadioWithDescription
|
||||||
value="port"
|
value="port"
|
||||||
label={t("pages.createMonitor.form.type.optionPort")}
|
label={t("pages.common.monitors.monitorTypes.optionPort")}
|
||||||
description={t(
|
description={t(
|
||||||
"pages.createMonitor.form.type.optionPortDescription"
|
"pages.createMonitor.form.type.optionPortDescription"
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<RadioWithDescription
|
<RadioWithDescription
|
||||||
value="game"
|
value="game"
|
||||||
label={t("pages.createMonitor.form.type.optionGame")}
|
label={t("pages.common.monitors.monitorTypes.optionGame")}
|
||||||
description={t(
|
description={t(
|
||||||
"pages.createMonitor.form.type.optionGameDescription"
|
"pages.createMonitor.form.type.optionGameDescription"
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<RadioWithDescription
|
<RadioWithDescription
|
||||||
value="grpc"
|
value="grpc"
|
||||||
label={t("pages.createMonitor.form.type.optionGrpc")}
|
label={t("pages.common.monitors.monitorTypes.optionGrpc")}
|
||||||
description={t(
|
description={t(
|
||||||
"pages.createMonitor.form.type.optionGrpcDescription"
|
"pages.createMonitor.form.type.optionGrpcDescription"
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<RadioWithDescription
|
<RadioWithDescription
|
||||||
value="websocket"
|
value="websocket"
|
||||||
label={t("pages.createMonitor.form.type.optionWebSocket")}
|
label={t("pages.common.monitors.monitorTypes.optionWebSocket")}
|
||||||
description={t(
|
description={t(
|
||||||
"pages.createMonitor.form.type.optionWebSocketDescription"
|
"pages.createMonitor.form.type.optionWebSocketDescription"
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -21,14 +21,14 @@ import {
|
|||||||
|
|
||||||
import { useTheme } from "@mui/material/styles";
|
import { useTheme } from "@mui/material/styles";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { useForm, Controller } from "react-hook-form";
|
import { useForm, Controller } from "react-hook-form";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { useStatusPageForm } from "@/Hooks/useStatusPageForm";
|
import { useStatusPageForm } from "@/Hooks/useStatusPageForm";
|
||||||
import type { StatusPageFormData } from "@/Validation/statusPage";
|
import type { StatusPageFormData } from "@/Validation/statusPage";
|
||||||
import { useGet, usePost, usePut, useDelete } from "@/Hooks/UseApi";
|
import { useGet, usePost, usePut, useDelete } from "@/Hooks/UseApi";
|
||||||
import type { Monitor } from "@/Types/Monitor";
|
import type { Monitor } from "@/Types/Monitor";
|
||||||
import type { StatusPageResponse } from "@/Types/StatusPage";
|
import type { MonitorDisplayType, StatusPageResponse } from "@/Types/StatusPage";
|
||||||
import timezones from "@/Utils/timezones.json";
|
import timezones from "@/Utils/timezones.json";
|
||||||
import { useNavigate, useParams } from "react-router-dom";
|
import { useNavigate, useParams } from "react-router-dom";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
@@ -39,6 +39,22 @@ interface TimezoneOption {
|
|||||||
name: string;
|
name: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MONITOR_TYPE_KEYS: Record<string, string> = {
|
||||||
|
http: "pages.common.monitors.monitorTypes.optionHttp",
|
||||||
|
ping: "pages.common.monitors.monitorTypes.optionPing",
|
||||||
|
docker: "pages.common.monitors.monitorTypes.optionDocker",
|
||||||
|
port: "pages.common.monitors.monitorTypes.optionPort",
|
||||||
|
game: "pages.common.monitors.monitorTypes.optionGame",
|
||||||
|
grpc: "pages.common.monitors.monitorTypes.optionGrpc",
|
||||||
|
websocket: "pages.common.monitors.monitorTypes.optionWebSocket",
|
||||||
|
hardware: "pages.common.monitors.monitorTypes.optionHardware",
|
||||||
|
};
|
||||||
|
|
||||||
|
const getMonitorTypeLabel = (type: string, t: (key: string) => string): string => {
|
||||||
|
const i18nMonitorKey = MONITOR_TYPE_KEYS[type];
|
||||||
|
return i18nMonitorKey ? t(i18nMonitorKey) : type;
|
||||||
|
};
|
||||||
|
|
||||||
const CreateStatusPage = () => {
|
const CreateStatusPage = () => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -49,10 +65,12 @@ const CreateStatusPage = () => {
|
|||||||
|
|
||||||
// Fetch existing status page data when configuring
|
// Fetch existing status page data when configuring
|
||||||
const { data: statusPageData, isLoading: isLoadingStatusPage } =
|
const { data: statusPageData, isLoading: isLoadingStatusPage } =
|
||||||
useGet<StatusPageResponse>(isCreate ? null : `/status-page/${url}?type=uptime`);
|
useGet<StatusPageResponse>(
|
||||||
|
isCreate ? null : `/status-page/${url}?type=uptime&type=infrastructure`
|
||||||
|
);
|
||||||
|
|
||||||
const { data: monitorsResponse } = useGet<Monitor[]>(
|
const { data: monitorsResponse } = useGet<Monitor[]>(
|
||||||
"/monitors/team?type=http&type=ping&type=port&type=docker"
|
"/monitors/team?type=http&type=ping&type=port&type=docker&type=hardware"
|
||||||
);
|
);
|
||||||
const monitors = monitorsResponse ?? [];
|
const monitors = monitorsResponse ?? [];
|
||||||
|
|
||||||
@@ -81,6 +99,24 @@ const CreateStatusPage = () => {
|
|||||||
reset(defaults);
|
reset(defaults);
|
||||||
}, [defaults, reset]);
|
}, [defaults, reset]);
|
||||||
|
|
||||||
|
const watchedMonitorIds: string[] = form.watch("monitors") ?? [];
|
||||||
|
const computedTypes: MonitorDisplayType[] = useMemo(() => {
|
||||||
|
const selectedMonitors = (watchedMonitorIds ?? [])
|
||||||
|
.map((id) => monitors.find((m) => m.id === id))
|
||||||
|
.filter((m): m is Monitor => m !== undefined);
|
||||||
|
|
||||||
|
const typesSet = new Set<MonitorDisplayType>();
|
||||||
|
selectedMonitors.forEach((m) => {
|
||||||
|
typesSet.add(m.type === "hardware" ? "infrastructure" : "uptime");
|
||||||
|
});
|
||||||
|
|
||||||
|
return typesSet.size ? Array.from(typesSet) : ["uptime"];
|
||||||
|
}, [JSON.stringify(watchedMonitorIds), monitors]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
form.setValue("type", computedTypes);
|
||||||
|
}, [computedTypes]);
|
||||||
|
|
||||||
const onError = (errors: any) => {
|
const onError = (errors: any) => {
|
||||||
logger.debug("Status page validation errors", errors);
|
logger.debug("Status page validation errors", errors);
|
||||||
};
|
};
|
||||||
@@ -103,7 +139,6 @@ const CreateStatusPage = () => {
|
|||||||
|
|
||||||
const onSubmit = async (data: StatusPageFormData) => {
|
const onSubmit = async (data: StatusPageFormData) => {
|
||||||
const fd = new FormData();
|
const fd = new FormData();
|
||||||
fd.append("type", "uptime");
|
|
||||||
fd.append("isPublished", String(data.isPublished));
|
fd.append("isPublished", String(data.isPublished));
|
||||||
if (data.companyName) fd.append("companyName", data.companyName);
|
if (data.companyName) fd.append("companyName", data.companyName);
|
||||||
if (data.url) fd.append("url", data.url);
|
if (data.url) fd.append("url", data.url);
|
||||||
@@ -112,11 +147,16 @@ const CreateStatusPage = () => {
|
|||||||
fd.append("showCharts", String(data.showCharts));
|
fd.append("showCharts", String(data.showCharts));
|
||||||
fd.append("showUptimePercentage", String(data.showUptimePercentage));
|
fd.append("showUptimePercentage", String(data.showUptimePercentage));
|
||||||
fd.append("showAdminLoginLink", String(data.showAdminLoginLink));
|
fd.append("showAdminLoginLink", String(data.showAdminLoginLink));
|
||||||
|
fd.append("showInfrastructure", String(data.showInfrastructure));
|
||||||
|
|
||||||
data.monitors.forEach((monitorId) => {
|
data.monitors.forEach((monitorId) => {
|
||||||
fd.append("monitors[]", monitorId);
|
fd.append("monitors[]", monitorId);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
data.type.forEach((type) => {
|
||||||
|
fd.append("type[]", type);
|
||||||
|
});
|
||||||
|
|
||||||
// Handle logo upload
|
// Handle logo upload
|
||||||
if (data.logo === null) {
|
if (data.logo === null) {
|
||||||
// Signal to remove the logo
|
// Signal to remove the logo
|
||||||
@@ -303,7 +343,9 @@ const CreateStatusPage = () => {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<GripVertical size={20} />
|
<GripVertical size={20} />
|
||||||
<Typography flexGrow={1}>{monitor.name}</Typography>
|
<Typography
|
||||||
|
flexGrow={1}
|
||||||
|
>{`${monitor.name} (${getMonitorTypeLabel(monitor.type, t)})`}</Typography>
|
||||||
<IconButton
|
<IconButton
|
||||||
size="small"
|
size="small"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -425,6 +467,23 @@ const CreateStatusPage = () => {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
<Controller
|
||||||
|
name="showInfrastructure"
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormControlLabel
|
||||||
|
control={
|
||||||
|
<Checkbox
|
||||||
|
checked={field.value}
|
||||||
|
onChange={field.onChange}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
label={t(
|
||||||
|
"pages.statusPages.form.features.option.showInfrastructure.label"
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
{/* <Controller
|
{/* <Controller
|
||||||
name="showUptimePercentage"
|
name="showUptimePercentage"
|
||||||
control={control}
|
control={control}
|
||||||
|
|||||||
@@ -0,0 +1,246 @@
|
|||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import Typography from "@mui/material/Typography";
|
||||||
|
import { Gauge } from "@/Components/design-elements";
|
||||||
|
import { useTheme } from "@mui/material/styles";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import prettyBytes from "pretty-bytes";
|
||||||
|
import type { Monitor } from "@/Types/Monitor";
|
||||||
|
import Grid from "@mui/material/Grid";
|
||||||
|
import useMediaQuery from "@mui/material/useMediaQuery";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import { LAYOUT, SPACING } from "@/Utils/Theme/constants";
|
||||||
|
|
||||||
|
const GAUGE_RADIUS = 60;
|
||||||
|
const GAUGE_STROKE_WIDTH = 12;
|
||||||
|
const PERCENTAGE_MULTIPLIER = 100;
|
||||||
|
|
||||||
|
interface StatusPageMonitor extends Monitor {
|
||||||
|
checks?: Monitor["recentChecks"];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MetricDetail {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MetricConfig {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
hasData: boolean;
|
||||||
|
progress: number;
|
||||||
|
details: MetricDetail[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const MetricDetailRow = ({ label, value }: MetricDetail) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
return (
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
justifyContent="space-between"
|
||||||
|
>
|
||||||
|
<Typography
|
||||||
|
variant="body2"
|
||||||
|
color={theme.palette.text.secondary}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2">{value}</Typography>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
interface MetricItemProps {
|
||||||
|
label: string;
|
||||||
|
progress: number;
|
||||||
|
details?: MetricDetail[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const MetricItem = ({ label, progress, details }: MetricItemProps) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
|
||||||
|
return (
|
||||||
|
<Grid
|
||||||
|
size={isSmall ? 12 : 4}
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
alignItems: "center",
|
||||||
|
textAlign: "center",
|
||||||
|
gap: theme.spacing(SPACING.LG),
|
||||||
|
padding: theme.spacing(LAYOUT.XS),
|
||||||
|
borderRight: isSmall ? "none" : `1px solid ${theme.palette.divider}`,
|
||||||
|
borderBottom: isSmall ? `1px solid ${theme.palette.divider}` : "none",
|
||||||
|
"&:last-child": {
|
||||||
|
borderRight: "none",
|
||||||
|
borderBottom: "none",
|
||||||
|
paddingBottom: theme.spacing(SPACING.LG),
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box
|
||||||
|
display="flex"
|
||||||
|
flexDirection="column"
|
||||||
|
alignItems="center"
|
||||||
|
>
|
||||||
|
<Gauge
|
||||||
|
progress={progress}
|
||||||
|
radius={GAUGE_RADIUS}
|
||||||
|
strokeWidth={GAUGE_STROKE_WIDTH}
|
||||||
|
/>
|
||||||
|
<Typography variant="body2">{label}</Typography>
|
||||||
|
</Box>
|
||||||
|
{details && details.length > 0 && (
|
||||||
|
<Box
|
||||||
|
width="100%"
|
||||||
|
paddingX={theme.spacing(LAYOUT.LG)}
|
||||||
|
>
|
||||||
|
{details.map((detail) => (
|
||||||
|
<MetricDetailRow
|
||||||
|
key={detail.label}
|
||||||
|
label={detail.label}
|
||||||
|
value={detail.value}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Grid>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
type LatestCheck = NonNullable<Monitor["recentChecks"]>[number];
|
||||||
|
|
||||||
|
const buildCpuMetric = (
|
||||||
|
check: LatestCheck,
|
||||||
|
t: (key: string) => string
|
||||||
|
): MetricConfig | null => {
|
||||||
|
if (!check.cpu || typeof check.cpu.usage_percent !== "number") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const usagePercent = (check.cpu.usage_percent ?? 0) * PERCENTAGE_MULTIPLIER;
|
||||||
|
return {
|
||||||
|
key: "cpu",
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.cpu"),
|
||||||
|
hasData: true,
|
||||||
|
progress: usagePercent,
|
||||||
|
details: [
|
||||||
|
{
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.usage"),
|
||||||
|
value: `${usagePercent.toFixed(2)}%`,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildMemoryMetric = (
|
||||||
|
check: LatestCheck,
|
||||||
|
t: (key: string) => string
|
||||||
|
): MetricConfig | null => {
|
||||||
|
if (
|
||||||
|
!check.memory ||
|
||||||
|
typeof check.memory.usage_percent !== "number" ||
|
||||||
|
typeof check.memory.used_bytes !== "number" ||
|
||||||
|
typeof check.memory.total_bytes !== "number"
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
key: "memory",
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.memory"),
|
||||||
|
hasData: true,
|
||||||
|
progress: (check.memory.usage_percent ?? 0) * PERCENTAGE_MULTIPLIER,
|
||||||
|
details: [
|
||||||
|
{
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.used"),
|
||||||
|
value: prettyBytes(check.memory.used_bytes ?? 0),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.total"),
|
||||||
|
value: prettyBytes(check.memory.total_bytes ?? 0),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildDiskMetric = (
|
||||||
|
check: LatestCheck,
|
||||||
|
t: (key: string) => string
|
||||||
|
): MetricConfig | null => {
|
||||||
|
if (!check.disk || check.disk.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const disks = check.disk;
|
||||||
|
const avgUsagePercent =
|
||||||
|
(disks.reduce((acc, disk) => acc + (disk?.usage_percent ?? 0), 0) / disks.length) *
|
||||||
|
PERCENTAGE_MULTIPLIER;
|
||||||
|
const totalUsedBytes = disks.reduce((acc, disk) => acc + (disk?.used_bytes ?? 0), 0);
|
||||||
|
const totalTotalBytes = disks.reduce((acc, disk) => acc + (disk?.total_bytes ?? 0), 0);
|
||||||
|
|
||||||
|
return {
|
||||||
|
key: "disk",
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.disk"),
|
||||||
|
hasData: true,
|
||||||
|
progress: avgUsagePercent,
|
||||||
|
details: [
|
||||||
|
{
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.used"),
|
||||||
|
value: prettyBytes(totalUsedBytes),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.total"),
|
||||||
|
value: prettyBytes(totalTotalBytes),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const InfrastructureMetrics = ({ monitor }: { monitor: StatusPageMonitor }) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
const latestCheck = monitor.recentChecks?.[0] ?? monitor.checks?.[0];
|
||||||
|
|
||||||
|
if (!latestCheck) {
|
||||||
|
return (
|
||||||
|
<Typography
|
||||||
|
variant="body2"
|
||||||
|
color={theme.palette.text.secondary}
|
||||||
|
>
|
||||||
|
{t("pages.statusPages.monitorsList.noData")}
|
||||||
|
</Typography>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const metrics: MetricConfig[] = [
|
||||||
|
buildCpuMetric(latestCheck, t),
|
||||||
|
buildMemoryMetric(latestCheck, t),
|
||||||
|
buildDiskMetric(latestCheck, t),
|
||||||
|
].filter((m): m is MetricConfig => m !== null);
|
||||||
|
|
||||||
|
if (metrics.length === 0) {
|
||||||
|
return (
|
||||||
|
<Typography
|
||||||
|
variant="body2"
|
||||||
|
color={theme.palette.text.secondary}
|
||||||
|
>
|
||||||
|
{t("pages.statusPages.monitorsList.noData")}
|
||||||
|
</Typography>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Grid
|
||||||
|
container
|
||||||
|
alignItems="center"
|
||||||
|
padding={theme.spacing(LAYOUT.XS)}
|
||||||
|
>
|
||||||
|
{metrics.map(({ key, label, progress, details }) => (
|
||||||
|
<MetricItem
|
||||||
|
key={key}
|
||||||
|
label={label}
|
||||||
|
progress={progress}
|
||||||
|
details={details}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Grid>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -5,13 +5,15 @@ import Typography from "@mui/material/Typography";
|
|||||||
import { HistogramResponseTime, HeatmapResponseTime } from "@/Components/common";
|
import { HistogramResponseTime, HeatmapResponseTime } from "@/Components/common";
|
||||||
import { StatusLabel, BaseBox } from "@/Components/design-elements";
|
import { StatusLabel, BaseBox } from "@/Components/design-elements";
|
||||||
import { SwitchComponent } from "@/Components/inputs";
|
import { SwitchComponent } from "@/Components/inputs";
|
||||||
|
import { InfrastructureMetrics } from "@/Pages/StatusPage/Status/Components/InfrastructureMetrics";
|
||||||
|
|
||||||
import { useTheme } from "@mui/material/styles";
|
import { useTheme, type Theme } from "@mui/material/styles";
|
||||||
import { useSelector } from "react-redux";
|
import { useSelector } from "react-redux";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import type { Monitor } from "@/Types/Monitor";
|
import type { Monitor } from "@/Types/Monitor";
|
||||||
import type { StatusPage } from "@/Types/StatusPage";
|
import type { StatusPage } from "@/Types/StatusPage";
|
||||||
import type { RootState } from "@/Types/state";
|
import type { RootState } from "@/Types/state";
|
||||||
|
import { LAYOUT, SPACING } from "@/Utils/Theme/constants";
|
||||||
|
|
||||||
interface StatusPageMonitor extends Monitor {
|
interface StatusPageMonitor extends Monitor {
|
||||||
checks?: Monitor["recentChecks"];
|
checks?: Monitor["recentChecks"];
|
||||||
@@ -22,6 +24,87 @@ interface MonitorsListProps {
|
|||||||
monitors: StatusPageMonitor[];
|
monitors: StatusPageMonitor[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const getMonitorBadgeStyles = (monitorType: string, theme: Theme) => {
|
||||||
|
// for future: specific badge styles can be defined here based on monitor type
|
||||||
|
const badgeConfig: Record<string, { color: string; bg: string }> = {
|
||||||
|
hardware: {
|
||||||
|
color: theme.palette.background.paper,
|
||||||
|
bg: theme.palette.info.light,
|
||||||
|
},
|
||||||
|
http: {
|
||||||
|
color: theme.palette.background.paper,
|
||||||
|
bg: theme.palette.success.light,
|
||||||
|
},
|
||||||
|
ping: {
|
||||||
|
color: theme.palette.background.paper,
|
||||||
|
bg: theme.palette.success.light,
|
||||||
|
},
|
||||||
|
port: {
|
||||||
|
color: theme.palette.background.paper,
|
||||||
|
bg: theme.palette.success.light,
|
||||||
|
},
|
||||||
|
docker: {
|
||||||
|
color: theme.palette.background.paper,
|
||||||
|
bg: theme.palette.success.light,
|
||||||
|
},
|
||||||
|
pagespeed: {
|
||||||
|
color: theme.palette.background.paper,
|
||||||
|
bg: theme.palette.success.light,
|
||||||
|
},
|
||||||
|
game: {
|
||||||
|
color: theme.palette.background.paper,
|
||||||
|
bg: theme.palette.success.light,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const config = badgeConfig[monitorType] ?? badgeConfig.http;
|
||||||
|
return {
|
||||||
|
backgroundColor: config.bg,
|
||||||
|
color: config.color,
|
||||||
|
padding: `${theme.spacing(SPACING.SM)} ${theme.spacing(SPACING.LG)}`,
|
||||||
|
borderRadius: theme.shape.borderRadius,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Extracted component for monitor content below the header row
|
||||||
|
const MonitorContent = ({
|
||||||
|
monitor,
|
||||||
|
statusPage,
|
||||||
|
chartType,
|
||||||
|
}: {
|
||||||
|
monitor: Monitor & { checks?: Monitor["recentChecks"] };
|
||||||
|
statusPage: StatusPage;
|
||||||
|
chartType: string;
|
||||||
|
}) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
const isInfrastructureMonitor = monitor?.type === "hardware";
|
||||||
|
|
||||||
|
if (isInfrastructureMonitor) {
|
||||||
|
if (statusPage.showInfrastructure === false) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return <InfrastructureMetrics monitor={monitor} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (statusPage.showCharts === false) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box sx={{ overflow: "hidden", minWidth: 0, flex: 1, mb: theme.spacing(SPACING.LG) }}>
|
||||||
|
{chartType === "histogram" ? (
|
||||||
|
<HistogramResponseTime
|
||||||
|
height={{ xs: 50, md: 100 }}
|
||||||
|
gap={{ xs: theme.spacing(SPACING.SM), md: theme.spacing(LAYOUT.SM) }}
|
||||||
|
checks={monitor?.checks?.slice().reverse() ?? []}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<HeatmapResponseTime checks={monitor?.checks?.slice().reverse() ?? []} />
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
export const MonitorsList = ({ statusPage, monitors }: MonitorsListProps) => {
|
export const MonitorsList = ({ statusPage, monitors }: MonitorsListProps) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -31,11 +114,12 @@ export const MonitorsList = ({ statusPage, monitors }: MonitorsListProps) => {
|
|||||||
const [chartType, setChartType] = useState<"histogram" | "heatmap">("histogram");
|
const [chartType, setChartType] = useState<"histogram" | "heatmap">("histogram");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap={theme.spacing(8)}>
|
<Stack gap={theme.spacing(LAYOUT.MD)}>
|
||||||
{statusPage.showCharts !== false && (
|
{statusPage.showCharts && (
|
||||||
<Stack
|
<Stack
|
||||||
direction={"row"}
|
direction={"row"}
|
||||||
alignItems={"center"}
|
alignItems={"center"}
|
||||||
|
gap={theme.spacing(LAYOUT.SM)}
|
||||||
>
|
>
|
||||||
<Typography>{t("pages.statusPages.monitorsList.chartTypeHeatmap")}</Typography>
|
<Typography>{t("pages.statusPages.monitorsList.chartTypeHeatmap")}</Typography>
|
||||||
<SwitchComponent
|
<SwitchComponent
|
||||||
@@ -56,52 +140,62 @@ export const MonitorsList = ({ statusPage, monitors }: MonitorsListProps) => {
|
|||||||
return (
|
return (
|
||||||
<BaseBox
|
<BaseBox
|
||||||
key={monitor.id}
|
key={monitor.id}
|
||||||
padding={theme.spacing(4)}
|
padding={theme.spacing(LAYOUT.MD)}
|
||||||
>
|
>
|
||||||
<Stack
|
<Stack
|
||||||
direction="row"
|
direction="row"
|
||||||
alignItems="center"
|
alignItems="center"
|
||||||
justifyContent="space-between"
|
justifyContent="space-between"
|
||||||
gap={theme.spacing(4)}
|
gap={theme.spacing(LAYOUT.XS)}
|
||||||
mb={statusPage.showCharts !== false ? theme.spacing(4) : 0}
|
mb={theme.spacing(LAYOUT.XS)}
|
||||||
>
|
>
|
||||||
<Box sx={{ overflow: "hidden", minWidth: 0, flex: 1 }}>
|
<Box sx={{ overflow: "hidden", minWidth: 0, flex: 1 }}>
|
||||||
<Typography
|
<Stack
|
||||||
variant="h6"
|
direction="row"
|
||||||
sx={{
|
alignItems="center"
|
||||||
overflow: "hidden",
|
gap={theme.spacing(SPACING.LG)}
|
||||||
textOverflow: "ellipsis",
|
mb={theme.spacing(SPACING.SM)}
|
||||||
whiteSpace: "nowrap",
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
{monitor.name}
|
<Typography
|
||||||
</Typography>
|
variant="h6"
|
||||||
{showURL && (
|
sx={{
|
||||||
|
overflow: "hidden",
|
||||||
|
textOverflow: "ellipsis",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{monitor.name}
|
||||||
|
</Typography>
|
||||||
|
<Typography
|
||||||
|
variant="caption"
|
||||||
|
sx={getMonitorBadgeStyles(monitor?.type ?? "", theme)}
|
||||||
|
>
|
||||||
|
{t(
|
||||||
|
`pages.common.monitors.monitorTypes.option${monitor?.type.charAt(0).toUpperCase() + monitor?.type.slice(1)}`
|
||||||
|
)}
|
||||||
|
</Typography>
|
||||||
|
</Stack>
|
||||||
|
{showURL && monitor?.url && (
|
||||||
<Typography
|
<Typography
|
||||||
variant="body2"
|
variant="body2"
|
||||||
color="text.secondary"
|
color={theme.palette.text.secondary}
|
||||||
|
sx={{
|
||||||
|
overflow: "hidden",
|
||||||
|
textOverflow: "ellipsis",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{monitor.url}
|
{monitor.url}
|
||||||
</Typography>
|
</Typography>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
<StatusLabel status={monitor.status} />
|
<StatusLabel status={monitor?.status} />
|
||||||
</Stack>
|
</Stack>
|
||||||
{statusPage.showCharts !== false && (
|
<MonitorContent
|
||||||
<Box sx={{ overflow: "hidden", minWidth: 0, flex: 1 }}>
|
monitor={monitor}
|
||||||
{chartType === "histogram" ? (
|
statusPage={statusPage}
|
||||||
<HistogramResponseTime
|
chartType={chartType}
|
||||||
height={{ xs: 50, md: 100 }}
|
/>
|
||||||
gap={{ xs: theme.spacing(0.5), md: theme.spacing(5) }}
|
|
||||||
checks={monitor?.checks?.slice().reverse() ?? []}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<HeatmapResponseTime
|
|
||||||
checks={monitor?.checks?.slice().reverse() ?? []}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</BaseBox>
|
</BaseBox>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -23,16 +23,17 @@ const StatusPageView = () => {
|
|||||||
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
|
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
|
||||||
const isPublic = location.pathname.startsWith("/status/public");
|
const isPublic = location.pathname.startsWith("/status/public");
|
||||||
|
|
||||||
const apiUrl = url ? `/status-page/${url}?type=uptime` : null;
|
const apiUrl = url ? `/status-page/${url}?type=uptime&type=infrastructure` : null;
|
||||||
|
|
||||||
const { data, isLoading, error } = useGet<StatusPageResponse>(apiUrl);
|
const { data, isLoading, error } = useGet<StatusPageResponse>(apiUrl);
|
||||||
|
|
||||||
const statusPage = data?.statusPage;
|
const statusPage = data?.statusPage;
|
||||||
const monitors = data?.monitors ?? [];
|
const monitors = data?.monitors ?? [];
|
||||||
|
const infrastructureMonitors = data?.infrastructureMonitors ?? [];
|
||||||
|
|
||||||
if (!statusPage) return null;
|
if (!statusPage) return null;
|
||||||
|
|
||||||
if (monitors?.length === 0) {
|
if (monitors?.length === 0 && infrastructureMonitors?.length === 0) {
|
||||||
return (
|
return (
|
||||||
<BasePage
|
<BasePage
|
||||||
loading={isLoading}
|
loading={isLoading}
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ export const StatusPagesTable = ({
|
|||||||
{
|
{
|
||||||
id: "type",
|
id: "type",
|
||||||
content: t("common.table.headers.type"),
|
content: t("common.table.headers.type"),
|
||||||
render: (row) => row.type,
|
render: (row) => row.type.join(", "),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "status",
|
id: "status",
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import type { Monitor } from "@/Types/Monitor";
|
import type { Monitor } from "@/Types/Monitor";
|
||||||
|
export type MonitorDisplayType = "uptime" | "infrastructure";
|
||||||
|
|
||||||
export interface StatusPage {
|
export interface StatusPage {
|
||||||
id: string;
|
id: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
teamId: string;
|
teamId: string;
|
||||||
type: string;
|
type: MonitorDisplayType[];
|
||||||
companyName: string;
|
companyName: string;
|
||||||
url: string;
|
url: string;
|
||||||
timezone?: string;
|
timezone?: string;
|
||||||
@@ -20,6 +21,7 @@ export interface StatusPage {
|
|||||||
showCharts: boolean;
|
showCharts: boolean;
|
||||||
showUptimePercentage: boolean;
|
showUptimePercentage: boolean;
|
||||||
showAdminLoginLink: boolean;
|
showAdminLoginLink: boolean;
|
||||||
|
showInfrastructure: boolean;
|
||||||
customCSS: string;
|
customCSS: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
@@ -28,4 +30,5 @@ export interface StatusPage {
|
|||||||
export interface StatusPageResponse {
|
export interface StatusPageResponse {
|
||||||
statusPage: StatusPage;
|
statusPage: StatusPage;
|
||||||
monitors: Monitor[];
|
monitors: Monitor[];
|
||||||
|
infrastructureMonitors?: Monitor[];
|
||||||
}
|
}
|
||||||
@@ -14,12 +14,16 @@ export const statusPageSchema = z.object({
|
|||||||
"URL can only contain lowercase letters, numbers, and hyphens"
|
"URL can only contain lowercase letters, numbers, and hyphens"
|
||||||
),
|
),
|
||||||
timezone: z.string().optional(),
|
timezone: z.string().optional(),
|
||||||
|
type: z
|
||||||
|
.array(z.enum(["uptime", "infrastructure"]))
|
||||||
|
.min(1, "At least one type is required"),
|
||||||
color: z.string().min(1, "Color is required"),
|
color: z.string().min(1, "Color is required"),
|
||||||
monitors: z.array(z.string()).min(1, "At least one monitor is required"),
|
monitors: z.array(z.string()).min(1, "At least one monitor is required"),
|
||||||
isPublished: z.boolean(),
|
isPublished: z.boolean(),
|
||||||
showCharts: z.boolean(),
|
showCharts: z.boolean(),
|
||||||
showUptimePercentage: z.boolean(),
|
showUptimePercentage: z.boolean(),
|
||||||
showAdminLoginLink: z.boolean(),
|
showAdminLoginLink: z.boolean(),
|
||||||
|
showInfrastructure: z.boolean(),
|
||||||
customCSS: z.string().optional(),
|
customCSS: z.string().optional(),
|
||||||
logo: z
|
logo: z
|
||||||
.object({
|
.object({
|
||||||
|
|||||||
@@ -288,7 +288,13 @@ const logoImageValidation = joi
|
|||||||
.optional(); // Make entire object optional
|
.optional(); // Make entire object optional
|
||||||
|
|
||||||
const statusPageValidation = joi.object({
|
const statusPageValidation = joi.object({
|
||||||
type: joi.string().valid("uptime").required(),
|
type: joi
|
||||||
|
.alternatives()
|
||||||
|
.try(
|
||||||
|
joi.string().valid("uptime", "infrastructure"),
|
||||||
|
joi.array().items(joi.string().valid("uptime", "infrastructure"))
|
||||||
|
)
|
||||||
|
.required(),
|
||||||
isPublished: joi.bool(),
|
isPublished: joi.bool(),
|
||||||
companyName: joi
|
companyName: joi
|
||||||
.string()
|
.string()
|
||||||
@@ -317,6 +323,7 @@ const statusPageValidation = joi.object({
|
|||||||
showUptimePercentage: joi.boolean(),
|
showUptimePercentage: joi.boolean(),
|
||||||
showCharts: joi.boolean(),
|
showCharts: joi.boolean(),
|
||||||
showAdminLoginLink: joi.boolean(),
|
showAdminLoginLink: joi.boolean(),
|
||||||
|
showInfrastructure: joi.boolean(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const settingsValidation = joi.object({
|
const settingsValidation = joi.object({
|
||||||
|
|||||||
@@ -407,6 +407,17 @@
|
|||||||
"paused": "paused",
|
"paused": "paused",
|
||||||
"total": "total",
|
"total": "total",
|
||||||
"up": "up"
|
"up": "up"
|
||||||
|
},
|
||||||
|
"monitorTypes": {
|
||||||
|
"optionDocker": "Docker",
|
||||||
|
"optionGame": "Game",
|
||||||
|
"optionHttp": "HTTP(S)",
|
||||||
|
"optionPing": "Ping",
|
||||||
|
"optionPort": "Port",
|
||||||
|
"optionPagespeed": "PageSpeed",
|
||||||
|
"optionHardware": "Infrastructure",
|
||||||
|
"optionGrpc": "gRPC",
|
||||||
|
"optionWebSocket": "WebSocket"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -534,19 +545,12 @@
|
|||||||
},
|
},
|
||||||
"type": {
|
"type": {
|
||||||
"description": "Select the type of check to perform",
|
"description": "Select the type of check to perform",
|
||||||
"optionDocker": "Docker",
|
|
||||||
"optionDockerDescription": "Use Docker to monitor if a container is running.",
|
"optionDockerDescription": "Use Docker to monitor if a container is running.",
|
||||||
"optionGame": "Game",
|
|
||||||
"optionGameDescription": "Monitor if a specific game server is online.",
|
"optionGameDescription": "Monitor if a specific game server is online.",
|
||||||
"optionGrpc": "gRPC",
|
|
||||||
"optionGrpcDescription": "Monitor gRPC services using the standard Health Checking Protocol.",
|
"optionGrpcDescription": "Monitor gRPC services using the standard Health Checking Protocol.",
|
||||||
"optionWebSocket": "WebSocket",
|
|
||||||
"optionWebSocketDescription": "Monitor WebSocket endpoints for connection health and response time.",
|
"optionWebSocketDescription": "Monitor WebSocket endpoints for connection health and response time.",
|
||||||
"optionHttp": "HTTP(S)",
|
|
||||||
"optionHttpDescription": "Use HTTP(S) to monitor your website or API endpoint.",
|
"optionHttpDescription": "Use HTTP(S) to monitor your website or API endpoint.",
|
||||||
"optionPing": "Ping",
|
|
||||||
"optionPingDescription": "Use ICMP Ping to monitor if a server is online.",
|
"optionPingDescription": "Use ICMP Ping to monitor if a server is online.",
|
||||||
"optionPort": "Port",
|
|
||||||
"optionPortDescription": "Monitor if a specific port on a server is open.",
|
"optionPortDescription": "Monitor if a specific port on a server is open.",
|
||||||
"title": "Type"
|
"title": "Type"
|
||||||
},
|
},
|
||||||
@@ -1178,7 +1182,22 @@
|
|||||||
},
|
},
|
||||||
"monitorsList": {
|
"monitorsList": {
|
||||||
"chartTypeHeatmap": "Heatmap",
|
"chartTypeHeatmap": "Heatmap",
|
||||||
"chartTypeHistogram": "Histogram"
|
"chartTypeHistogram": "Histogram",
|
||||||
|
"noData": "No data available",
|
||||||
|
"infrastructure": {
|
||||||
|
"title": "Infrastructure",
|
||||||
|
"cpu": "CPU",
|
||||||
|
"memory": "RAM",
|
||||||
|
"memoryText": "Memory",
|
||||||
|
"disk": "Disk",
|
||||||
|
"usage": "Usage",
|
||||||
|
"used": "Used",
|
||||||
|
"total": "Total"
|
||||||
|
},
|
||||||
|
"uptime": {
|
||||||
|
"title": "Uptime",
|
||||||
|
"responseTime": "Response time"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"statusBar": {
|
"statusBar": {
|
||||||
"allDown": "All systems are down",
|
"allDown": "All systems are down",
|
||||||
@@ -1270,6 +1289,9 @@
|
|||||||
},
|
},
|
||||||
"showAdminLoginLink": {
|
"showAdminLoginLink": {
|
||||||
"label": "Show admin login link"
|
"label": "Show admin login link"
|
||||||
|
},
|
||||||
|
"showInfrastructure": {
|
||||||
|
"label": "Show infrastructure metrics"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { Monitor, type MonitorType, MonitorTypes, UserRole } from "@/types/index
|
|||||||
import sslChecker, { SSLDetails } from "ssl-checker";
|
import sslChecker, { SSLDetails } from "ssl-checker";
|
||||||
type SSLCheckerType = typeof sslChecker;
|
type SSLCheckerType = typeof sslChecker;
|
||||||
|
|
||||||
export const fetchMonitorCertificate = async (checker: SSLCheckerType, monitor: Monitor): Promise<SSLDetails> => {
|
const fetchMonitorCertificate = async (checker: SSLCheckerType, monitor: Monitor): Promise<SSLDetails> => {
|
||||||
const monitorUrl = new URL(monitor.url);
|
const monitorUrl = new URL(monitor.url);
|
||||||
const hostname = monitorUrl.hostname;
|
const hostname = monitorUrl.hostname;
|
||||||
const cert = await checker(hostname);
|
const cert = await checker(hostname);
|
||||||
@@ -12,14 +12,14 @@ export const fetchMonitorCertificate = async (checker: SSLCheckerType, monitor:
|
|||||||
}
|
}
|
||||||
return cert;
|
return cert;
|
||||||
};
|
};
|
||||||
export const requireString = (value: unknown, fieldName: string): string => {
|
const requireString = (value: unknown, fieldName: string): string => {
|
||||||
if (typeof value === "string" && value.trim().length > 0) {
|
if (typeof value === "string" && value.trim().length > 0) {
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
throw new AppError({ message: `${fieldName} is required`, status: 400 });
|
throw new AppError({ message: `${fieldName} is required`, status: 400 });
|
||||||
};
|
};
|
||||||
|
|
||||||
export const optionalString = (value: unknown, fieldName: string): string | undefined => {
|
const optionalString = (value: unknown, fieldName: string): string | undefined => {
|
||||||
if (value === undefined) {
|
if (value === undefined) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
@@ -29,7 +29,7 @@ export const optionalString = (value: unknown, fieldName: string): string | unde
|
|||||||
throw new AppError({ message: `${fieldName} must be a string`, status: 400 });
|
throw new AppError({ message: `${fieldName} must be a string`, status: 400 });
|
||||||
};
|
};
|
||||||
|
|
||||||
export const optionalNumber = (value: unknown, fieldName: string): number | undefined => {
|
const optionalNumber = (value: unknown, fieldName: string): number | undefined => {
|
||||||
if (value === undefined) {
|
if (value === undefined) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
@@ -45,7 +45,7 @@ export const optionalNumber = (value: unknown, fieldName: string): number | unde
|
|||||||
throw new AppError({ message: `${fieldName} must be a number`, status: 400 });
|
throw new AppError({ message: `${fieldName} must be a number`, status: 400 });
|
||||||
};
|
};
|
||||||
|
|
||||||
export const optionalBoolean = (value: unknown, fieldName: string): boolean | undefined => {
|
const optionalBoolean = (value: unknown, fieldName: string): boolean | undefined => {
|
||||||
if (value === undefined) {
|
if (value === undefined) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
@@ -63,7 +63,7 @@ export const optionalBoolean = (value: unknown, fieldName: string): boolean | un
|
|||||||
throw new AppError({ message: `${fieldName} must be a boolean`, status: 400 });
|
throw new AppError({ message: `${fieldName} must be a boolean`, status: 400 });
|
||||||
};
|
};
|
||||||
|
|
||||||
export const parseMonitorTypeFilter = (value: unknown): MonitorType | MonitorType[] | undefined => {
|
const parseMonitorTypeFilter = (value: unknown): MonitorType | MonitorType[] | undefined => {
|
||||||
const parseSingle = (input: unknown): MonitorType => {
|
const parseSingle = (input: unknown): MonitorType => {
|
||||||
if (typeof input !== "string") {
|
if (typeof input !== "string") {
|
||||||
throw new AppError({ message: "Monitor type must be a string", status: 400 });
|
throw new AppError({ message: "Monitor type must be a string", status: 400 });
|
||||||
@@ -83,7 +83,7 @@ export const parseMonitorTypeFilter = (value: unknown): MonitorType | MonitorTyp
|
|||||||
return parseSingle(value);
|
return parseSingle(value);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const parseSortOrder = (value: unknown): "asc" | "desc" | undefined => {
|
const parseSortOrder = (value: unknown): "asc" | "desc" | undefined => {
|
||||||
if (value === undefined) {
|
if (value === undefined) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
@@ -93,36 +93,42 @@ export const parseSortOrder = (value: unknown): "asc" | "desc" | undefined => {
|
|||||||
throw new AppError({ message: "order must be either 'asc' or 'desc'", status: 400 });
|
throw new AppError({ message: "order must be either 'asc' or 'desc'", status: 400 });
|
||||||
};
|
};
|
||||||
|
|
||||||
export const requireTeamId = (teamId?: string): string => {
|
const requireTeamId = (teamId?: string): string => {
|
||||||
if (!teamId) {
|
if (!teamId) {
|
||||||
throw new AppError({ message: "Team ID is required", status: 400 });
|
throw new AppError({ message: "Team ID is required", status: 400 });
|
||||||
}
|
}
|
||||||
return teamId;
|
return teamId;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const requireUserId = (userId?: string): string => {
|
const requireUserId = (userId?: string): string => {
|
||||||
if (!userId) {
|
if (!userId) {
|
||||||
throw new AppError({ message: "User ID is required", status: 400 });
|
throw new AppError({ message: "User ID is required", status: 400 });
|
||||||
}
|
}
|
||||||
return userId;
|
return userId;
|
||||||
};
|
};
|
||||||
export const requireUserEmail = (userEmail?: string): string => {
|
const requireUserEmail = (userEmail?: string): string => {
|
||||||
if (!userEmail) {
|
if (!userEmail) {
|
||||||
throw new AppError({ message: "User email is required", status: 400 });
|
throw new AppError({ message: "User email is required", status: 400 });
|
||||||
}
|
}
|
||||||
return userEmail;
|
return userEmail;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const requireFirstName = (firstName?: string): string => {
|
|
||||||
if (!firstName) {
|
|
||||||
throw new AppError({ message: "First name is required", status: 400 });
|
|
||||||
}
|
|
||||||
return firstName;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const requireUserRoles = (userRoles?: UserRole[]): UserRole[] => {
|
export const requireUserRoles = (userRoles?: UserRole[]): UserRole[] => {
|
||||||
if (!userRoles || userRoles.length === 0) {
|
if (!userRoles || userRoles.length === 0) {
|
||||||
throw new AppError({ message: "User roles are required", status: 400 });
|
throw new AppError({ message: "User roles are required", status: 400 });
|
||||||
}
|
}
|
||||||
return userRoles;
|
return userRoles;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export {
|
||||||
|
fetchMonitorCertificate,
|
||||||
|
requireString,
|
||||||
|
optionalString,
|
||||||
|
optionalNumber,
|
||||||
|
optionalBoolean,
|
||||||
|
parseMonitorTypeFilter,
|
||||||
|
parseSortOrder,
|
||||||
|
requireTeamId,
|
||||||
|
requireUserId,
|
||||||
|
requireUserEmail,
|
||||||
|
};
|
||||||
@@ -1,30 +1,35 @@
|
|||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { requireTeamId, requireUserId, requireUserEmail } from "./controllerUtils.js";
|
import { requireTeamId, requireUserId, requireUserEmail } from "./controllerUtils.js";
|
||||||
import { IIncidentService } from "@/service/index.js";
|
|
||||||
import { getIncidentsByTeamQueryValidation, getIncidentSummaryQueryValidation } from "@/validation/incidentValidation.js";
|
|
||||||
|
|
||||||
const SERVICE_NAME = "IncidentController";
|
const SERVICE_NAME = "incidentController";
|
||||||
|
|
||||||
class IncidentController {
|
class IncidentController {
|
||||||
private incidentService: IIncidentService;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
constructor(incidentService: IIncidentService) {
|
|
||||||
|
private incidentService: any;
|
||||||
|
constructor(incidentService: any) {
|
||||||
this.incidentService = incidentService;
|
this.incidentService = incidentService;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get serviceName() {
|
||||||
|
return IncidentController.SERVICE_NAME;
|
||||||
|
}
|
||||||
|
|
||||||
getIncidentsByTeam = async (req: Request, res: Response, next: NextFunction) => {
|
getIncidentsByTeam = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedQuery = getIncidentsByTeamQueryValidation.parse(req.query);
|
const { sortOrder, dateRange, page, rowsPerPage, status, monitorId, resolutionType } = req.query || {};
|
||||||
|
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req.user?.teamId);
|
||||||
const result = await this.incidentService.getIncidentsByTeam(
|
const result = await this.incidentService.getIncidentsByTeam(
|
||||||
teamId,
|
teamId,
|
||||||
validatedQuery.sortOrder,
|
sortOrder,
|
||||||
validatedQuery.dateRange,
|
dateRange,
|
||||||
validatedQuery.page,
|
page,
|
||||||
validatedQuery.rowsPerPage,
|
rowsPerPage,
|
||||||
validatedQuery.status,
|
status,
|
||||||
validatedQuery.monitorId,
|
monitorId,
|
||||||
validatedQuery.resolutionType
|
resolutionType
|
||||||
);
|
);
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
@@ -40,9 +45,10 @@ class IncidentController {
|
|||||||
getIncidentSummary = async (req: Request, res: Response, next: NextFunction) => {
|
getIncidentSummary = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req.user?.teamId);
|
||||||
const validatedQuery = getIncidentSummaryQueryValidation.parse(req.query);
|
|
||||||
|
|
||||||
const summary = await this.incidentService.getIncidentSummary(teamId, validatedQuery.limit);
|
const limit = req.query.limit ? parseInt(req.query.limit as string, 10) : 10;
|
||||||
|
|
||||||
|
const summary = await this.incidentService.getIncidentSummary(teamId, limit);
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: "Incident summary retrieved successfully",
|
msg: "Incident summary retrieved successfully",
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { inviteBodyValidation, inviteVerificationBodyValidation } from "@/validation/authValidation.js";
|
import { inviteBodyValidation, inviteVerificationBodyValidation } from "@/validation/authValidation.js";
|
||||||
import { requireFirstName, requireTeamId, requireUserRoles } from "@/controllers/controllerUtils.js";
|
import { requireTeamId, requireUserRoles } from "@/controllers/controllerUtils.js";
|
||||||
import { IInviteService } from "@/service/index.js";
|
|
||||||
const SERVICE_NAME = "inviteController";
|
const SERVICE_NAME = "inviteController";
|
||||||
|
|
||||||
class InviteController {
|
class InviteController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
private inviteService: IInviteService;
|
private inviteService: any;
|
||||||
constructor(inviteService: IInviteService) {
|
constructor(inviteService: any) {
|
||||||
this.inviteService = inviteService;
|
this.inviteService = inviteService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,9 +34,8 @@ class InviteController {
|
|||||||
|
|
||||||
sendInviteEmail = async (req: Request, res: Response, next: NextFunction) => {
|
sendInviteEmail = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
const userRoles = requireUserRoles(req.user?.role);
|
const userRoles = requireUserRoles(req?.user?.role);
|
||||||
const firstName = requireFirstName(req.user?.firstName);
|
|
||||||
|
|
||||||
const inviteRequest = req.body;
|
const inviteRequest = req.body;
|
||||||
inviteRequest.teamId = teamId;
|
inviteRequest.teamId = teamId;
|
||||||
@@ -45,7 +43,7 @@ class InviteController {
|
|||||||
|
|
||||||
const inviteToken = await this.inviteService.sendInviteEmail({
|
const inviteToken = await this.inviteService.sendInviteEmail({
|
||||||
invite: inviteRequest,
|
invite: inviteRequest,
|
||||||
firstName,
|
firstName: req?.user?.firstName,
|
||||||
userRoles,
|
userRoles,
|
||||||
});
|
});
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import { ILogger } from "@/utils/logger.js";
|
|
||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
|
|
||||||
const SERVICE_NAME = "LogController";
|
const SERVICE_NAME = "LogController";
|
||||||
|
|
||||||
class LogController {
|
class LogController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
private logger: ILogger;
|
private logger: any;
|
||||||
constructor(logger: ILogger) {
|
constructor(logger: any) {
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
get serviceName() {
|
get serviceName() {
|
||||||
@@ -15,7 +14,7 @@ class LogController {
|
|||||||
|
|
||||||
getLogs = async (req: Request, res: Response, next: NextFunction) => {
|
getLogs = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const logs = this.logger.getLogs();
|
const logs = await this.logger.getLogs();
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: "Logs fetched successfully",
|
msg: "Logs fetched successfully",
|
||||||
|
|||||||
@@ -9,19 +9,26 @@ import {
|
|||||||
deleteMaintenanceWindowByIdParamValidation,
|
deleteMaintenanceWindowByIdParamValidation,
|
||||||
} from "@/validation/maintenanceWindowValidation.js";
|
} from "@/validation/maintenanceWindowValidation.js";
|
||||||
import { requireTeamId } from "@/controllers/controllerUtils.js";
|
import { requireTeamId } from "@/controllers/controllerUtils.js";
|
||||||
import { IMaintenanceWindowService } from "@/service/index.js";
|
|
||||||
|
const SERVICE_NAME = "maintenanceWindowController";
|
||||||
|
|
||||||
class MaintenanceWindowController {
|
class MaintenanceWindowController {
|
||||||
private maintenanceWindowService: IMaintenanceWindowService;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
constructor(maintenanceWindowService: IMaintenanceWindowService) {
|
private maintenanceWindowService: any;
|
||||||
|
constructor(maintenanceWindowService: any) {
|
||||||
this.maintenanceWindowService = maintenanceWindowService;
|
this.maintenanceWindowService = maintenanceWindowService;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get serviceName() {
|
||||||
|
return MaintenanceWindowController.SERVICE_NAME;
|
||||||
|
}
|
||||||
|
|
||||||
createMaintenanceWindows = async (req: Request, res: Response, next: NextFunction) => {
|
createMaintenanceWindows = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedBody = createMaintenanceWindowBodyValidation.parse(req.body);
|
createMaintenanceWindowBodyValidation.parse(req.body);
|
||||||
const teamId = requireTeamId(req?.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
await this.maintenanceWindowService.createMaintenanceWindow({ teamId, body: validatedBody });
|
|
||||||
|
await this.maintenanceWindowService.createMaintenanceWindow({ teamId, body: req.body });
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
@@ -33,11 +40,11 @@ class MaintenanceWindowController {
|
|||||||
};
|
};
|
||||||
getMaintenanceWindowById = async (req: Request, res: Response, next: NextFunction) => {
|
getMaintenanceWindowById = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedParams = getMaintenanceWindowByIdParamValidation.parse(req.params);
|
getMaintenanceWindowByIdParamValidation.parse(req.params);
|
||||||
|
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req.user?.teamId);
|
||||||
|
|
||||||
const maintenanceWindow = await this.maintenanceWindowService.getMaintenanceWindowById({ id: validatedParams.id, teamId });
|
const maintenanceWindow = await this.maintenanceWindowService.getMaintenanceWindowById({ id: req.params.id as string, teamId });
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
@@ -51,18 +58,11 @@ class MaintenanceWindowController {
|
|||||||
|
|
||||||
getMaintenanceWindowsByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
getMaintenanceWindowsByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedQuery = getMaintenanceWindowsByTeamIdQueryValidation.parse(req.query);
|
getMaintenanceWindowsByTeamIdQueryValidation.parse(req.query);
|
||||||
|
|
||||||
const teamId = requireTeamId(req?.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
|
|
||||||
const maintenanceWindows = await this.maintenanceWindowService.getMaintenanceWindowsByTeamId({
|
const maintenanceWindows = await this.maintenanceWindowService.getMaintenanceWindowsByTeamId({ teamId, query: req.query });
|
||||||
teamId,
|
|
||||||
active: validatedQuery.active,
|
|
||||||
page: validatedQuery.page,
|
|
||||||
rowsPerPage: validatedQuery.rowsPerPage,
|
|
||||||
field: validatedQuery.field,
|
|
||||||
order: validatedQuery.order,
|
|
||||||
});
|
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
@@ -76,12 +76,12 @@ class MaintenanceWindowController {
|
|||||||
|
|
||||||
getMaintenanceWindowsByMonitorId = async (req: Request, res: Response, next: NextFunction) => {
|
getMaintenanceWindowsByMonitorId = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedParams = getMaintenanceWindowsByMonitorIdParamValidation.parse(req.params);
|
getMaintenanceWindowsByMonitorIdParamValidation.parse(req.params);
|
||||||
|
|
||||||
const teamId = requireTeamId(req?.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
|
|
||||||
const maintenanceWindows = await this.maintenanceWindowService.getMaintenanceWindowsByMonitorId({
|
const maintenanceWindows = await this.maintenanceWindowService.getMaintenanceWindowsByMonitorId({
|
||||||
monitorId: validatedParams.monitorId,
|
monitorId: req.params.monitorId as string,
|
||||||
teamId,
|
teamId,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -96,11 +96,11 @@ class MaintenanceWindowController {
|
|||||||
};
|
};
|
||||||
deleteMaintenanceWindow = async (req: Request, res: Response, next: NextFunction) => {
|
deleteMaintenanceWindow = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedParams = deleteMaintenanceWindowByIdParamValidation.parse(req.params);
|
deleteMaintenanceWindowByIdParamValidation.parse(req.params);
|
||||||
|
|
||||||
const teamId = requireTeamId(req?.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
|
|
||||||
await this.maintenanceWindowService.deleteMaintenanceWindow({ id: validatedParams.id, teamId });
|
await this.maintenanceWindowService.deleteMaintenanceWindow({ id: req.params.id as string, teamId });
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
@@ -113,14 +113,14 @@ class MaintenanceWindowController {
|
|||||||
|
|
||||||
editMaintenanceWindow = async (req: Request, res: Response, next: NextFunction) => {
|
editMaintenanceWindow = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedParams = editMaintenanceWindowByIdParamValidation.parse(req.params);
|
editMaintenanceWindowByIdParamValidation.parse(req.params);
|
||||||
const validatedBody = editMaintenanceByIdWindowBodyValidation.parse(req.body);
|
editMaintenanceByIdWindowBodyValidation.parse(req.body);
|
||||||
|
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req.user?.teamId);
|
||||||
|
|
||||||
const editedMaintenanceWindow = await this.maintenanceWindowService.editMaintenanceWindow({
|
const editedMaintenanceWindow = await this.maintenanceWindowService.editMaintenanceWindow({
|
||||||
id: validatedParams.id,
|
id: req.params.id as string,
|
||||||
body: validatedBody,
|
body: req.body,
|
||||||
teamId,
|
teamId,
|
||||||
});
|
});
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { Request, Response, NextFunction } from "express";
|
|||||||
import {
|
import {
|
||||||
getMonitorByIdParamValidation,
|
getMonitorByIdParamValidation,
|
||||||
getMonitorByIdQueryValidation,
|
getMonitorByIdQueryValidation,
|
||||||
|
getMonitorsByTeamIdParamValidation,
|
||||||
getMonitorsByTeamIdQueryValidation,
|
getMonitorsByTeamIdQueryValidation,
|
||||||
getMonitorsWithChecksQueryValidation,
|
getMonitorsWithChecksQueryValidation,
|
||||||
createMonitorBodyValidation,
|
createMonitorBodyValidation,
|
||||||
@@ -11,14 +12,22 @@ import {
|
|||||||
getCertificateParamValidation,
|
getCertificateParamValidation,
|
||||||
getHardwareDetailsByIdParamValidation,
|
getHardwareDetailsByIdParamValidation,
|
||||||
getHardwareDetailsByIdQueryValidation,
|
getHardwareDetailsByIdQueryValidation,
|
||||||
getUptimeDetailsByIdParamValidation,
|
|
||||||
getUptimeDetailsByIdQueryValidation,
|
|
||||||
importMonitorsBodyValidation,
|
|
||||||
} from "@/validation/monitorValidation.js";
|
} from "@/validation/monitorValidation.js";
|
||||||
import sslChecker from "ssl-checker";
|
import sslChecker from "ssl-checker";
|
||||||
import { fetchMonitorCertificate, requireTeamId, requireUserId } from "./controllerUtils.js";
|
import {
|
||||||
|
fetchMonitorCertificate,
|
||||||
|
requireString,
|
||||||
|
optionalString,
|
||||||
|
optionalNumber,
|
||||||
|
optionalBoolean,
|
||||||
|
parseMonitorTypeFilter,
|
||||||
|
parseSortOrder,
|
||||||
|
requireTeamId,
|
||||||
|
requireUserId,
|
||||||
|
} from "./controllerUtils.js";
|
||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
import { IMonitorService } from "@/service/index.js";
|
import { IMonitorService } from "@/service/index.js";
|
||||||
|
import { GeoContinent } from "@/types/geoCheck.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "monitorController";
|
const SERVICE_NAME = "monitorController";
|
||||||
class MonitorController {
|
class MonitorController {
|
||||||
@@ -36,9 +45,10 @@ class MonitorController {
|
|||||||
|
|
||||||
getMonitorCertificate = async (req: Request, res: Response, next: NextFunction) => {
|
getMonitorCertificate = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedParams = getCertificateParamValidation.parse(req.params);
|
getCertificateParamValidation.parse(req.params);
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
const monitor = await this.monitorService.getMonitorById({ teamId, monitorId: validatedParams.monitorId });
|
const monitorId = requireString(req.params?.monitorId, "Monitor ID");
|
||||||
|
const monitor = await this.monitorService.getMonitorById({ teamId, monitorId });
|
||||||
const certificate = await fetchMonitorCertificate(sslChecker, monitor);
|
const certificate = await fetchMonitorCertificate(sslChecker, monitor);
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
@@ -55,14 +65,10 @@ class MonitorController {
|
|||||||
|
|
||||||
getUptimeDetailsById = async (req: Request, res: Response, next: NextFunction) => {
|
getUptimeDetailsById = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedParams = getUptimeDetailsByIdParamValidation.parse(req.params);
|
const monitorId = requireString(req?.params?.monitorId, "Monitor ID");
|
||||||
const validatedQuery = getUptimeDetailsByIdQueryValidation.parse(req.query);
|
const dateRange = requireString(req?.query?.dateRange, "dateRange");
|
||||||
|
const normalize = optionalBoolean(req?.query?.normalize, "normalize");
|
||||||
const monitorId = validatedParams.monitorId;
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
const dateRange = validatedQuery.dateRange;
|
|
||||||
const normalize = validatedQuery.normalize;
|
|
||||||
|
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
|
||||||
|
|
||||||
const data = await this.monitorService.getUptimeDetailsById({
|
const data = await this.monitorService.getUptimeDetailsById({
|
||||||
teamId,
|
teamId,
|
||||||
@@ -82,12 +88,12 @@ class MonitorController {
|
|||||||
|
|
||||||
getHardwareDetailsById = async (req: Request, res: Response, next: NextFunction) => {
|
getHardwareDetailsById = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedParams = getHardwareDetailsByIdParamValidation.parse(req.params);
|
getHardwareDetailsByIdParamValidation.parse(req.params);
|
||||||
const validatedQuery = getHardwareDetailsByIdQueryValidation.parse(req.query);
|
getHardwareDetailsByIdQueryValidation.parse(req.query);
|
||||||
|
|
||||||
const monitorId = validatedParams.monitorId;
|
const monitorId = requireString(req?.params?.monitorId, "Monitor ID");
|
||||||
const dateRange = validatedQuery.dateRange || "recent";
|
const dateRange = optionalString(req?.query?.dateRange, "dateRange") || "recent";
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
|
|
||||||
const data = await this.monitorService.getHardwareDetailsById({
|
const data = await this.monitorService.getHardwareDetailsById({
|
||||||
teamId,
|
teamId,
|
||||||
@@ -106,12 +112,12 @@ class MonitorController {
|
|||||||
};
|
};
|
||||||
getPageSpeedDetailsById = async (req: Request, res: Response, next: NextFunction) => {
|
getPageSpeedDetailsById = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedParams = getHardwareDetailsByIdParamValidation.parse(req.params);
|
getHardwareDetailsByIdParamValidation.parse(req.params);
|
||||||
const validatedQuery = getHardwareDetailsByIdQueryValidation.parse(req.query);
|
getHardwareDetailsByIdQueryValidation.parse(req.query);
|
||||||
|
|
||||||
const monitorId = validatedParams.monitorId;
|
const monitorId = requireString(req?.params?.monitorId, "Monitor ID");
|
||||||
const dateRange = validatedQuery.dateRange || "recent";
|
const dateRange = requireString(req?.query?.dateRange, "dateRange");
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
|
|
||||||
const data = await this.monitorService.getPageSpeedDetailsById({
|
const data = await this.monitorService.getPageSpeedDetailsById({
|
||||||
teamId,
|
teamId,
|
||||||
@@ -131,14 +137,18 @@ class MonitorController {
|
|||||||
|
|
||||||
getGeoChecksByMonitorId = async (req: Request, res: Response, next: NextFunction) => {
|
getGeoChecksByMonitorId = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedParams = getMonitorByIdParamValidation.parse(req.params);
|
getMonitorByIdParamValidation.parse(req.params);
|
||||||
const validatedQuery = getMonitorByIdQueryValidation.parse(req.query);
|
getMonitorByIdQueryValidation.parse(req.query);
|
||||||
|
|
||||||
const monitorId = validatedParams.monitorId;
|
const monitorId = requireString(req?.params?.monitorId, "Monitor ID");
|
||||||
const dateRange = validatedQuery.dateRange || "recent";
|
const dateRange = requireString(req?.query?.dateRange, "dateRange");
|
||||||
const continentParam = validatedQuery.continent;
|
const continentParam = req?.query?.continent;
|
||||||
const continents = continentParam ? (Array.isArray(continentParam) ? continentParam : [continentParam]) : undefined;
|
const continents = continentParam
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
? Array.isArray(continentParam)
|
||||||
|
? (continentParam as GeoContinent[])
|
||||||
|
: [continentParam as GeoContinent]
|
||||||
|
: undefined;
|
||||||
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
|
|
||||||
const data = await this.monitorService.getGeoChecksByMonitorId({
|
const data = await this.monitorService.getGeoChecksByMonitorId({
|
||||||
teamId,
|
teamId,
|
||||||
@@ -159,10 +169,11 @@ class MonitorController {
|
|||||||
|
|
||||||
getMonitorById = async (req: Request, res: Response, next: NextFunction) => {
|
getMonitorById = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedParams = getMonitorByIdParamValidation.parse(req.params);
|
getMonitorByIdParamValidation.parse(req.params);
|
||||||
|
getMonitorByIdQueryValidation.parse(req.query);
|
||||||
|
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
const monitorId = validatedParams.monitorId;
|
const monitorId = requireString(req?.params?.monitorId, "Monitor ID");
|
||||||
|
|
||||||
const monitor = await this.monitorService.getMonitorById({ teamId, monitorId });
|
const monitor = await this.monitorService.getMonitorById({ teamId, monitorId });
|
||||||
|
|
||||||
@@ -178,12 +189,12 @@ class MonitorController {
|
|||||||
|
|
||||||
createMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
createMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedBody = createMonitorBodyValidation.parse(req.body);
|
createMonitorBodyValidation.parse(req.body);
|
||||||
|
|
||||||
const userId = requireUserId(req.user?.id);
|
const userId = requireString(req?.user?.id, "User ID");
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
|
|
||||||
const monitor = await this.monitorService.createMonitor(teamId, userId, validatedBody);
|
const monitor = await this.monitorService.createMonitor(teamId, userId, req.body);
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
@@ -197,10 +208,14 @@ class MonitorController {
|
|||||||
|
|
||||||
importMonitorsFromJSON = async (req: Request, res: Response, next: NextFunction) => {
|
importMonitorsFromJSON = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
const userId = requireUserId(req.user?.id);
|
const userId = requireUserId(req?.user?.id);
|
||||||
const validatedBody = importMonitorsBodyValidation.parse(req.body);
|
|
||||||
const monitors = validatedBody.monitors;
|
const { monitors } = req.body;
|
||||||
|
|
||||||
|
if (!monitors || !Array.isArray(monitors)) {
|
||||||
|
throw new AppError({ message: "Invalid request: monitors array is required", status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
const result = await this.monitorService.importMonitorsFromJSON({ teamId, userId, monitors });
|
const result = await this.monitorService.importMonitorsFromJSON({ teamId, userId, monitors });
|
||||||
|
|
||||||
@@ -216,9 +231,9 @@ class MonitorController {
|
|||||||
|
|
||||||
deleteMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
deleteMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedParams = getMonitorByIdParamValidation.parse(req.params);
|
getMonitorByIdParamValidation.parse(req.params);
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const monitorId = requireString(req?.params?.monitorId, "Monitor ID");
|
||||||
const monitorId = validatedParams.monitorId;
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
|
|
||||||
const deletedMonitor = await this.monitorService.deleteMonitor({ teamId, monitorId });
|
const deletedMonitor = await this.monitorService.deleteMonitor({ teamId, monitorId });
|
||||||
|
|
||||||
@@ -234,7 +249,8 @@ class MonitorController {
|
|||||||
|
|
||||||
deleteAllMonitors = async (req: Request, res: Response, next: NextFunction) => {
|
deleteAllMonitors = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
|
|
||||||
const deletedCount = await this.monitorService.deleteAllMonitors({ teamId });
|
const deletedCount = await this.monitorService.deleteAllMonitors({ teamId });
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
@@ -248,12 +264,12 @@ class MonitorController {
|
|||||||
|
|
||||||
editMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
editMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedParams = getMonitorByIdParamValidation.parse(req.params);
|
getMonitorByIdParamValidation.parse(req.params);
|
||||||
const validatedBody = editMonitorBodyValidation.parse(req.body);
|
editMonitorBodyValidation.parse(req.body);
|
||||||
const monitorId = validatedParams.monitorId;
|
const monitorId = requireString(req?.params?.monitorId, "Monitor ID");
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
|
|
||||||
const editedMonitor = await this.monitorService.editMonitor({ teamId, monitorId, body: validatedBody });
|
const editedMonitor = await this.monitorService.editMonitor({ teamId, monitorId, body: req.body });
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
@@ -267,10 +283,10 @@ class MonitorController {
|
|||||||
|
|
||||||
pauseMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
pauseMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedParams = pauseMonitorParamValidation.parse(req.params);
|
pauseMonitorParamValidation.parse(req.params);
|
||||||
|
|
||||||
const monitorId = validatedParams.monitorId;
|
const monitorId = requireString(req?.params?.monitorId, "Monitor ID");
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
|
|
||||||
const monitor = await this.monitorService.pauseMonitor({ teamId, monitorId });
|
const monitor = await this.monitorService.pauseMonitor({ teamId, monitorId });
|
||||||
|
|
||||||
@@ -286,8 +302,8 @@ class MonitorController {
|
|||||||
|
|
||||||
addDemoMonitors = async (req: Request, res: Response, next: NextFunction) => {
|
addDemoMonitors = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const id = requireUserId(req.user?.id);
|
const id = requireString(req?.user?.id, "User ID");
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
const demoMonitors = await this.monitorService.addDemoMonitors({ userId: id, teamId });
|
const demoMonitors = await this.monitorService.addDemoMonitors({ userId: id, teamId });
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
@@ -300,13 +316,32 @@ class MonitorController {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
sendTestEmail = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const { to } = req.body;
|
||||||
|
if (!to || typeof to !== "string") {
|
||||||
|
throw new AppError({ message: "Invalid 'to' email address", status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const messageId = await this.monitorService.sendTestEmail({ to });
|
||||||
|
return res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
msg: "Test email sent successfully",
|
||||||
|
data: { messageId },
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
getMonitorsByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
getMonitorsByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedQuery = getMonitorsByTeamIdQueryValidation.parse(req.query);
|
getMonitorsByTeamIdParamValidation.parse(req.params);
|
||||||
|
getMonitorsByTeamIdQueryValidation.parse(req.query);
|
||||||
|
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
const type = validatedQuery.type;
|
const type = parseMonitorTypeFilter(req.query?.type);
|
||||||
const filter = validatedQuery.filter;
|
const filter = optionalString(req.query?.filter, "filter");
|
||||||
|
|
||||||
const monitors = await this.monitorService.getMonitorsByTeamId({ teamId, type, filter });
|
const monitors = await this.monitorService.getMonitorsByTeamId({ teamId, type, filter });
|
||||||
|
|
||||||
@@ -322,17 +357,17 @@ class MonitorController {
|
|||||||
|
|
||||||
getMonitorsWithChecksByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
getMonitorsWithChecksByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedQuery = getMonitorsWithChecksQueryValidation.parse(req.query);
|
getMonitorsByTeamIdParamValidation.parse(req.params);
|
||||||
|
getMonitorsWithChecksQueryValidation.parse(req.query);
|
||||||
const explain = validatedQuery.explain;
|
const explain = optionalBoolean(req?.query?.explain, "explain");
|
||||||
const limit = validatedQuery.limit;
|
const limit = optionalNumber(req?.query?.limit, "limit");
|
||||||
const page = validatedQuery.page;
|
const page = optionalNumber(req?.query?.page, "page");
|
||||||
const rowsPerPage = validatedQuery.rowsPerPage;
|
const rowsPerPage = optionalNumber(req?.query?.rowsPerPage, "rowsPerPage");
|
||||||
const filter = validatedQuery.filter;
|
const filter = optionalString(req?.query?.filter, "filter");
|
||||||
const field = validatedQuery.field;
|
const field = optionalString(req?.query?.field, "field");
|
||||||
const order = validatedQuery.order;
|
const order = parseSortOrder(req?.query?.order);
|
||||||
const type = validatedQuery.type;
|
const type = parseMonitorTypeFilter(req?.query?.type);
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
|
|
||||||
const monitors = await this.monitorService.getMonitorsWithChecksByTeamId({
|
const monitors = await this.monitorService.getMonitorsWithChecksByTeamId({
|
||||||
teamId,
|
teamId,
|
||||||
@@ -357,7 +392,11 @@ class MonitorController {
|
|||||||
|
|
||||||
exportMonitorsToJSON = async (req: Request, res: Response, next: NextFunction) => {
|
exportMonitorsToJSON = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = req?.user?.teamId;
|
||||||
|
if (!teamId) {
|
||||||
|
throw new AppError({ message: "Team ID is required", status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
const json = await this.monitorService.exportMonitorsToJSON({ teamId });
|
const json = await this.monitorService.exportMonitorsToJSON({ teamId });
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
@@ -385,7 +424,11 @@ class MonitorController {
|
|||||||
|
|
||||||
getGroupsByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
getGroupsByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = req?.user?.teamId;
|
||||||
|
if (!teamId) {
|
||||||
|
throw new AppError({ message: "Team ID is required", status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
const groups = await this.monitorService.getGroupsByTeamId({ teamId });
|
const groups = await this.monitorService.getGroupsByTeamId({ teamId });
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
|
|||||||
@@ -1,21 +1,16 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
|
|
||||||
import {
|
import { Notification } from "@/types/index.js";
|
||||||
createNotificationBodyValidation,
|
import { createNotificationBodyValidation } from "@/validation/notificationValidation.js";
|
||||||
deleteNotificationParamValidation,
|
|
||||||
getNotificationByIdParamValidation,
|
|
||||||
testNotificationBodyValidation,
|
|
||||||
editNotificationParamValidation,
|
|
||||||
testAllNotificationsBodyValidation,
|
|
||||||
} from "@/validation/notificationValidation.js";
|
|
||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
import { IMonitorsRepository } from "@/repositories/index.js";
|
import { IMonitorsRepository } from "@/repositories/index.js";
|
||||||
import { INotificationsService } from "@/service/index.js";
|
import { INotificationsService } from "@/service/index.js";
|
||||||
import { requireTeamId, requireUserId } from "./controllerUtils.js";
|
import { requireTeamId } from "./controllerUtils.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "NotificationController";
|
const SERVICE_NAME = "NotificationController";
|
||||||
|
|
||||||
class NotificationController {
|
class NotificationController {
|
||||||
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
private notificationsService: INotificationsService;
|
private notificationsService: INotificationsService;
|
||||||
private monitorsRepository: IMonitorsRepository;
|
private monitorsRepository: IMonitorsRepository;
|
||||||
constructor(notificationsService: INotificationsService, monitorsRepository: IMonitorsRepository) {
|
constructor(notificationsService: INotificationsService, monitorsRepository: IMonitorsRepository) {
|
||||||
@@ -23,9 +18,13 @@ class NotificationController {
|
|||||||
this.monitorsRepository = monitorsRepository;
|
this.monitorsRepository = monitorsRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get serviceName() {
|
||||||
|
return NotificationController.SERVICE_NAME;
|
||||||
|
}
|
||||||
|
|
||||||
testNotification = async (req: Request, res: Response, next: NextFunction) => {
|
testNotification = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const notification = testNotificationBodyValidation.parse(req.body);
|
const notification: Notification = req.body;
|
||||||
const success = await this.notificationsService.sendTestNotification(notification);
|
const success = await this.notificationsService.sendTestNotification(notification);
|
||||||
|
|
||||||
if (!success) {
|
if (!success) {
|
||||||
@@ -35,7 +34,6 @@ class NotificationController {
|
|||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: "Notification sent successfully",
|
msg: "Notification sent successfully",
|
||||||
details: { service: SERVICE_NAME },
|
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
next(error);
|
next(error);
|
||||||
@@ -44,12 +42,23 @@ class NotificationController {
|
|||||||
|
|
||||||
createNotification = async (req: Request, res: Response, next: NextFunction) => {
|
createNotification = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedBody = createNotificationBodyValidation.parse(req.body);
|
createNotificationBodyValidation.parse(req.body);
|
||||||
|
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const body = req.body;
|
||||||
const userId = requireUserId(req.user?.id);
|
|
||||||
|
|
||||||
const notification = await this.notificationsService.createNotification(validatedBody, userId, teamId);
|
const teamId = req?.user?.teamId;
|
||||||
|
if (!teamId) {
|
||||||
|
throw new AppError({ message: "Team ID is required", status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = req?.user?.id;
|
||||||
|
if (!userId) {
|
||||||
|
throw new AppError({ message: "User ID is required", status: 400 });
|
||||||
|
}
|
||||||
|
body.userId = userId;
|
||||||
|
body.teamId = teamId;
|
||||||
|
|
||||||
|
const notification = await this.notificationsService.createNotification(body);
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: "Notification created successfully",
|
msg: "Notification created successfully",
|
||||||
@@ -62,7 +71,11 @@ class NotificationController {
|
|||||||
|
|
||||||
getNotificationsByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
getNotificationsByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = req?.user?.teamId;
|
||||||
|
if (!teamId) {
|
||||||
|
throw new AppError({ message: "Team ID is required", status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
const notifications = await this.notificationsService.findNotificationsByTeamId(teamId);
|
const notifications = await this.notificationsService.findNotificationsByTeamId(teamId);
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
@@ -77,10 +90,17 @@ class NotificationController {
|
|||||||
|
|
||||||
deleteNotification = async (req: Request, res: Response, next: NextFunction) => {
|
deleteNotification = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = req?.user?.teamId;
|
||||||
const validatedParams = deleteNotificationParamValidation.parse(req.params);
|
if (!teamId) {
|
||||||
|
throw new AppError({ message: "Team ID is required", status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
await this.notificationsService.deleteById(validatedParams.id, teamId);
|
const notificationId = req.params.id as string;
|
||||||
|
if (!notificationId) {
|
||||||
|
throw new AppError({ message: "Notification ID is required", status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.notificationsService.deleteById(notificationId, teamId);
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: "Notification deleted successfully",
|
msg: "Notification deleted successfully",
|
||||||
@@ -93,9 +113,12 @@ class NotificationController {
|
|||||||
getNotificationById = async (req: Request, res: Response, next: NextFunction) => {
|
getNotificationById = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req.user?.teamId);
|
||||||
const validatedParams = getNotificationByIdParamValidation.parse(req.params);
|
const notificationId = req.params.id as string;
|
||||||
|
if (!notificationId) {
|
||||||
|
throw new AppError({ message: "Notification ID is required", status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
const notification = await this.notificationsService.findById(validatedParams.id, teamId);
|
const notification = await this.notificationsService.findById(notificationId, teamId);
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
@@ -109,13 +132,14 @@ class NotificationController {
|
|||||||
|
|
||||||
editNotification = async (req: Request, res: Response, next: NextFunction) => {
|
editNotification = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedBody = createNotificationBodyValidation.parse(req.body);
|
createNotificationBodyValidation.parse(req.body);
|
||||||
const validatedParams = editNotificationParamValidation.parse(req.params);
|
|
||||||
|
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req.user?.teamId);
|
||||||
const notificationId = validatedParams.id;
|
const notificationId = req.params.id as string;
|
||||||
|
if (!notificationId) {
|
||||||
const editedNotification = await this.notificationsService.updateById(notificationId, teamId, validatedBody);
|
throw new AppError({ message: "Notification ID is required", status: 400 });
|
||||||
|
}
|
||||||
|
const editedNotification = await this.notificationsService.updateById(notificationId, teamId, req.body);
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: "Notification updated successfully",
|
msg: "Notification updated successfully",
|
||||||
@@ -128,11 +152,13 @@ class NotificationController {
|
|||||||
|
|
||||||
testAllNotifications = async (req: Request, res: Response, next: NextFunction) => {
|
testAllNotifications = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const validatedBody = testAllNotificationsBodyValidation.parse(req.body);
|
const monitorId = req.body.monitorId;
|
||||||
|
const teamId = req?.user?.teamId;
|
||||||
|
if (!teamId) {
|
||||||
|
throw new AppError({ message: "Team ID is required", status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const monitor = await this.monitorsRepository.findById(monitorId, teamId);
|
||||||
|
|
||||||
const monitor = await this.monitorsRepository.findById(validatedBody.monitorId, teamId);
|
|
||||||
|
|
||||||
const notifications = monitor.notifications;
|
const notifications = monitor.notifications;
|
||||||
if (notifications.length === 0) {
|
if (notifications.length === 0) {
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import mongoose from "mongoose";
|
||||||
|
import { logger } from "@/utils/logger.js";
|
||||||
|
import StatusPageModel from "../models/StatusPage.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Migration: Convert StatusPage `type` field from string to array of strings
|
||||||
|
*
|
||||||
|
* Old format: { type: "uptime" }
|
||||||
|
* New format: { type: ["uptime"] }
|
||||||
|
*/
|
||||||
|
export async function migrateStatusPageTypeToArray(): Promise<void> {
|
||||||
|
const SERVICE_NAME = "Migration:MigrateStatusPageTypeToArray";
|
||||||
|
|
||||||
|
try {
|
||||||
|
logger.info({ service: SERVICE_NAME, message: "Starting migration of StatusPage type field from string to array" });
|
||||||
|
|
||||||
|
const db = mongoose.connection.db;
|
||||||
|
if (!db) {
|
||||||
|
throw new Error("Database connection is not initialized");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find all status pages where `type` is a string (not yet migrated)
|
||||||
|
const result = await StatusPageModel.updateMany(
|
||||||
|
{
|
||||||
|
$expr: {
|
||||||
|
$eq: [{ $type: "$type" }, "string"], // only scalar string, not existing array
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
type: ["$type"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.modifiedCount === 0) {
|
||||||
|
logger.info({ service: SERVICE_NAME, message: "No StatusPage documents needed migration" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info({
|
||||||
|
service: SERVICE_NAME,
|
||||||
|
message: `Migration complete. Converted ${result.modifiedCount} StatusPage document(s) from string type to array type`,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
logger.error({ service: SERVICE_NAME, message: `Error during StatusPage type migration: ${errorMessage}` });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import { convertChecksToTimeSeries } from "./0002_convertChecksToTimeSeries.js";
|
|||||||
import { cleanupDuplicateMonitorStats } from "./0003_cleanupDuplicateMonitorStats.js";
|
import { cleanupDuplicateMonitorStats } from "./0003_cleanupDuplicateMonitorStats.js";
|
||||||
import { fixInfrastructureThresholds } from "./0004_fixInfrastructureThresholds.js";
|
import { fixInfrastructureThresholds } from "./0004_fixInfrastructureThresholds.js";
|
||||||
import MigrationModel from "../models/Migration.js";
|
import MigrationModel from "../models/Migration.js";
|
||||||
|
import { migrateStatusPageTypeToArray } from "./0005_migrateStatusPageTypeToArray.js";
|
||||||
|
|
||||||
type MigrationEntry = {
|
type MigrationEntry = {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -14,6 +15,7 @@ const migrations: MigrationEntry[] = [
|
|||||||
{ name: "0002_convertChecksToTimeSeries", execute: convertChecksToTimeSeries },
|
{ name: "0002_convertChecksToTimeSeries", execute: convertChecksToTimeSeries },
|
||||||
{ name: "0003_cleanupDuplicateMonitorStats", execute: cleanupDuplicateMonitorStats },
|
{ name: "0003_cleanupDuplicateMonitorStats", execute: cleanupDuplicateMonitorStats },
|
||||||
{ name: "0004_fixInfrastructureThresholds", execute: fixInfrastructureThresholds },
|
{ name: "0004_fixInfrastructureThresholds", execute: fixInfrastructureThresholds },
|
||||||
|
{ name: "0005_migrateStatusPageTypeToArray", execute: migrateStatusPageTypeToArray },
|
||||||
];
|
];
|
||||||
|
|
||||||
const runMigrations = async (logger?: { info: Function; error: Function }) => {
|
const runMigrations = async (logger?: { info: Function; error: Function }) => {
|
||||||
|
|||||||
@@ -43,9 +43,9 @@ const StatusPageSchema = new Schema<StatusPageDocument>(
|
|||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
type: {
|
type: {
|
||||||
type: String,
|
type: [String],
|
||||||
required: true,
|
required: true,
|
||||||
default: "uptime",
|
default: [],
|
||||||
enum: StatusPageTypes,
|
enum: StatusPageTypes,
|
||||||
},
|
},
|
||||||
companyName: {
|
companyName: {
|
||||||
@@ -100,6 +100,10 @@ const StatusPageSchema = new Schema<StatusPageDocument>(
|
|||||||
type: Boolean,
|
type: Boolean,
|
||||||
default: false,
|
default: false,
|
||||||
},
|
},
|
||||||
|
showInfrastructure: {
|
||||||
|
type: Boolean,
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
customCSS: {
|
customCSS: {
|
||||||
type: String,
|
type: String,
|
||||||
default: "",
|
default: "",
|
||||||
|
|||||||
@@ -5,12 +5,12 @@ export interface IMaintenanceWindowsRepository {
|
|||||||
// fetch
|
// fetch
|
||||||
findById(id: string, teamId: string): Promise<MaintenanceWindow>;
|
findById(id: string, teamId: string): Promise<MaintenanceWindow>;
|
||||||
findByMonitorId(monitorId: string, teamId: string): Promise<MaintenanceWindow[]>;
|
findByMonitorId(monitorId: string, teamId: string): Promise<MaintenanceWindow[]>;
|
||||||
findByTeamId(teamId: string, page: number, rowsPerPage: number, field?: string, order?: string, active?: boolean): Promise<MaintenanceWindow[]>;
|
findByTeamId(teamId: string, active: boolean, page: number, rowsPerPage: number, field: string, order: string): Promise<MaintenanceWindow[]>;
|
||||||
|
|
||||||
// update
|
// update
|
||||||
updateById(id: string, teamId: string, data: Partial<MaintenanceWindow>): Promise<MaintenanceWindow>;
|
updateById(id: string, teamId: string, data: Partial<MaintenanceWindow>): Promise<MaintenanceWindow>;
|
||||||
// delete
|
// delete
|
||||||
deleteById(id: string, teamId: string): Promise<MaintenanceWindow>;
|
deleteById(id: string, teamId: string): Promise<MaintenanceWindow>;
|
||||||
// other
|
// other
|
||||||
countByTeamId(teamId: string, active?: boolean): Promise<number>;
|
countByTeamId(teamId: string, active: boolean): Promise<number>;
|
||||||
}
|
}
|
||||||
@@ -75,11 +75,11 @@ class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository
|
|||||||
|
|
||||||
findByTeamId = async (
|
findByTeamId = async (
|
||||||
teamId: string,
|
teamId: string,
|
||||||
|
active: boolean,
|
||||||
page: number,
|
page: number,
|
||||||
rowsPerPage: number,
|
rowsPerPage: number,
|
||||||
field?: string,
|
field: string,
|
||||||
order?: string,
|
order: string
|
||||||
active?: boolean
|
|
||||||
): Promise<MaintenanceWindow[]> => {
|
): Promise<MaintenanceWindow[]> => {
|
||||||
const maintenanceQuery: Record<string, any> = { teamId };
|
const maintenanceQuery: Record<string, any> = { teamId };
|
||||||
|
|
||||||
@@ -126,7 +126,7 @@ class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository
|
|||||||
}
|
}
|
||||||
return this.toEntity(deleted);
|
return this.toEntity(deleted);
|
||||||
};
|
};
|
||||||
countByTeamId = async (teamId: string, active?: boolean) => {
|
countByTeamId = async (teamId: string, active: boolean) => {
|
||||||
const maintenanceQuery: Record<string, any> = { teamId };
|
const maintenanceQuery: Record<string, any> = { teamId };
|
||||||
|
|
||||||
if (active !== undefined) maintenanceQuery.active = active;
|
if (active !== undefined) maintenanceQuery.active = active;
|
||||||
|
|||||||
@@ -57,6 +57,7 @@ class MongoStatusPagesRepository implements IStatusPagesRepository {
|
|||||||
showCharts: doc.showCharts,
|
showCharts: doc.showCharts,
|
||||||
showUptimePercentage: doc.showUptimePercentage,
|
showUptimePercentage: doc.showUptimePercentage,
|
||||||
showAdminLoginLink: doc.showAdminLoginLink,
|
showAdminLoginLink: doc.showAdminLoginLink,
|
||||||
|
showInfrastructure: doc.showInfrastructure,
|
||||||
customCSS: doc.customCSS,
|
customCSS: doc.customCSS,
|
||||||
createdAt: this.toDateString(doc.createdAt),
|
createdAt: this.toDateString(doc.createdAt),
|
||||||
updatedAt: this.toDateString(doc.updatedAt),
|
updatedAt: this.toDateString(doc.updatedAt),
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ class MonitorRoutes {
|
|||||||
this.router.get("/export/json", isAllowed(["admin", "superadmin"]), this.monitorController.exportMonitorsToJSON);
|
this.router.get("/export/json", isAllowed(["admin", "superadmin"]), this.monitorController.exportMonitorsToJSON);
|
||||||
this.router.post("/import/json", isAllowed(["admin", "superadmin"]), this.monitorController.importMonitorsFromJSON);
|
this.router.post("/import/json", isAllowed(["admin", "superadmin"]), this.monitorController.importMonitorsFromJSON);
|
||||||
|
|
||||||
|
this.router.post("/test-email", isAllowed(["admin", "superadmin"]), this.monitorController.sendTestEmail);
|
||||||
this.router.get("/games", this.monitorController.getAllGames);
|
this.router.get("/games", this.monitorController.getAllGames);
|
||||||
|
|
||||||
// Individual monitor CRUD routes
|
// Individual monitor CRUD routes
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ const SERVICE_NAME = "incidentService";
|
|||||||
import type { Monitor } from "@/types/monitor.js";
|
import type { Monitor } from "@/types/monitor.js";
|
||||||
import type { MonitorStatusResponse } from "@/types/network.js";
|
import type { MonitorStatusResponse } from "@/types/network.js";
|
||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
|
import { ParseBoolean } from "@/utils/utils.js";
|
||||||
import { getDateForRange } from "@/utils/dataUtils.js";
|
import { getDateForRange } from "@/utils/dataUtils.js";
|
||||||
import type { IIncidentsRepository, IMonitorsRepository, IUsersRepository } from "@/repositories/index.js";
|
import type { IIncidentsRepository, IMonitorsRepository, IUsersRepository } from "@/repositories/index.js";
|
||||||
import type { Incident, IncidentSummary, User } from "@/types/index.js";
|
import type { Incident, IncidentSummary, User } from "@/types/index.js";
|
||||||
@@ -21,13 +22,13 @@ export interface IIncidentService {
|
|||||||
teamId: string,
|
teamId: string,
|
||||||
sortOrder: string,
|
sortOrder: string,
|
||||||
dateRange: string,
|
dateRange: string,
|
||||||
page: number,
|
page: string,
|
||||||
rowsPerPage: number,
|
rowsPerPage: string,
|
||||||
status: boolean | undefined,
|
status: string,
|
||||||
monitorId: string | undefined,
|
monitorId: string,
|
||||||
resolutionType: string | undefined
|
resolutionType: string
|
||||||
): Promise<{ incidents: Incident[]; count: number }>;
|
): Promise<{ incidents: Incident[]; count: number }>;
|
||||||
getIncidentSummary(teamId: string, limit?: number): Promise<IncidentSummary>;
|
getIncidentSummary(teamId: string, limit?: string): Promise<IncidentSummary>;
|
||||||
getIncidentById(incidentId: string, teamId: string): Promise<{ incident: Incident; monitor: Monitor; user: User | null }>;
|
getIncidentById(incidentId: string, teamId: string): Promise<{ incident: Incident; monitor: Monitor; user: User | null }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -163,13 +164,13 @@ export class IncidentService implements IIncidentService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return resolvedIncident;
|
return resolvedIncident;
|
||||||
} catch (error: unknown) {
|
} catch (error: any) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "resolveIncident",
|
method: "resolveIncident",
|
||||||
message: error instanceof Error ? error.message : "Unknown error",
|
message: error.message,
|
||||||
details: { id: incidentId },
|
details: { id: incidentId },
|
||||||
stack: error instanceof Error ? error.stack : undefined,
|
stack: error.stack,
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -179,11 +180,11 @@ export class IncidentService implements IIncidentService {
|
|||||||
teamId: string,
|
teamId: string,
|
||||||
sortOrder: string,
|
sortOrder: string,
|
||||||
dateRange: string,
|
dateRange: string,
|
||||||
page: number,
|
page: string,
|
||||||
rowsPerPage: number,
|
rowsPerPage: string,
|
||||||
status: boolean | undefined,
|
status: string,
|
||||||
monitorId: string | undefined,
|
monitorId: string,
|
||||||
resolutionType: string | undefined
|
resolutionType: string
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
if (!teamId) {
|
if (!teamId) {
|
||||||
@@ -192,8 +193,9 @@ export class IncidentService implements IIncidentService {
|
|||||||
|
|
||||||
const startDate = getDateForRange(dateRange);
|
const startDate = getDateForRange(dateRange);
|
||||||
|
|
||||||
const parsedPage = page ?? 0;
|
const parsedPage = Number.isFinite(parseInt(page)) ? parseInt(page) : 0;
|
||||||
const parsedRowsPerPage = rowsPerPage ?? 20;
|
const parsedRowsPerPage = Number.isFinite(parseInt(rowsPerPage)) ? parseInt(rowsPerPage) : 20;
|
||||||
|
const parsedStatus = typeof status === "undefined" ? undefined : ParseBoolean(status);
|
||||||
|
|
||||||
const incidents = await this.incidentsRepository.findByTeamId(
|
const incidents = await this.incidentsRepository.findByTeamId(
|
||||||
teamId,
|
teamId,
|
||||||
@@ -201,43 +203,43 @@ export class IncidentService implements IIncidentService {
|
|||||||
parsedPage,
|
parsedPage,
|
||||||
parsedRowsPerPage,
|
parsedRowsPerPage,
|
||||||
sortOrder,
|
sortOrder,
|
||||||
status,
|
parsedStatus,
|
||||||
monitorId,
|
monitorId,
|
||||||
resolutionType
|
resolutionType
|
||||||
);
|
);
|
||||||
|
|
||||||
const count = await this.incidentsRepository.countByTeamId(teamId, startDate, status, monitorId, resolutionType);
|
const count = await this.incidentsRepository.countByTeamId(teamId, startDate, parsedStatus, monitorId, resolutionType);
|
||||||
|
|
||||||
return { incidents, count };
|
return { incidents, count };
|
||||||
} catch (error: unknown) {
|
} catch (error: any) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "getIncidentsByTeam",
|
method: "getIncidentsByTeam",
|
||||||
message: error instanceof Error ? error.message : "Unknown error",
|
message: error.message,
|
||||||
details: { teamId },
|
details: { teamId },
|
||||||
stack: error instanceof Error ? error.stack : undefined,
|
stack: error.stack,
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
getIncidentSummary = async (teamId: string, limit?: number) => {
|
getIncidentSummary = async (teamId: string, limit?: string) => {
|
||||||
try {
|
try {
|
||||||
if (!teamId) {
|
if (!teamId) {
|
||||||
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "getIncidentSummary", status: 400 });
|
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "getIncidentSummary", status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const parsedLimit = limit ?? 10;
|
const parsedLimit = limit && Number.isFinite(parseInt(limit, 10)) ? parseInt(limit, 10) : 10;
|
||||||
const summary = await this.incidentsRepository.findSummaryByTeamId(teamId, parsedLimit);
|
const summary = await this.incidentsRepository.findSummaryByTeamId(teamId, parsedLimit);
|
||||||
|
|
||||||
return summary;
|
return summary;
|
||||||
} catch (error: unknown) {
|
} catch (error: any) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "getIncidentSummary",
|
method: "getIncidentSummary",
|
||||||
message: error instanceof Error ? error.message : "Unknown error",
|
message: error.message,
|
||||||
details: { teamId },
|
details: { teamId },
|
||||||
stack: error instanceof Error ? error.stack : undefined,
|
stack: error.stack,
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -252,13 +254,13 @@ export class IncidentService implements IIncidentService {
|
|||||||
user = await this.usersRepository.findById(incident.resolvedBy);
|
user = await this.usersRepository.findById(incident.resolvedBy);
|
||||||
}
|
}
|
||||||
return { incident, monitor, user };
|
return { incident, monitor, user };
|
||||||
} catch (error: unknown) {
|
} catch (error: any) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "getIncidentById",
|
method: "getIncidentById",
|
||||||
message: error instanceof Error ? error.message : "Unknown error",
|
message: error.message,
|
||||||
details: { incidentId },
|
details: { incidentId },
|
||||||
stack: error instanceof Error ? error.stack : undefined,
|
stack: error.stack,
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { IMaintenanceWindowsRepository, IMonitorsRepository } from "@/repositories/index.js";
|
import { IMaintenanceWindowsRepository, IMonitorsRepository } from "@/repositories/index.js";
|
||||||
import type { MaintenanceWindow } from "@/types/index.js";
|
import type { MaintenanceWindow } from "@/types/index.js";
|
||||||
|
import { ParseBoolean } from "@/utils/utils.js";
|
||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "maintenanceWindowService";
|
const SERVICE_NAME = "maintenanceWindowService";
|
||||||
@@ -9,11 +10,7 @@ export interface IMaintenanceWindowService {
|
|||||||
getMaintenanceWindowById(params: { id: string; teamId: string }): Promise<MaintenanceWindow>;
|
getMaintenanceWindowById(params: { id: string; teamId: string }): Promise<MaintenanceWindow>;
|
||||||
getMaintenanceWindowsByTeamId(params: {
|
getMaintenanceWindowsByTeamId(params: {
|
||||||
teamId: string;
|
teamId: string;
|
||||||
active?: boolean;
|
query: Record<string, string>;
|
||||||
page?: number;
|
|
||||||
rowsPerPage?: number;
|
|
||||||
field?: string;
|
|
||||||
order?: string;
|
|
||||||
}): Promise<{ maintenanceWindows: MaintenanceWindow[]; maintenanceWindowCount: number }>;
|
}): Promise<{ maintenanceWindows: MaintenanceWindow[]; maintenanceWindowCount: number }>;
|
||||||
getMaintenanceWindowsByMonitorId(params: { monitorId: string; teamId: string }): Promise<MaintenanceWindow[]>;
|
getMaintenanceWindowsByMonitorId(params: { monitorId: string; teamId: string }): Promise<MaintenanceWindow[]>;
|
||||||
deleteMaintenanceWindow(params: { id: string; teamId: string }): Promise<MaintenanceWindow>;
|
deleteMaintenanceWindow(params: { id: string; teamId: string }): Promise<MaintenanceWindow>;
|
||||||
@@ -75,25 +72,14 @@ export class MaintenanceWindowService implements IMaintenanceWindowService {
|
|||||||
return await this.maintenanceWindowsRepository.findById(id, teamId);
|
return await this.maintenanceWindowsRepository.findById(id, teamId);
|
||||||
};
|
};
|
||||||
|
|
||||||
getMaintenanceWindowsByTeamId = async ({
|
getMaintenanceWindowsByTeamId = async ({ teamId, query }: { teamId: string; query: any }) => {
|
||||||
teamId,
|
let { active, page, rowsPerPage, field, order } = query || {};
|
||||||
active,
|
|
||||||
page,
|
|
||||||
rowsPerPage,
|
|
||||||
field,
|
|
||||||
order,
|
|
||||||
}: {
|
|
||||||
teamId: string;
|
|
||||||
active?: boolean;
|
|
||||||
page?: number;
|
|
||||||
rowsPerPage?: number;
|
|
||||||
field?: string;
|
|
||||||
order?: string;
|
|
||||||
}) => {
|
|
||||||
page = page ?? 0;
|
|
||||||
rowsPerPage = rowsPerPage ?? 10;
|
|
||||||
|
|
||||||
const maintenanceWindows = await this.maintenanceWindowsRepository.findByTeamId(teamId, page, rowsPerPage, field, order, active);
|
active = typeof active === "undefined" ? undefined : ParseBoolean(active);
|
||||||
|
page = parseInt(page) || 0;
|
||||||
|
rowsPerPage = parseInt(rowsPerPage) || 10;
|
||||||
|
|
||||||
|
const maintenanceWindows = await this.maintenanceWindowsRepository.findByTeamId(teamId, active, page, rowsPerPage, field, order);
|
||||||
const maintenanceWindowCount = await this.maintenanceWindowsRepository.countByTeamId(teamId, active);
|
const maintenanceWindowCount = await this.maintenanceWindowsRepository.countByTeamId(teamId, active);
|
||||||
return { maintenanceWindows, maintenanceWindowCount };
|
return { maintenanceWindows, maintenanceWindowCount };
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ export interface IMonitorService {
|
|||||||
readonly serviceName: string;
|
readonly serviceName: string;
|
||||||
|
|
||||||
// create
|
// create
|
||||||
createMonitor(teamId: string, userId: string, body: Partial<Monitor>): Promise<void>;
|
createMonitor(teamId: string, userId: string, body: Monitor): Promise<void>;
|
||||||
createMonitors(monitors: Array<Monitor>, userId: string, teamId: string): Promise<Monitor[] | null>;
|
createMonitors(monitors: Array<Monitor>, userId: string, teamId: string): Promise<Monitor[] | null>;
|
||||||
addDemoMonitors(args: { userId: string; teamId: string }): Promise<Monitor[]>;
|
addDemoMonitors(args: { userId: string; teamId: string }): Promise<Monitor[]>;
|
||||||
|
|
||||||
@@ -64,7 +64,7 @@ export interface IMonitorService {
|
|||||||
getGroupsByTeamId(args: { teamId: string }): Promise<string[]>;
|
getGroupsByTeamId(args: { teamId: string }): Promise<string[]>;
|
||||||
|
|
||||||
// update
|
// update
|
||||||
editMonitor(args: { teamId: string; monitorId: string; body: Partial<Monitor> }): Promise<Monitor>;
|
editMonitor(args: { teamId: string; monitorId: string; body: Monitor }): Promise<Monitor>;
|
||||||
pauseMonitor(args: { teamId: string; monitorId: string }): Promise<Monitor>;
|
pauseMonitor(args: { teamId: string; monitorId: string }): Promise<Monitor>;
|
||||||
|
|
||||||
// delete
|
// delete
|
||||||
@@ -72,6 +72,7 @@ export interface IMonitorService {
|
|||||||
deleteAllMonitors(args: { teamId: string }): Promise<number>;
|
deleteAllMonitors(args: { teamId: string }): Promise<number>;
|
||||||
|
|
||||||
// other
|
// other
|
||||||
|
sendTestEmail(args: { to: string }): Promise<string>;
|
||||||
exportMonitorsToJSON(args: { teamId: string }): Promise<Monitor[]>;
|
exportMonitorsToJSON(args: { teamId: string }): Promise<Monitor[]>;
|
||||||
importMonitorsFromJSON(args: { teamId: string; userId: string; monitors: any[] }): Promise<{ imported: number; errors: string[] }>;
|
importMonitorsFromJSON(args: { teamId: string; userId: string; monitors: any[] }): Promise<{ imported: number; errors: string[] }>;
|
||||||
}
|
}
|
||||||
@@ -429,7 +430,7 @@ export class MonitorService implements IMonitorService {
|
|||||||
return groups;
|
return groups;
|
||||||
};
|
};
|
||||||
|
|
||||||
editMonitor = async ({ teamId, monitorId, body }: { teamId: string; monitorId: string; body: Partial<Monitor> }) => {
|
editMonitor = async ({ teamId, monitorId, body }: { teamId: string; monitorId: string; body: Monitor }) => {
|
||||||
const editedMonitor = await this.monitorsRepository.updateById(monitorId, teamId, body);
|
const editedMonitor = await this.monitorsRepository.updateById(monitorId, teamId, body);
|
||||||
await this.jobQueue.updateJob(editedMonitor);
|
await this.jobQueue.updateJob(editedMonitor);
|
||||||
return editedMonitor;
|
return editedMonitor;
|
||||||
@@ -508,6 +509,20 @@ export class MonitorService implements IMonitorService {
|
|||||||
return deletedCount;
|
return deletedCount;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
sendTestEmail = async ({ to }: { to: string }): Promise<string> => {
|
||||||
|
const subject = "Test email from Checkmate";
|
||||||
|
const context = { testName: "Monitoring System" };
|
||||||
|
|
||||||
|
const html = await this.emailService.buildEmail("testEmailTemplate", context);
|
||||||
|
const messageId = await this.emailService.sendEmail(to, subject, html);
|
||||||
|
|
||||||
|
if (!messageId) {
|
||||||
|
throw new AppError({ message: "Failed to send test email.", service: SERVICE_NAME, method: "sendTestEmail", status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return messageId;
|
||||||
|
};
|
||||||
|
|
||||||
exportMonitorsToJSON = async ({ teamId }: { teamId: string }): Promise<any[]> => {
|
exportMonitorsToJSON = async ({ teamId }: { teamId: string }): Promise<any[]> => {
|
||||||
const monitors = await this.monitorsRepository.findByTeamId(teamId, {});
|
const monitors = await this.monitorsRepository.findByTeamId(teamId, {});
|
||||||
|
|
||||||
|
|||||||
@@ -3,5 +3,5 @@ import type { NotificationMessage } from "@/types/notificationMessage.js";
|
|||||||
|
|
||||||
export interface INotificationProvider {
|
export interface INotificationProvider {
|
||||||
sendMessage: (notification: Notification, message: NotificationMessage) => Promise<boolean>;
|
sendMessage: (notification: Notification, message: NotificationMessage) => Promise<boolean>;
|
||||||
sendTestAlert(notification: Partial<Notification>): Promise<boolean>;
|
sendTestAlert(notification: Notification): Promise<boolean>;
|
||||||
}
|
}
|
||||||
@@ -13,7 +13,7 @@ export class DiscordProvider implements INotificationProvider {
|
|||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
sendTestAlert = async (notification: Partial<Notification>) => {
|
sendTestAlert = async (notification: Notification) => {
|
||||||
if (!notification.address) {
|
if (!notification.address) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ export class EmailProvider implements INotificationProvider {
|
|||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
|
async sendTestAlert(notification: Notification): Promise<boolean> {
|
||||||
const subject = "Test notification";
|
const subject = "Test notification";
|
||||||
const html = await buildTestEmail(this.emailService);
|
const html = await buildTestEmail(this.emailService);
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ export class MatrixProvider implements INotificationProvider {
|
|||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
sendTestAlert = async (notification: Partial<Notification>) => {
|
sendTestAlert = async (notification: Notification) => {
|
||||||
const { homeserverUrl, accessToken, roomId } = notification;
|
const { homeserverUrl, accessToken, roomId } = notification;
|
||||||
if (!homeserverUrl || !accessToken || !roomId) {
|
if (!homeserverUrl || !accessToken || !roomId) {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ export class PagerDutyProvider implements INotificationProvider {
|
|||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
|
async sendTestAlert(notification: Notification): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
await got.post("https://events.pagerduty.com/v2/enqueue", {
|
await got.post("https://events.pagerduty.com/v2/enqueue", {
|
||||||
json: {
|
json: {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ export class SlackProvider implements INotificationProvider {
|
|||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
|
async sendTestAlert(notification: Notification): Promise<boolean> {
|
||||||
if (!notification.address) {
|
if (!notification.address) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ export class TeamsProvider implements INotificationProvider {
|
|||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
|
async sendTestAlert(notification: Notification): Promise<boolean> {
|
||||||
if (!notification.address) {
|
if (!notification.address) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ export class WebhookProvider implements INotificationProvider {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
sendTestAlert = async (notification: Partial<Notification>) => {
|
sendTestAlert = async (notification: Notification) => {
|
||||||
if (!notification.address) {
|
if (!notification.address) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,14 +8,14 @@ import { ILogger } from "@/utils/logger.js";
|
|||||||
import type { INotificationMessageBuilder } from "@/service/infrastructure/notificationMessageBuilder.js";
|
import type { INotificationMessageBuilder } from "@/service/infrastructure/notificationMessageBuilder.js";
|
||||||
|
|
||||||
export interface INotificationsService {
|
export interface INotificationsService {
|
||||||
createNotification: (notificationData: Partial<Notification>, userId: string, teamId: string) => Promise<Notification>;
|
createNotification: (notificationData: Partial<Notification>) => Promise<Notification>;
|
||||||
findById: (id: string, teamId: string) => Promise<Notification>;
|
findById: (id: string, teamId: string) => Promise<Notification>;
|
||||||
findNotificationsByTeamId: (teamId: string) => Promise<Notification[]>;
|
findNotificationsByTeamId: (teamId: string) => Promise<Notification[]>;
|
||||||
updateById(id: string, teamId: string, updateData: Partial<Notification>): Promise<Notification>;
|
updateById(id: string, teamId: string, updateData: Partial<Notification>): Promise<Notification>;
|
||||||
deleteById: (id: string, teamId: string) => Promise<Notification>;
|
deleteById: (id: string, teamId: string) => Promise<Notification>;
|
||||||
handleNotifications: (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse, decision: MonitorActionDecision) => Promise<boolean>;
|
handleNotifications: (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse, decision: MonitorActionDecision) => Promise<boolean>;
|
||||||
|
|
||||||
sendTestNotification: (notification: Partial<Notification>) => Promise<boolean>;
|
sendTestNotification: (notification: Notification) => Promise<boolean>;
|
||||||
testAllNotifications: (notificationIds: string[]) => Promise<boolean>;
|
testAllNotifications: (notificationIds: string[]) => Promise<boolean>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,7 +141,7 @@ export class NotificationsService implements INotificationsService {
|
|||||||
return await this.sendNotifications(monitor, monitorStatusResponse, decision);
|
return await this.sendNotifications(monitor, monitorStatusResponse, decision);
|
||||||
};
|
};
|
||||||
|
|
||||||
sendTestNotification = async (notification: Partial<Notification>) => {
|
sendTestNotification = async (notification: Notification) => {
|
||||||
switch (notification.type) {
|
switch (notification.type) {
|
||||||
case "email":
|
case "email":
|
||||||
return await this.emailProvider.sendTestAlert(notification);
|
return await this.emailProvider.sendTestAlert(notification);
|
||||||
@@ -174,9 +174,7 @@ export class NotificationsService implements INotificationsService {
|
|||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
createNotification = async (notificationData: Partial<Notification>, userId: string, teamId: string): Promise<Notification> => {
|
createNotification = async (notificationData: Partial<Notification>): Promise<Notification> => {
|
||||||
notificationData.userId = userId;
|
|
||||||
notificationData.teamId = teamId;
|
|
||||||
return await this.notificationsRepository.create(notificationData);
|
return await this.notificationsRepository.create(notificationData);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -12,8 +12,7 @@ export const supportsGeoCheck = (type: MonitorType): boolean => GeoCheckSupporte
|
|||||||
export const MonitorStatuses = ["up", "down", "paused", "initializing", "maintenance", "breached"] as const;
|
export const MonitorStatuses = ["up", "down", "paused", "initializing", "maintenance", "breached"] as const;
|
||||||
export type MonitorStatus = (typeof MonitorStatuses)[number];
|
export type MonitorStatus = (typeof MonitorStatuses)[number];
|
||||||
|
|
||||||
export const MonitorMatchMethods = ["equal", "include", "regex"] as const;
|
export type MonitorMatchMethod = "equal" | "include" | "regex" | "";
|
||||||
export type MonitorMatchMethod = (typeof MonitorMatchMethods)[number] | "";
|
|
||||||
|
|
||||||
export interface Monitor {
|
export interface Monitor {
|
||||||
id: string;
|
id: string;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
export const StatusPageTypes = ["uptime"] as const;
|
export const StatusPageTypes = ["uptime", "infrastructure"] as const;
|
||||||
export type StatusPageType = (typeof StatusPageTypes)[number];
|
export type StatusPageType = (typeof StatusPageTypes)[number];
|
||||||
|
|
||||||
export interface StatusPageLogo {
|
export interface StatusPageLogo {
|
||||||
@@ -15,7 +15,7 @@ export interface StatusPage {
|
|||||||
id: string;
|
id: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
teamId: string;
|
teamId: string;
|
||||||
type: StatusPageType;
|
type: StatusPageType[];
|
||||||
companyName: string;
|
companyName: string;
|
||||||
url: string;
|
url: string;
|
||||||
timezone?: string;
|
timezone?: string;
|
||||||
@@ -28,6 +28,7 @@ export interface StatusPage {
|
|||||||
showCharts: boolean;
|
showCharts: boolean;
|
||||||
showUptimePercentage: boolean;
|
showUptimePercentage: boolean;
|
||||||
showAdminLoginLink: boolean;
|
showAdminLoginLink: boolean;
|
||||||
|
showInfrastructure: boolean;
|
||||||
customCSS: string;
|
customCSS: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
import { booleanCoercion } from "./shared.js";
|
|
||||||
|
|
||||||
//****************************************
|
|
||||||
// Incident Validations
|
|
||||||
//****************************************
|
|
||||||
|
|
||||||
export const getIncidentsByTeamQueryValidation = z.object({
|
|
||||||
sortOrder: z.enum(["asc", "desc"]),
|
|
||||||
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]),
|
|
||||||
page: z.coerce.number().int().min(0),
|
|
||||||
rowsPerPage: z.coerce.number().int().min(1),
|
|
||||||
status: booleanCoercion.optional(),
|
|
||||||
monitorId: z.string().optional(),
|
|
||||||
resolutionType: z.enum(["manual", "automatic"]).optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const getIncidentSummaryQueryValidation = z.object({
|
|
||||||
limit: z.coerce.number().int().min(1).optional(),
|
|
||||||
});
|
|
||||||
@@ -20,4 +20,3 @@ export * from "./settingsValidation.js";
|
|||||||
export * from "./statusPageValidation.js";
|
export * from "./statusPageValidation.js";
|
||||||
export * from "./notificationValidation.js";
|
export * from "./notificationValidation.js";
|
||||||
export * from "./userValidation.js";
|
export * from "./userValidation.js";
|
||||||
export * from "./incidentValidation.js";
|
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { booleanCoercion } from "./shared.js";
|
import { booleanCoercion } from "./shared.js";
|
||||||
|
|
||||||
const dateToString = z.coerce.date().transform((d) => d.toISOString());
|
|
||||||
|
|
||||||
//****************************************
|
//****************************************
|
||||||
// Maintenance Window Validations
|
// Maintenance Window Validations
|
||||||
//****************************************
|
//****************************************
|
||||||
@@ -13,10 +11,10 @@ export const createMaintenanceWindowBodyValidation = z.object({
|
|||||||
active: z.boolean().optional(),
|
active: z.boolean().optional(),
|
||||||
duration: z.number().min(1, "Duration is required"),
|
duration: z.number().min(1, "Duration is required"),
|
||||||
durationUnit: z.enum(["seconds", "minutes", "hours", "days"]),
|
durationUnit: z.enum(["seconds", "minutes", "hours", "days"]),
|
||||||
start: dateToString,
|
start: z.coerce.date(),
|
||||||
end: dateToString,
|
end: z.coerce.date(),
|
||||||
repeat: z.number().min(0, "Repeat must be a non-negative number"),
|
repeat: z.number().min(0, "Repeat must be a non-negative number"),
|
||||||
expiry: dateToString.optional(),
|
expiry: z.coerce.date().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const getMaintenanceWindowByIdParamValidation = z.object({
|
export const getMaintenanceWindowByIdParamValidation = z.object({
|
||||||
@@ -47,10 +45,10 @@ export const editMaintenanceByIdWindowBodyValidation = z.object({
|
|||||||
active: z.boolean().optional(),
|
active: z.boolean().optional(),
|
||||||
name: z.string().optional(),
|
name: z.string().optional(),
|
||||||
repeat: z.number().optional(),
|
repeat: z.number().optional(),
|
||||||
start: dateToString.optional(),
|
start: z.coerce.date().optional(),
|
||||||
end: dateToString.optional(),
|
end: z.coerce.date().optional(),
|
||||||
expiry: dateToString.optional(),
|
expiry: z.coerce.date().optional(),
|
||||||
monitors: z.array(z.string()).optional(),
|
monitors: z.array(z.unknown()).optional(),
|
||||||
duration: z.number().optional(),
|
duration: z.number().optional(),
|
||||||
durationUnit: z.enum(["seconds", "minutes", "hours", "days"]).optional(),
|
durationUnit: z.enum(["seconds", "minutes", "hours", "days"]).optional(),
|
||||||
});
|
});
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { booleanCoercion } from "./shared.js";
|
import { booleanCoercion } from "./shared.js";
|
||||||
import { GeoContinents } from "@/types/geoCheck.js";
|
import { GeoContinents } from "@/types/geoCheck.js";
|
||||||
import { MonitorMatchMethods, MonitorTypes } from "@/types/monitor.js";
|
|
||||||
|
|
||||||
export const getMonitorByIdParamValidation = z.object({
|
export const getMonitorByIdParamValidation = z.object({
|
||||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
monitorId: z.string().min(1, "Monitor ID is required"),
|
||||||
@@ -14,7 +13,7 @@ export const getMonitorByIdQueryValidation = z.object({
|
|||||||
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]).optional(),
|
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]).optional(),
|
||||||
numToDisplay: z.coerce.number().optional(),
|
numToDisplay: z.coerce.number().optional(),
|
||||||
normalize: booleanCoercion.optional(),
|
normalize: booleanCoercion.optional(),
|
||||||
continent: z.union([z.enum(GeoContinents), z.array(z.enum(GeoContinents))]).optional(),
|
continent: z.enum(GeoContinents).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const getMonitorsByTeamIdParamValidation = z.object({});
|
export const getMonitorsByTeamIdParamValidation = z.object({});
|
||||||
@@ -26,14 +25,14 @@ export const getMonitorsByTeamIdQueryValidation = z.object({
|
|||||||
z.array(z.enum(["http", "ping", "pagespeed", "docker", "hardware", "port", "game", "grpc", "websocket"])),
|
z.array(z.enum(["http", "ping", "pagespeed", "docker", "hardware", "port", "game", "grpc", "websocket"])),
|
||||||
])
|
])
|
||||||
.optional(),
|
.optional(),
|
||||||
filter: z.union([z.string(), z.literal("")]).optional(),
|
filter: z.union([z.string(), z.literal(""), z.null()]).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const getMonitorsWithChecksQueryValidation = z.object({
|
export const getMonitorsWithChecksQueryValidation = z.object({
|
||||||
limit: z.coerce.number().int().min(1).max(100).optional(),
|
limit: z.coerce.number().int().min(1).max(100).optional(),
|
||||||
page: z.coerce.number().int().min(0).optional(),
|
page: z.coerce.number().int().min(0).optional(),
|
||||||
rowsPerPage: z.coerce.number().int().min(1).max(100).optional(),
|
rowsPerPage: z.coerce.number().int().min(1).max(100).optional(),
|
||||||
filter: z.union([z.string(), z.literal("")]).optional(),
|
filter: z.union([z.string(), z.literal(""), z.null()]).optional(),
|
||||||
field: z.string().optional(),
|
field: z.string().optional(),
|
||||||
order: z.enum(["asc", "desc"]).optional(),
|
order: z.enum(["asc", "desc"]).optional(),
|
||||||
type: z
|
type: z
|
||||||
@@ -52,8 +51,8 @@ export const getCertificateParamValidation = z.object({
|
|||||||
export const createMonitorBodyValidation = z.object({
|
export const createMonitorBodyValidation = z.object({
|
||||||
_id: z.string().optional(),
|
_id: z.string().optional(),
|
||||||
name: z.string().min(1, "Name is required"),
|
name: z.string().min(1, "Name is required"),
|
||||||
description: z.union([z.string(), z.literal("")]).optional(),
|
description: z.union([z.string(), z.null(), z.literal("")]).optional(),
|
||||||
type: z.enum(MonitorTypes, "Invalid monitor type"),
|
type: z.string().min(1, "Type is required"),
|
||||||
statusWindowSize: z.number().min(1).max(20).default(5),
|
statusWindowSize: z.number().min(1).max(20).default(5),
|
||||||
statusWindowThreshold: z.number().min(1).max(100).default(60),
|
statusWindowThreshold: z.number().min(1).max(100).default(60),
|
||||||
url: z.string().min(1, "URL is required"),
|
url: z.string().min(1, "URL is required"),
|
||||||
@@ -70,7 +69,7 @@ export const createMonitorBodyValidation = z.object({
|
|||||||
secret: z.string().optional(),
|
secret: z.string().optional(),
|
||||||
jsonPath: z.union([z.string(), z.literal("")]).optional(),
|
jsonPath: z.union([z.string(), z.literal("")]).optional(),
|
||||||
expectedValue: z.union([z.string(), z.literal("")]).optional(),
|
expectedValue: z.union([z.string(), z.literal("")]).optional(),
|
||||||
matchMethod: z.union([z.enum(MonitorMatchMethods), z.literal("")]).optional(),
|
matchMethod: z.union([z.string(), z.null(), z.literal("")]).optional(),
|
||||||
gameId: z.union([z.string(), z.literal("")]).optional(),
|
gameId: z.union([z.string(), z.literal("")]).optional(),
|
||||||
grpcServiceName: z.union([z.string(), z.literal("")]).default(""),
|
grpcServiceName: z.union([z.string(), z.literal("")]).default(""),
|
||||||
selectedDisks: z.array(z.string()).optional(),
|
selectedDisks: z.array(z.string()).optional(),
|
||||||
@@ -82,11 +81,11 @@ export const createMonitorBodyValidation = z.object({
|
|||||||
|
|
||||||
export const editMonitorBodyValidation = z.object({
|
export const editMonitorBodyValidation = z.object({
|
||||||
name: z.string().optional(),
|
name: z.string().optional(),
|
||||||
type: z.enum(MonitorTypes).optional(),
|
type: z.string().optional(),
|
||||||
url: z.string().optional(),
|
url: z.string().optional(),
|
||||||
statusWindowSize: z.number().min(1).max(20).default(5),
|
statusWindowSize: z.number().min(1).max(20).default(5),
|
||||||
statusWindowThreshold: z.number().min(1).max(100).default(60),
|
statusWindowThreshold: z.number().min(1).max(100).default(60),
|
||||||
description: z.union([z.string(), z.literal("")]).optional(),
|
description: z.union([z.string(), z.null(), z.literal("")]).optional(),
|
||||||
interval: z.number().optional(),
|
interval: z.number().optional(),
|
||||||
notifications: z.array(z.string()).optional(),
|
notifications: z.array(z.string()).optional(),
|
||||||
secret: z.string().optional(),
|
secret: z.string().optional(),
|
||||||
@@ -94,7 +93,7 @@ export const editMonitorBodyValidation = z.object({
|
|||||||
useAdvancedMatching: z.boolean().optional(),
|
useAdvancedMatching: z.boolean().optional(),
|
||||||
jsonPath: z.union([z.string(), z.literal("")]).optional(),
|
jsonPath: z.union([z.string(), z.literal("")]).optional(),
|
||||||
expectedValue: z.union([z.string(), z.literal("")]).optional(),
|
expectedValue: z.union([z.string(), z.literal("")]).optional(),
|
||||||
matchMethod: z.union([z.enum(MonitorMatchMethods), z.literal("")]).optional(),
|
matchMethod: z.union([z.string(), z.null(), z.literal("")]).optional(),
|
||||||
port: z.number().min(1).max(65535).optional(),
|
port: z.number().min(1).max(65535).optional(),
|
||||||
cpuAlertThreshold: z.number().optional(),
|
cpuAlertThreshold: z.number().optional(),
|
||||||
memoryAlertThreshold: z.number().optional(),
|
memoryAlertThreshold: z.number().optional(),
|
||||||
@@ -113,62 +112,6 @@ export const pauseMonitorParamValidation = z.object({
|
|||||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
monitorId: z.string().min(1, "Monitor ID is required"),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const getUptimeDetailsByIdParamValidation = z.object({
|
|
||||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const getUptimeDetailsByIdQueryValidation = z.object({
|
|
||||||
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]),
|
|
||||||
normalize: booleanCoercion.optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const importedMonitorSchema = z.object({
|
|
||||||
id: z.string().optional(),
|
|
||||||
userId: z.string().optional(),
|
|
||||||
teamId: z.string().optional(),
|
|
||||||
name: z.string().min(1, "Name is required"),
|
|
||||||
description: z.union([z.string(), z.literal("")]).optional(),
|
|
||||||
status: z.enum(["up", "down", "paused", "initializing", "maintenance", "breached"]).optional(),
|
|
||||||
statusWindow: z.array(z.boolean()).optional(),
|
|
||||||
statusWindowSize: z.number().optional(),
|
|
||||||
statusWindowThreshold: z.number().optional(),
|
|
||||||
type: z.enum(MonitorTypes, "Invalid monitor type"),
|
|
||||||
ignoreTlsErrors: z.boolean().optional(),
|
|
||||||
useAdvancedMatching: z.boolean().optional(),
|
|
||||||
jsonPath: z.union([z.string(), z.literal("")]).optional(),
|
|
||||||
expectedValue: z.union([z.string(), z.literal("")]).optional(),
|
|
||||||
matchMethod: z.union([z.enum(MonitorMatchMethods), z.literal("")]).optional(),
|
|
||||||
url: z.string().min(1, "URL is required"),
|
|
||||||
port: z.number().optional(),
|
|
||||||
isActive: z.boolean().optional(),
|
|
||||||
interval: z.number().optional(),
|
|
||||||
uptimePercentage: z.number().optional(),
|
|
||||||
notifications: z.array(z.string()).optional(),
|
|
||||||
secret: z.string().optional(),
|
|
||||||
cpuAlertThreshold: z.number().optional(),
|
|
||||||
cpuAlertCounter: z.number().optional(),
|
|
||||||
memoryAlertThreshold: z.number().optional(),
|
|
||||||
memoryAlertCounter: z.number().optional(),
|
|
||||||
diskAlertThreshold: z.number().optional(),
|
|
||||||
diskAlertCounter: z.number().optional(),
|
|
||||||
tempAlertThreshold: z.number().optional(),
|
|
||||||
tempAlertCounter: z.number().optional(),
|
|
||||||
selectedDisks: z.array(z.string()).optional(),
|
|
||||||
gameId: z.union([z.string(), z.literal("")]).optional(),
|
|
||||||
grpcServiceName: z.union([z.string(), z.literal("")]).optional(),
|
|
||||||
group: z.union([z.string(), z.null()]).optional(),
|
|
||||||
geoCheckEnabled: z.boolean().optional(),
|
|
||||||
geoCheckLocations: z.array(z.enum(GeoContinents)).optional(),
|
|
||||||
geoCheckInterval: z.number().optional(),
|
|
||||||
recentChecks: z.array(z.unknown()).optional(),
|
|
||||||
createdAt: z.string().optional(),
|
|
||||||
updatedAt: z.string().optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const importMonitorsBodyValidation = z.object({
|
|
||||||
monitors: z.array(importedMonitorSchema).min(1, "At least one monitor is required"),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const getHardwareDetailsByIdParamValidation = z.object({
|
export const getHardwareDetailsByIdParamValidation = z.object({
|
||||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
monitorId: z.string().min(1, "Monitor ID is required"),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -67,22 +67,6 @@ export const createNotificationBodyValidation = z.discriminatedUnion("type", [
|
|||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export const testNotificationBodyValidation = createNotificationBodyValidation;
|
|
||||||
|
|
||||||
export const deleteNotificationParamValidation = z.object({
|
|
||||||
id: z.string().min(1, "Notification ID is required"),
|
|
||||||
});
|
|
||||||
export const getNotificationByIdParamValidation = z.object({
|
|
||||||
id: z.string().min(1, "Notification ID is required"),
|
|
||||||
});
|
|
||||||
export const editNotificationParamValidation = z.object({
|
|
||||||
id: z.string().min(1, "Notification ID is required"),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const testAllNotificationsBodyValidation = z.object({
|
|
||||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const sendTestEmailBodyValidation = z.object({
|
export const sendTestEmailBodyValidation = z.object({
|
||||||
to: z.string().min(1, "To field is required"),
|
to: z.string().min(1, "To field is required"),
|
||||||
systemEmailHost: z.string().optional(),
|
systemEmailHost: z.string().optional(),
|
||||||
|
|||||||
@@ -10,13 +10,13 @@ export const getStatusPageParamValidation = z.object({
|
|||||||
});
|
});
|
||||||
|
|
||||||
export const getStatusPageQueryValidation = z.object({
|
export const getStatusPageQueryValidation = z.object({
|
||||||
type: z.literal("uptime"),
|
type: z.array(z.enum(["uptime", "infrastructure"])),
|
||||||
timeFrame: z.coerce.number().optional(),
|
timeFrame: z.coerce.number().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const createStatusPageBodyValidation = z
|
export const createStatusPageBodyValidation = z
|
||||||
.object({
|
.object({
|
||||||
type: z.literal("uptime"),
|
type: z.array(z.enum(["uptime", "infrastructure"])),
|
||||||
companyName: z.string().min(1, "Company name is required"),
|
companyName: z.string().min(1, "Company name is required"),
|
||||||
url: z.string().regex(/^[a-zA-Z0-9_-]+$/, {
|
url: z.string().regex(/^[a-zA-Z0-9_-]+$/, {
|
||||||
message: "URL can only contain letters, numbers, underscores, and hyphens",
|
message: "URL can only contain letters, numbers, underscores, and hyphens",
|
||||||
|
|||||||
Reference in new issue
Block a user