Merge pull request #3975 from nikhilsaxena04/feat/status-page-incident-history

feat: add clickthrough incident history to public status page (#3972)
This commit is contained in:
Alexander Holliday authored and GitHub committed 2026-09-22 10:15:57 -07:00
commit a5e66318b5
39 files changed
+427 -44

No files matched your search

+2 -22
View File
@@ -93,7 +93,6 @@
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/code-frame": "^7.29.7", "@babel/code-frame": "^7.29.7",
"@babel/generator": "^7.29.7", "@babel/generator": "^7.29.7",
@@ -409,7 +408,6 @@
"node_modules/@emotion/react": { "node_modules/@emotion/react": {
"version": "11.14.0", "version": "11.14.0",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.3", "@babel/runtime": "^7.18.3",
"@emotion/babel-plugin": "^11.13.5", "@emotion/babel-plugin": "^11.13.5",
@@ -447,7 +445,6 @@
"node_modules/@emotion/styled": { "node_modules/@emotion/styled": {
"version": "11.14.1", "version": "11.14.1",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.3", "@babel/runtime": "^7.18.3",
"@emotion/babel-plugin": "^11.13.5", "@emotion/babel-plugin": "^11.13.5",
@@ -1236,7 +1233,6 @@
"node_modules/@mui/material": { "node_modules/@mui/material": {
"version": "7.3.7", "version": "7.3.7",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/runtime": "^7.28.4", "@babel/runtime": "^7.28.4",
"@mui/core-downloads-tracker": "^7.3.7", "@mui/core-downloads-tracker": "^7.3.7",
@@ -1341,7 +1337,6 @@
"node_modules/@mui/system": { "node_modules/@mui/system": {
"version": "7.3.7", "version": "7.3.7",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/runtime": "^7.28.4", "@babel/runtime": "^7.28.4",
"@mui/private-theming": "^7.3.7", "@mui/private-theming": "^7.3.7",
@@ -2386,7 +2381,6 @@
"version": "24.5.2", "version": "24.5.2",
"devOptional": true, "devOptional": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"undici-types": "~7.12.0" "undici-types": "~7.12.0"
} }
@@ -2402,7 +2396,6 @@
"node_modules/@types/react": { "node_modules/@types/react": {
"version": "18.3.27", "version": "18.3.27",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@types/prop-types": "*", "@types/prop-types": "*",
"csstype": "^3.2.2" "csstype": "^3.2.2"
@@ -2493,7 +2486,6 @@
"integrity": "sha512-4Z+L8I2OqhZV8qA132M4wNL30ypZGYOQVBfMgxDH/K5UX0PNqTu1c6za9ST5r9+tavvHiTWmBnKzpCJ/GlVFtg==", "integrity": "sha512-4Z+L8I2OqhZV8qA132M4wNL30ypZGYOQVBfMgxDH/K5UX0PNqTu1c6za9ST5r9+tavvHiTWmBnKzpCJ/GlVFtg==",
"dev": true, "dev": true,
"license": "BSD-2-Clause", "license": "BSD-2-Clause",
"peer": true,
"dependencies": { "dependencies": {
"@typescript-eslint/scope-manager": "7.18.0", "@typescript-eslint/scope-manager": "7.18.0",
"@typescript-eslint/types": "7.18.0", "@typescript-eslint/types": "7.18.0",
@@ -2774,7 +2766,6 @@
"version": "8.15.0", "version": "8.15.0",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"acorn": "bin/acorn" "acorn": "bin/acorn"
}, },
@@ -3131,7 +3122,6 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"baseline-browser-mapping": "^2.10.42", "baseline-browser-mapping": "^2.10.42",
"caniuse-lite": "^1.0.30001800", "caniuse-lite": "^1.0.30001800",
@@ -3575,8 +3565,7 @@
}, },
"node_modules/dayjs": { "node_modules/dayjs": {
"version": "1.11.13", "version": "1.11.13",
"license": "MIT", "license": "MIT"
"peer": true
}, },
"node_modules/debug": { "node_modules/debug": {
"version": "4.4.3", "version": "4.4.3",
@@ -3975,7 +3964,6 @@
"version": "8.57.1", "version": "8.57.1",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.6.1", "@eslint-community/regexpp": "^4.6.1",
@@ -4788,7 +4776,6 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/runtime": "^7.27.6" "@babel/runtime": "^7.27.6"
}, },
@@ -5600,7 +5587,6 @@
"resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-5.19.0.tgz", "resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-5.19.0.tgz",
"integrity": "sha512-REhYUN8gNP3HlcIZS6QU2uy8iovl31cXsrNDkCcqWSQbCkcpdYLczqDz5PVIwNH42UQNyvukjes/RoHPDrOUmQ==", "integrity": "sha512-REhYUN8gNP3HlcIZS6QU2uy8iovl31cXsrNDkCcqWSQbCkcpdYLczqDz5PVIwNH42UQNyvukjes/RoHPDrOUmQ==",
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"peer": true,
"dependencies": { "dependencies": {
"@mapbox/geojson-rewind": "^0.5.2", "@mapbox/geojson-rewind": "^0.5.2",
"@mapbox/jsonlint-lines-primitives": "^2.0.2", "@mapbox/jsonlint-lines-primitives": "^2.0.2",
@@ -6382,7 +6368,6 @@
"node_modules/react-dom": { "node_modules/react-dom": {
"version": "18.3.1", "version": "18.3.1",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"loose-envify": "^1.1.0", "loose-envify": "^1.1.0",
"scheduler": "^0.23.2" "scheduler": "^0.23.2"
@@ -6394,7 +6379,6 @@
"node_modules/react-hook-form": { "node_modules/react-hook-form": {
"version": "7.71.1", "version": "7.71.1",
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=18.0.0" "node": ">=18.0.0"
}, },
@@ -6598,8 +6582,7 @@
}, },
"node_modules/redux": { "node_modules/redux": {
"version": "5.0.1", "version": "5.0.1",
"license": "MIT", "license": "MIT"
"peer": true
}, },
"node_modules/redux-persist": { "node_modules/redux-persist": {
"version": "6.0.0", "version": "6.0.0",
@@ -6749,7 +6732,6 @@
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz",
"integrity": "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA==", "integrity": "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@types/estree": "1.0.9" "@types/estree": "1.0.9"
}, },
@@ -7591,7 +7573,6 @@
"version": "5.9.3", "version": "5.9.3",
"devOptional": true, "devOptional": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"bin": { "bin": {
"tsc": "bin/tsc", "tsc": "bin/tsc",
"tsserver": "bin/tsserver" "tsserver": "bin/tsserver"
@@ -7729,7 +7710,6 @@
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
"integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"esbuild": "^0.25.0", "esbuild": "^0.25.0",
"fdir": "^6.4.4", "fdir": "^6.4.4",
@@ -14,6 +14,7 @@ import {
import type { StatusPageThemeTokens } from "@/Pages/StatusPage/Status/themes/tokens"; import type { StatusPageThemeTokens } from "@/Pages/StatusPage/Status/themes/tokens";
import { ThemedHeatmap } from "@/Pages/StatusPage/Status/themes/shared/ThemedHeatmap"; import { ThemedHeatmap } from "@/Pages/StatusPage/Status/themes/shared/ThemedHeatmap";
import { ThemedHistogram } from "@/Pages/StatusPage/Status/themes/shared/ThemedHistogram"; import { ThemedHistogram } from "@/Pages/StatusPage/Status/themes/shared/ThemedHistogram";
import { IncidentModal } from "@/Pages/StatusPage/Status/themes/shared/IncidentModal";
import { import {
ThemedInfrastructure, ThemedInfrastructure,
type GaugeFillLevel, type GaugeFillLevel,
@@ -116,6 +117,8 @@ export const BaseStatusPage = ({
[config, tokens, mode] [config, tokens, mode]
); );
const [chartMode, setChartMode] = useState<"heatmap" | "histogram">("heatmap"); const [chartMode, setChartMode] = useState<"heatmap" | "histogram">("heatmap");
const [selectedMonitorId, setSelectedMonitorId] = useState<string | null>(null);
const [selectedDate, setSelectedDate] = useState<string | null>(null);
const overall = resolveOverallStatus(monitors, t, config.overallStatusOptions); const overall = resolveOverallStatus(monitors, t, config.overallStatusOptions);
const logoSrc = statusPage.logo?.data const logoSrc = statusPage.logo?.data
@@ -306,6 +309,10 @@ export const BaseStatusPage = ({
cells={cells} cells={cells}
containerSx={styles.heatmap} containerSx={styles.heatmap}
cellSx={styles.heatmapCell} cellSx={styles.heatmapCell}
onCellClick={(date) => {
setSelectedMonitorId(monitor.id);
setSelectedDate(date);
}}
/> />
) : ( ) : (
<ThemedHistogram <ThemedHistogram
@@ -313,6 +320,10 @@ export const BaseStatusPage = ({
containerSx={styles.histogram} containerSx={styles.histogram}
barSx={styles.bar} barSx={styles.bar}
statsSx={styles.chartStats} statsSx={styles.chartStats}
onCellClick={(date) => {
setSelectedMonitorId(monitor.id);
setSelectedDate(date);
}}
/> />
))} ))}
</Box> </Box>
@@ -333,6 +344,16 @@ export const BaseStatusPage = ({
Checkmate Checkmate
</a> </a>
</Box> </Box>
<IncidentModal
url={statusPage.url}
monitorId={selectedMonitorId}
date={selectedDate}
timezone={bucketTimezone}
onClose={() => {
setSelectedMonitorId(null);
setSelectedDate(null);
}}
/>
</Box> </Box>
); );
}; };
@@ -25,6 +25,7 @@ export interface ChartCell {
responseTime: number; // 0 for empty cells responseTime: number; // 0 for empty cells
tooltip: React.ReactNode | null; tooltip: React.ReactNode | null;
ariaLabel: string; ariaLabel: string;
date: string | null;
} }
const DAY_DOWN_THRESHOLD = 0.5; const DAY_DOWN_THRESHOLD = 0.5;
@@ -61,7 +62,7 @@ export const classifyResponseTime = (
return "fast"; return "fast";
}; };
const emptyCell = (key: string): ChartCell => ({ const emptyCell = (key: string, date: string | null = null): ChartCell => ({
key, key,
barKind: "empty", barKind: "empty",
heatKind: "empty", heatKind: "empty",
@@ -70,6 +71,7 @@ const emptyCell = (key: string): ChartCell => ({
tooltip: null, tooltip: null,
ariaLabel: "", ariaLabel: "",
severity: 0, severity: 0,
date,
}); });
const padCells = (cells: ChartCell[], length: number): ChartCell[] => [ const padCells = (cells: ChartCell[], length: number): ChartCell[] => [
@@ -92,6 +94,7 @@ export const checksToCells = (checks: CheckSnapshot[]): ChartCell[] => {
tooltip: <ThemedChartTooltip check={check} />, tooltip: <ThemedChartTooltip check={check} />,
ariaLabel: `${formatMs(check.responseTime)}, ${check.status ? "up" : "down"}`, ariaLabel: `${formatMs(check.responseTime)}, ${check.status ? "up" : "down"}`,
severity: 0, severity: 0,
date: null,
}) })
); );
return padCells(cells, MAX_RECENT_CHECKS); return padCells(cells, MAX_RECENT_CHECKS);
@@ -108,7 +111,7 @@ export const dailyBucketsToCells = (
const enumerated = enumerateDays(days, bucketTimezone); const enumerated = enumerateDays(days, bucketTimezone);
return enumerated.map((date) => { return enumerated.map((date) => {
const bucket = byDate.get(date); const bucket = byDate.get(date);
if (!bucket) return emptyCell(`day-${date}`); if (!bucket) return emptyCell(`day-${date}`, date);
const upRatio = bucket.upChecks / bucket.totalChecks; const upRatio = bucket.upChecks / bucket.totalChecks;
const barKind = classifyDay(bucket, upRatio); const barKind = classifyDay(bucket, upRatio);
@@ -132,6 +135,7 @@ export const dailyBucketsToCells = (
date, date,
uptime: formatPercentage(bucket.upChecks / bucket.totalChecks), uptime: formatPercentage(bucket.upChecks / bucket.totalChecks),
}), }),
date,
}; };
}); });
}; };
@@ -0,0 +1,111 @@
import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import Typography from "@mui/material/Typography";
import Stack from "@mui/material/Stack";
import IconButton from "@mui/material/IconButton";
import { X as XIcon } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useGet } from "@/Hooks/UseApi";
import { useTheme } from "@mui/material";
import { SPACING } from "@/Utils/Theme/constants";
import { formatDateWithTz } from "@/Utils/TimeUtils";
import type { Incident } from "@/Types/Incident";
interface IncidentModalProps {
url: string;
monitorId: string | null;
date: string | null;
timezone: string;
onClose: () => void;
}
export const IncidentModal = ({
url,
monitorId,
date,
timezone,
onClose,
}: IncidentModalProps) => {
const theme = useTheme();
const { t } = useTranslation();
const open = Boolean(monitorId && date);
const { data, isLoading, error } = useGet<{ incidents: Incident[] }>(
open ? `/status-page/${url}/incidents/${monitorId}?date=${date}` : null,
{},
{ revalidateOnFocus: false, keepPreviousData: true }
);
return (
<Dialog
open={open}
onClose={onClose}
maxWidth="sm"
fullWidth
>
<DialogTitle
sx={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}
>
{t("pages.statusPages.monitorsList.incidents.modalTitle", { date })} ({timezone})
<IconButton
onClick={onClose}
size="small"
aria-label="close"
>
<XIcon size={20} />
</IconButton>
</DialogTitle>
<DialogContent>
{isLoading ? (
<Typography mt={SPACING.SM}>
{t("pages.statusPages.monitorsList.incidents.loading")}
</Typography>
) : error ? (
<Typography
mt={SPACING.SM}
color={theme.palette.error.main}
>
{t("pages.statusPages.monitorsList.incidents.errorLoading")}
</Typography>
) : data?.incidents && data.incidents.length > 0 ? (
<Stack
gap={SPACING.LG}
mt={SPACING.SM}
>
{data.incidents.map((incident) => (
<Stack
key={incident.id}
p={SPACING.LG}
border={1}
borderColor="divider"
borderRadius={theme.shape.borderRadius}
>
<Typography
variant="subtitle2"
fontWeight="bold"
>
{incident.message ||
(incident.statusCode ? `Error ${incident.statusCode}` : "Incident")}
</Typography>
<Typography
variant="body2"
color={theme.palette.text.secondary}
>
{formatDateWithTz(incident.startTime, "h:mm A", timezone)} -{" "}
{incident.endTime
? formatDateWithTz(incident.endTime, "h:mm A", timezone)
: t("pages.statusPages.monitorsList.incidents.ongoing")}
</Typography>
</Stack>
))}
</Stack>
) : (
<Typography mt={SPACING.SM}>
{t("pages.statusPages.monitorsList.incidents.noIncidents")}
</Typography>
)}
</DialogContent>
</Dialog>
);
};
@@ -2,6 +2,8 @@ import Tooltip from "@mui/material/Tooltip";
import Box from "@mui/material/Box"; import Box from "@mui/material/Box";
import type { SxProps, Theme } from "@mui/material/styles"; import type { SxProps, Theme } from "@mui/material/styles";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { mergeSx } from "@/Pages/StatusPage/Status/themes/shared/sx";
import type { import type {
ChartCell, ChartCell,
HeatCellKind, HeatCellKind,
@@ -11,17 +13,15 @@ interface Props {
cells: ChartCell[]; cells: ChartCell[];
containerSx: SxProps<Theme>; containerSx: SxProps<Theme>;
cellSx: (kind: HeatCellKind, severity?: number) => SxProps<Theme>; cellSx: (kind: HeatCellKind, severity?: number) => SxProps<Theme>;
onCellClick?: (date: string) => void;
} }
export const ThemedHeatmap = ({ cells, containerSx, cellSx }: Props) => { export const ThemedHeatmap = ({ cells, containerSx, cellSx, onCellClick }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<Box <Box
sx={[ sx={mergeSx(containerSx, { gridTemplateColumns: `repeat(${cells.length}, 1fr)` })}
...(Array.isArray(containerSx) ? containerSx : [containerSx]),
{ gridTemplateColumns: `repeat(${cells.length}, 1fr)` },
]}
role="img" role="img"
aria-label={t("pages.statusPages.monitorsList.chart.heatmapAria")} aria-label={t("pages.statusPages.monitorsList.chart.heatmapAria")}
> >
@@ -30,7 +30,15 @@ export const ThemedHeatmap = ({ cells, containerSx, cellSx }: Props) => {
return ( return (
<Box <Box
key={cell.key} key={cell.key}
sx={cellSx("empty")} sx={mergeSx(
cellSx("empty"),
!!cell.date && !!onCellClick ? { cursor: "pointer" } : undefined
)}
onClick={() => {
if (cell.date && onCellClick) {
onCellClick(cell.date);
}
}}
/> />
); );
} }
@@ -42,8 +50,16 @@ export const ThemedHeatmap = ({ cells, containerSx, cellSx }: Props) => {
placement="top" placement="top"
> >
<Box <Box
sx={cellSx(cell.heatKind, cell.severity)} sx={mergeSx(
cellSx(cell.heatKind, cell.severity),
!!cell.date && !!onCellClick ? { cursor: "pointer" } : undefined
)}
aria-label={cell.ariaLabel} aria-label={cell.ariaLabel}
onClick={() => {
if (cell.date && onCellClick) {
onCellClick(cell.date);
}
}}
/> />
</Tooltip> </Tooltip>
); );
@@ -5,6 +5,8 @@ import Stack from "@mui/material/Stack";
import type { SxProps, Theme } from "@mui/material/styles"; import type { SxProps, Theme } from "@mui/material/styles";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { formatMs } from "@/Utils/TimeUtils"; import { formatMs } from "@/Utils/TimeUtils";
import { mergeSx } from "@/Pages/StatusPage/Status/themes/shared/sx";
import type { import type {
BarKind, BarKind,
ChartCell, ChartCell,
@@ -16,6 +18,7 @@ interface Props {
barSx: (kind: BarKind, heightPct: number, severity?: number) => SxProps<Theme>; barSx: (kind: BarKind, heightPct: number, severity?: number) => SxProps<Theme>;
statsSx: SxProps<Theme>; statsSx: SxProps<Theme>;
statsGap?: number; statsGap?: number;
onCellClick?: (date: string) => void;
} }
export const ThemedHistogram = ({ export const ThemedHistogram = ({
@@ -24,6 +27,7 @@ export const ThemedHistogram = ({
barSx, barSx,
statsSx, statsSx,
statsGap = 1, statsGap = 1,
onCellClick,
}: Props) => { }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -39,17 +43,22 @@ export const ThemedHistogram = ({
return ( return (
<Stack gap={statsGap}> <Stack gap={statsGap}>
<Box <Box
sx={[ sx={mergeSx(containerSx, { gridTemplateColumns: `repeat(${cells.length}, 1fr)` })}
...(Array.isArray(containerSx) ? containerSx : [containerSx]),
{ gridTemplateColumns: `repeat(${cells.length}, 1fr)` },
]}
> >
{cells.map((cell) => { {cells.map((cell) => {
if (cell.barKind === "empty") { if (cell.barKind === "empty") {
return ( return (
<Box <Box
key={cell.key} key={cell.key}
sx={barSx("empty", cell.heightPct)} sx={mergeSx(
barSx("empty", cell.heightPct),
!!cell.date && !!onCellClick ? { cursor: "pointer" } : undefined
)}
onClick={() => {
if (cell.date && onCellClick) {
onCellClick(cell.date);
}
}}
/> />
); );
} }
@@ -61,8 +70,16 @@ export const ThemedHistogram = ({
placement="top" placement="top"
> >
<Box <Box
sx={barSx(cell.barKind, cell.heightPct, cell.severity)} sx={mergeSx(
barSx(cell.barKind, cell.heightPct, cell.severity),
!!cell.date && !!onCellClick ? { cursor: "pointer" } : undefined
)}
aria-label={cell.ariaLabel} aria-label={cell.ariaLabel}
onClick={() => {
if (cell.date && onCellClick) {
onCellClick(cell.date);
}
}}
/> />
</Tooltip> </Tooltip>
); );
@@ -0,0 +1,16 @@
import type { SxProps, Theme } from "@mui/material/styles";
export const mergeSx = (
...styles: Array<SxProps<Theme> | false | null | undefined>
): SxProps<Theme> => {
const result: SxProps<Theme>[] = [];
for (const style of styles) {
if (!style) continue;
if (Array.isArray(style)) {
result.push(...(style.filter(Boolean) as SxProps<Theme>[]));
} else {
result.push(style);
}
}
return result as SxProps<Theme>;
};
+3
View File
@@ -1377,6 +1377,9 @@
"maintenance": "صيانة", "maintenance": "صيانة",
"paused": "متوقف مؤقتاً", "paused": "متوقف مؤقتاً",
"up": "قيد التشغيل" "up": "قيد التشغيل"
},
"incidents": {
"errorLoading": "فشل تحميل الحوادث."
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1377,6 +1377,9 @@
"uptime": { "uptime": {
"title": "Temps en línia", "title": "Temps en línia",
"responseTime": "Temps de resposta" "responseTime": "Temps de resposta"
},
"incidents": {
"errorLoading": "No s'han pogut carregar les incidències."
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1377,6 +1377,9 @@
"maintenance": "Údržba", "maintenance": "Údržba",
"paused": "Pozastaveno", "paused": "Pozastaveno",
"up": "V provozu" "up": "V provozu"
},
"incidents": {
"errorLoading": "Nepodařilo se načíst incidenty."
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1378,6 +1378,9 @@
"maintenance": "Wartung", "maintenance": "Wartung",
"paused": "Pausiert", "paused": "Pausiert",
"up": "Betriebsbereit" "up": "Betriebsbereit"
},
"incidents": {
"errorLoading": "Vorfälle konnten nicht geladen werden."
} }
}, },
"statusBar": { "statusBar": {
+7
View File
@@ -1712,6 +1712,13 @@
"uptime": { "uptime": {
"title": "Uptime", "title": "Uptime",
"responseTime": "Response time" "responseTime": "Response time"
},
"incidents": {
"modalTitle": "Incidents for {{date}}",
"loading": "Loading...",
"noIncidents": "No incidents reported for this day.",
"ongoing": "Ongoing",
"errorLoading": "Failed to load incidents."
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1377,6 +1377,9 @@
"maintenance": "Mantenimiento", "maintenance": "Mantenimiento",
"paused": "Pausado", "paused": "Pausado",
"up": "Operativo" "up": "Operativo"
},
"incidents": {
"errorLoading": "Error al cargar incidentes."
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1377,6 +1377,9 @@
"maintenance": "Huolto", "maintenance": "Huolto",
"paused": "Keskeytetty", "paused": "Keskeytetty",
"up": "Toiminnassa" "up": "Toiminnassa"
},
"incidents": {
"errorLoading": "Häiriöiden lataaminen epäonnistui."
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1377,6 +1377,9 @@
"maintenance": "Maintenance", "maintenance": "Maintenance",
"paused": "En pause", "paused": "En pause",
"up": "Opérationnel" "up": "Opérationnel"
},
"incidents": {
"errorLoading": "Échec du chargement des incidents."
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1473,6 +1473,9 @@
"uptime": { "uptime": {
"title": "Uptime", "title": "Uptime",
"responseTime": "Tempo di risposta" "responseTime": "Tempo di risposta"
},
"incidents": {
"errorLoading": "Impossibile caricare gli incidenti."
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1377,6 +1377,9 @@
"maintenance": "メンテナンス", "maintenance": "メンテナンス",
"paused": "一時停止中", "paused": "一時停止中",
"up": "稼働中" "up": "稼働中"
},
"incidents": {
"errorLoading": "インシデントの読み込みに失敗しました。"
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1584,6 +1584,9 @@
"uptime": { "uptime": {
"responseTime": "Czas odpowiedzi", "responseTime": "Czas odpowiedzi",
"title": "Czas pracy" "title": "Czas pracy"
},
"incidents": {
"errorLoading": "Nie udało się załadować incydentów."
} }
}, },
"preview": { "preview": {
+3
View File
@@ -1377,6 +1377,9 @@
"maintenance": "Manutenção", "maintenance": "Manutenção",
"paused": "Pausado", "paused": "Pausado",
"up": "Operacional" "up": "Operacional"
},
"incidents": {
"errorLoading": "Falha ao carregar incidentes."
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1377,6 +1377,9 @@
"maintenance": "Обслуживание", "maintenance": "Обслуживание",
"paused": "Приостановлено", "paused": "Приостановлено",
"up": "Работает" "up": "Работает"
},
"incidents": {
"errorLoading": "Не удалось загрузить инциденты."
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1377,6 +1377,9 @@
"maintenance": "การบำรุงรักษา", "maintenance": "การบำรุงรักษา",
"paused": "หยุดชั่วคราว", "paused": "หยุดชั่วคราว",
"up": "ใช้งานได้" "up": "ใช้งานได้"
},
"incidents": {
"errorLoading": "ไม่สามารถโหลดเหตุการณ์ได้"
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1377,6 +1377,9 @@
"maintenance": "Bakım", "maintenance": "Bakım",
"paused": "Duraklatıldı", "paused": "Duraklatıldı",
"up": "Çalışıyor" "up": "Çalışıyor"
},
"incidents": {
"errorLoading": "Olaylar yüklenemedi."
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1377,6 +1377,9 @@
"maintenance": "Обслуговування", "maintenance": "Обслуговування",
"paused": "Призупинено", "paused": "Призупинено",
"up": "Працює" "up": "Працює"
},
"incidents": {
"errorLoading": "Не вдалося завантажити інциденти."
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1377,6 +1377,9 @@
"maintenance": "Bảo trì", "maintenance": "Bảo trì",
"paused": "Tạm dừng", "paused": "Tạm dừng",
"up": "Hoạt động" "up": "Hoạt động"
},
"incidents": {
"errorLoading": "Không thể tải sự cố."
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1378,6 +1378,9 @@
"maintenance": "维护中", "maintenance": "维护中",
"paused": "已暂停", "paused": "已暂停",
"up": "运行中" "up": "运行中"
},
"incidents": {
"errorLoading": "无法加载事件。"
} }
}, },
"statusBar": { "statusBar": {
+3
View File
@@ -1377,6 +1377,9 @@
"maintenance": "維護中", "maintenance": "維護中",
"paused": "已暫停", "paused": "已暫停",
"up": "運行中" "up": "運行中"
},
"incidents": {
"errorLoading": "無法載入事件。"
} }
}, },
"statusBar": { "statusBar": {
+7
View File
@@ -18,6 +18,7 @@
"compression": "1.8.1", "compression": "1.8.1",
"cookie-parser": "^1.4.7", "cookie-parser": "^1.4.7",
"cors": "^2.8.5", "cors": "^2.8.5",
"dayjs": "^1.11.23",
"dockerode": "5.0.0", "dockerode": "5.0.0",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.19.2", "express": "^4.19.2",
@@ -5803,6 +5804,12 @@
"node": ">=18" "node": ">=18"
} }
}, },
"node_modules/dayjs": {
"version": "1.11.23",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz",
"integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==",
"license": "MIT"
},
"node_modules/debug": { "node_modules/debug": {
"version": "4.4.3", "version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+1
View File
@@ -42,6 +42,7 @@
"compression": "1.8.1", "compression": "1.8.1",
"cookie-parser": "^1.4.7", "cookie-parser": "^1.4.7",
"cors": "^2.8.5", "cors": "^2.8.5",
"dayjs": "^1.11.23",
"dockerode": "5.0.0", "dockerode": "5.0.0",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.19.2", "express": "^4.19.2",
@@ -7,6 +7,8 @@ import {
getStatusPageQueryValidation, getStatusPageQueryValidation,
imageValidation, imageValidation,
resolveStatusPageQueryValidation, resolveStatusPageQueryValidation,
getPublicMonitorIncidentsParamValidation,
getPublicMonitorIncidentsQueryValidation,
} from "@/api/validation/statusPageValidation.js"; } from "@/api/validation/statusPageValidation.js";
import { AppError } from "@/utils/AppError.js"; import { AppError } from "@/utils/AppError.js";
import { requireTeamId, requireUserId } from "@/api/controllers/controllerUtils.js"; import { requireTeamId, requireUserId } from "@/api/controllers/controllerUtils.js";
@@ -17,6 +19,7 @@ export interface IStatusPageController {
createStatusPage: RequestHandler; createStatusPage: RequestHandler;
updateStatusPage: RequestHandler; updateStatusPage: RequestHandler;
getStatusPageByUrl: RequestHandler; getStatusPageByUrl: RequestHandler;
getPublicMonitorIncidents: RequestHandler;
resolveStatusPageByDomain: RequestHandler; resolveStatusPageByDomain: RequestHandler;
getStatusPagesByTeamId: RequestHandler; getStatusPagesByTeamId: RequestHandler;
deleteStatusPage: RequestHandler; deleteStatusPage: RequestHandler;
@@ -85,6 +88,19 @@ class StatusPageController implements IStatusPageController {
}); });
}); });
getPublicMonitorIncidents = catchAsync(async (req: Request, res: Response) => {
const { url, monitorId } = getPublicMonitorIncidentsParamValidation.parse(req.params);
const { date } = getPublicMonitorIncidentsQueryValidation.parse(req.query);
const incidents = await this.statusPageService.getPublicMonitorIncidents(url, monitorId, date, req.user?.teamId);
return res.status(200).json({
success: true,
msg: "Incidents retrieved successfully",
data: { incidents },
});
});
resolveStatusPageByDomain = catchAsync(async (req: Request, res: Response) => { resolveStatusPageByDomain = catchAsync(async (req: Request, res: Response) => {
const { range } = resolveStatusPageQueryValidation.parse(req.query); const { range } = resolveStatusPageQueryValidation.parse(req.query);
const domain = resolveStatusPageDomainFromRequest(req.hostname, req.query.domain as string | undefined); const domain = resolveStatusPageDomainFromRequest(req.hostname, req.query.domain as string | undefined);
@@ -16,7 +16,15 @@ export const isPublicStatusPageApiPath = (method: string, path: string): boolean
return true; return true;
} }
if (!slug || slug === "team" || slug.includes("/")) { if (!slug || slug === "team") {
return false;
}
if (slug.includes("/")) {
const parts = slug.split("/");
if (parts.length === 3 && parts[1] === "incidents") {
return true;
}
return false; return false;
} }
@@ -14,6 +14,7 @@ export const createStatusPageRoutes = (
router.put("/:id", imageUpload.single("logo"), verifyJWT, isAllowed(["admin", "superadmin"]), statusPageController.updateStatusPage); router.put("/:id", imageUpload.single("logo"), verifyJWT, isAllowed(["admin", "superadmin"]), statusPageController.updateStatusPage);
router.get("/resolve", statusPageController.resolveStatusPageByDomain); router.get("/resolve", statusPageController.resolveStatusPageByDomain);
router.get("/:url", verifyStatusPageAccess, statusPageController.getStatusPageByUrl); router.get("/:url", verifyStatusPageAccess, statusPageController.getStatusPageByUrl);
router.get("/:url/incidents/:monitorId", verifyStatusPageAccess, statusPageController.getPublicMonitorIncidents);
router.delete("/:id", verifyJWT, isAllowed(["admin", "superadmin"]), statusPageController.deleteStatusPage); router.delete("/:id", verifyJWT, isAllowed(["admin", "superadmin"]), statusPageController.deleteStatusPage);
return router; return router;
}; };
@@ -20,6 +20,15 @@ export const getStatusPageParamValidation = z.object({
url: z.string().min(1, "URL is required"), url: z.string().min(1, "URL is required"),
}); });
export const getPublicMonitorIncidentsParamValidation = z.object({
url: z.string().min(1, "URL is required"),
monitorId: z.string().regex(/^[0-9a-fA-F]{24}$/, "Must be a valid monitor ID"),
});
export const getPublicMonitorIncidentsQueryValidation = z.object({
date: z.string().date("Date must be a valid calendar date in YYYY-MM-DD format"),
});
export const getStatusPageQueryValidation = z.object({ export const getStatusPageQueryValidation = z.object({
type: z.union([z.enum(StatusPageTypes), z.array(z.enum(StatusPageTypes))]).transform((val) => (Array.isArray(val) ? val : [val])), type: z.union([z.enum(StatusPageTypes), z.array(z.enum(StatusPageTypes))]).transform((val) => (Array.isArray(val) ? val : [val])),
range: z.enum(StatusPageRanges).optional().default("latest"), range: z.enum(StatusPageRanges).optional().default("latest"),
+1 -1
View File
@@ -99,7 +99,7 @@ export const buildApi = (shared: SharedServices, jobScheduler: IJobScheduler): A
emailService, emailService,
}); });
const statusPageService = new StatusPageService(statusPagesRepository, settingsService, monitorsRepository, checksRepository); const statusPageService = new StatusPageService(statusPagesRepository, settingsService, monitorsRepository, checksRepository, incidentsRepository);
const tagsService = new TagsService(tagsRepository, monitorsRepository); const tagsService = new TagsService(tagsRepository, monitorsRepository);
const diagnosticService = new DiagnosticService(db); const diagnosticService = new DiagnosticService(db);
const proxiesService = new ProxiesService(proxiesRepository, monitorsRepository, settingsService); const proxiesService = new ProxiesService(proxiesRepository, monitorsRepository, settingsService);
@@ -82,6 +82,7 @@ IncidentSchema.index({ teamId: 1, startTime: -1 });
IncidentSchema.index({ status: 1, startTime: -1 }); IncidentSchema.index({ status: 1, startTime: -1 });
IncidentSchema.index({ resolutionType: 1, status: 1 }); IncidentSchema.index({ resolutionType: 1, status: 1 });
IncidentSchema.index({ resolvedBy: 1, status: 1 }); IncidentSchema.index({ resolvedBy: 1, status: 1 });
IncidentSchema.index({ monitorId: 1, startTime: -1 });
IncidentSchema.index({ createdAt: -1 }); IncidentSchema.index({ createdAt: -1 });
const IncidentModel = model<IncidentDocument>("Incident", IncidentSchema); const IncidentModel = model<IncidentDocument>("Incident", IncidentSchema);
@@ -17,6 +17,7 @@ export interface IIncidentsRepository {
monitorId?: string, monitorId?: string,
resolutionType?: string resolutionType?: string
): Promise<Incident[]>; ): Promise<Incident[]>;
findByMonitorIdAndDate(monitorId: string, teamId: string, dateStart: Date, dateEnd: Date): Promise<Incident[]>;
findSummaryByTeamId(teamId: string, limit?: number): Promise<IncidentSummary>; findSummaryByTeamId(teamId: string, limit?: number): Promise<IncidentSummary>;
countByTeamId(teamId: string, startDate: Date | undefined, status?: boolean, monitorId?: string, resolutionType?: string): Promise<number>; countByTeamId(teamId: string, startDate: Date | undefined, status?: boolean, monitorId?: string, resolutionType?: string): Promise<number>;
@@ -120,6 +120,17 @@ class MongoIncidentsRepository implements IIncidentsRepository {
return this.mapDocuments(incidents); return this.mapDocuments(incidents);
}; };
findByMonitorIdAndDate = async (monitorId: string, teamId: string, dateStart: Date, dateEnd: Date): Promise<Incident[]> => {
const matchStage = {
monitorId: new mongoose.Types.ObjectId(monitorId),
teamId: new mongoose.Types.ObjectId(teamId),
startTime: { $lt: dateEnd },
$or: [{ endTime: null }, { endTime: { $gte: dateStart } }],
};
const incidents = await IncidentModel.find(matchStage).sort({ startTime: -1 });
return this.mapDocuments(incidents);
};
updateById = async (incidentId: string, teamId: string, patch: Partial<Incident>) => { updateById = async (incidentId: string, teamId: string, patch: Partial<Incident>) => {
const updatedIncident = await IncidentModel.findOneAndUpdate( const updatedIncident = await IncidentModel.findOneAndUpdate(
{ _id: new mongoose.Types.ObjectId(incidentId), teamId: new mongoose.Types.ObjectId(teamId) }, { _id: new mongoose.Types.ObjectId(incidentId), teamId: new mongoose.Types.ObjectId(teamId) },
@@ -20,6 +20,11 @@ export interface Incident {
updatedAt: string; updatedAt: string;
} }
export type PublicIncident = Pick<
Incident,
"id" | "monitorId" | "status" | "startTime" | "endTime" | "resolutionType" | "message" | "statusCode" | "createdAt"
>;
export interface IncidentSummaryTopMonitor { export interface IncidentSummaryTopMonitor {
monitorId: string; monitorId: string;
monitorName: string | null; monitorName: string | null;
@@ -1,6 +1,13 @@
import { type IIncidentsRepository } from "@/domain/incidents/incident.repository.interface.js";
import type { Incident, PublicIncident } from "@/domain/incidents/incident.type.js";
import { type IStatusPagesRepository } from "@/domain/status-pages/status-page-repository.interface.js"; import { type IStatusPagesRepository } from "@/domain/status-pages/status-page-repository.interface.js";
import { ISettingsService } from "@/domain/app-settings/app-settings.service.js"; import { ISettingsService } from "@/domain/app-settings/app-settings.service.js";
import { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js"; import { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
import { IChecksRepository } from "@/domain/checks/check.repository.interface.js";
import type { DailyCheckBucket } from "@/domain/checks/check.type.js";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc.js";
import timezone from "dayjs/plugin/timezone.js";
import { import {
DEFAULT_STATUS_PAGE_THEME, DEFAULT_STATUS_PAGE_THEME,
DEFAULT_STATUS_PAGE_THEME_MODE, DEFAULT_STATUS_PAGE_THEME_MODE,
@@ -12,8 +19,9 @@ import {
import { AppError } from "@/utils/AppError.js"; import { AppError } from "@/utils/AppError.js";
import { normalizeStatusPageDomain } from "@/utils/statusPageDomain.js"; import { normalizeStatusPageDomain } from "@/utils/statusPageDomain.js";
import { Monitor } from "@/domain/monitors/monitor.type.js"; import { Monitor } from "@/domain/monitors/monitor.type.js";
import { IChecksRepository } from "@/domain/checks/check.repository.interface.js";
import type { DailyCheckBucket } from "@/domain/checks/check.type.js"; dayjs.extend(utc);
dayjs.extend(timezone);
export interface IStatusPageService { export interface IStatusPageService {
createStatusPage(userId: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage>; createStatusPage(userId: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage>;
@@ -21,6 +29,7 @@ export interface IStatusPageService {
getStatusPageByCustomDomain(customDomain: string): Promise<StatusPage>; getStatusPageByCustomDomain(customDomain: string): Promise<StatusPage>;
getStatusPagesByTeamId(teamId: string): Promise<StatusPage[]>; getStatusPagesByTeamId(teamId: string): Promise<StatusPage[]>;
getPublicStatusPagePayload(statusPage: StatusPage, requesterTeamId: string | undefined, range: StatusPageRange): Promise<PublicStatusPagePayload>; getPublicStatusPagePayload(statusPage: StatusPage, requesterTeamId: string | undefined, range: StatusPageRange): Promise<PublicStatusPagePayload>;
getPublicMonitorIncidents(url: string, monitorId: string, date: string, requesterTeamId?: string): Promise<PublicIncident[]>;
updateStatusPage(id: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage>; updateStatusPage(id: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage>;
deleteStatusPage(statusPageId: string, teamId: string): Promise<StatusPage>; deleteStatusPage(statusPageId: string, teamId: string): Promise<StatusPage>;
@@ -31,7 +40,8 @@ export class StatusPageService implements IStatusPageService {
private statusPagesRepository: IStatusPagesRepository, private statusPagesRepository: IStatusPagesRepository,
private settingsService: ISettingsService, private settingsService: ISettingsService,
private monitorsRepository: IMonitorsRepository, private monitorsRepository: IMonitorsRepository,
private checksRepository: IChecksRepository private checksRepository: IChecksRepository,
private incidentsRepository: IIncidentsRepository
) {} ) {}
private assertCustomDomainAllowed = (customDomain: string | null | undefined) => { private assertCustomDomainAllowed = (customDomain: string | null | undefined) => {
@@ -95,6 +105,18 @@ export class StatusPageService implements IStatusPageService {
return base; return base;
}; };
private toPublicIncident = (incident: Incident): PublicIncident => ({
id: incident.id,
monitorId: incident.monitorId,
status: incident.status,
startTime: incident.startTime,
endTime: incident.endTime,
resolutionType: incident.resolutionType,
message: incident.message ?? null,
statusCode: incident.statusCode ?? null,
createdAt: incident.createdAt,
});
createStatusPage = async ( createStatusPage = async (
userId: string, userId: string,
teamId: string, teamId: string,
@@ -167,6 +189,29 @@ export class StatusPageService implements IStatusPageService {
}; };
}; };
getPublicMonitorIncidents = async (url: string, monitorId: string, date: string, requesterTeamId?: string): Promise<PublicIncident[]> => {
const statusPage = await this.getStatusPageByUrl(url);
// Ensure the status page is public or the requester is the owner
if (!statusPage.isPublished) {
if (!requesterTeamId || statusPage.teamId !== requesterTeamId) {
throw new AppError({ message: "Forbidden", status: 403 });
}
}
// Ensure the requested monitor actually belongs to this status page
if (!statusPage.monitors.includes(monitorId)) {
throw new AppError({ message: "Monitor not found on this status page", status: 404 });
}
const tz = statusPage.timezone ?? "Etc/UTC";
const dateStart = dayjs.tz(date, tz).startOf("day").toDate();
const dateEnd = dayjs.tz(date, tz).endOf("day").toDate();
const incidents = await this.incidentsRepository.findByMonitorIdAndDate(monitorId, statusPage.teamId, dateStart, dateEnd);
return incidents.map(this.toPublicIncident);
};
updateStatusPage = async (id: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage> => { updateStatusPage = async (id: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage> => {
const normalizedData = this.normalizeCustomDomainInput(this.normalizeInput(data)); const normalizedData = this.normalizeCustomDomainInput(this.normalizeInput(data));
const updated = await this.statusPagesRepository.updateById(id, teamId, image, normalizedData); const updated = await this.statusPagesRepository.updateById(id, teamId, image, normalizedData);
@@ -4,6 +4,7 @@ import type { IStatusPagesRepository } from "../../../src/domain/status-pages/st
import type { ISettingsService } from "../../../src/domain/app-settings/app-settings.service.ts"; import type { ISettingsService } from "../../../src/domain/app-settings/app-settings.service.ts";
import type { IMonitorsRepository } from "../../../src/domain/monitors/monitor.repository.interface.ts"; import type { IMonitorsRepository } from "../../../src/domain/monitors/monitor.repository.interface.ts";
import type { IChecksRepository } from "../../../src/domain/checks/check.repository.interface.ts"; import type { IChecksRepository } from "../../../src/domain/checks/check.repository.interface.ts";
import type { IIncidentsRepository } from "../../../src/domain/incidents/incident.repository.interface.ts";
import type { CheckSnapshot } from "../../../src/domain/checks/check.type.ts"; import type { CheckSnapshot } from "../../../src/domain/checks/check.type.ts";
import type { Monitor } from "../../../src/domain/monitors/monitor.type.ts"; import type { Monitor } from "../../../src/domain/monitors/monitor.type.ts";
import type { StatusPage } from "../../../src/domain/status-pages/status-page.type.ts"; import type { StatusPage } from "../../../src/domain/status-pages/status-page.type.ts";
@@ -84,13 +85,19 @@ const createChecksRepo = () =>
getDailyStatusBuckets: jest.fn().mockResolvedValue([]), getDailyStatusBuckets: jest.fn().mockResolvedValue([]),
}) as unknown as jest.Mocked<IChecksRepository>; }) as unknown as jest.Mocked<IChecksRepository>;
const createIncidentsRepo = () =>
({
findByMonitorIdAndDate: jest.fn().mockResolvedValue([]),
}) as unknown as jest.Mocked<IIncidentsRepository>;
const createService = (themesEnabled = true, clientHost = "http://localhost:5173", showURL = false) => { const createService = (themesEnabled = true, clientHost = "http://localhost:5173", showURL = false) => {
const repo = createRepo(); const repo = createRepo();
const settingsService = createSettingsService(themesEnabled, clientHost, showURL); const settingsService = createSettingsService(themesEnabled, clientHost, showURL);
const monitorsRepo = createMonitorsRepo(); const monitorsRepo = createMonitorsRepo();
const checksRepo = createChecksRepo(); const checksRepo = createChecksRepo();
const service = new StatusPageService(repo, settingsService, monitorsRepo, checksRepo); const incidentsRepo = createIncidentsRepo();
return { service, repo, settingsService, monitorsRepo, checksRepo }; const service = new StatusPageService(repo, settingsService, monitorsRepo, checksRepo, incidentsRepo);
return { service, repo, settingsService, monitorsRepo, checksRepo, incidentsRepo };
}; };
// ── Tests ──────────────────────────────────────────────────────────────────── // ── Tests ────────────────────────────────────────────────────────────────────
@@ -424,6 +431,51 @@ describe("StatusPageService", () => {
}); });
}); });
describe("getPublicMonitorIncidents", () => {
const publishedPage = () => makeStatusPage({ isPublished: true, url: "my-status-page", monitors: ["mon-1"], teamId: "team-1" });
it("rejects an unpublished page (403)", async () => {
const { service, repo } = createService();
(repo.findByUrl as jest.Mock).mockResolvedValue(makeStatusPage({ isPublished: false }));
await expect(service.getPublicMonitorIncidents("my-status-page", "mon-1", "2026-08-01")).rejects.toMatchObject({ status: 403 });
});
it("rejects if monitor is not on the page (404)", async () => {
const { service, repo } = createService();
(repo.findByUrl as jest.Mock).mockResolvedValue(publishedPage());
await expect(service.getPublicMonitorIncidents("my-status-page", "mon-99", "2026-08-01")).rejects.toMatchObject({ status: 404 });
});
it("fetches and sanitizes incidents successfully", async () => {
const { service, repo, incidentsRepo } = createService();
(repo.findByUrl as jest.Mock).mockResolvedValue(publishedPage());
const mockIncident = {
id: "inc-1",
monitorId: "mon-1",
teamId: "team-1",
resolvedBy: "user-99",
status: false,
startTime: "2026-08-01T10:00:00Z",
endTime: "2026-08-01T11:00:00Z",
resolutionType: "manual" as const,
message: "Test incident",
createdAt: "2026-08-01T10:00:00Z",
updatedAt: "2026-08-01T10:00:00Z",
};
(incidentsRepo.findByMonitorIdAndDate as jest.Mock).mockResolvedValue([mockIncident]);
const results = await service.getPublicMonitorIncidents("my-status-page", "mon-1", "2026-08-01");
expect(incidentsRepo.findByMonitorIdAndDate).toHaveBeenCalled();
expect(results).toHaveLength(1);
expect(results[0]).toHaveProperty("id", "inc-1");
expect(results[0]).not.toHaveProperty("teamId");
expect(results[0]).not.toHaveProperty("resolvedBy");
expect(results[0]).not.toHaveProperty("updatedAt");
});
});
describe("deleteStatusPage", () => { describe("deleteStatusPage", () => {
it("delegates to repository and returns deleted page", async () => { it("delegates to repository and returns deleted page", async () => {
const { service, repo } = createService(true); const { service, repo } = createService(true);