import { useEffect, useState } from "react"; import { Link, useSearchParams } from "react-router-dom"; import { IconPrinter } from "@tabler/icons-react"; import { api, type AvailabilityRow, type CurrentUser, type MonthlyReport as Report, type ServiceLevelResult } from "../api/client"; import { ErrorNotice } from "../components/Notice"; import { BlockSkeleton } from "../components/Skeleton"; import { CATEGORY_NAMES, incidentPath, SEVERITY_BADGE } from "../components/IncidentHistory"; import { formatDate, formatDateTime } from "../utils/date"; import { readableError } from "../utils/errors"; import { toast } from "../utils/toast"; import PageIntro from "../components/PageIntro"; /** "2 h 40 min", "35 min", "3 d 4 h". */ function span(minutes: number): string { const m = Math.max(1, Math.round(minutes)); if (m < 60) return `${m} min`; const h = Math.floor(m / 60); if (h < 24) return m % 60 && h < 10 ? `${h} h ${m % 60} min` : `${h} h`; const d = Math.floor(h / 24); return h % 24 ? `${d} d ${h % 24} h` : `${d} d`; } const RESULT_WORDS: Record = { ok: { label: "Passed", badge: "bg-green-lt text-green" }, partial: { label: "Partly worked", badge: "bg-yellow-lt text-yellow" }, failed: { label: "Failed", badge: "bg-red-lt text-red" }, not_needed: { label: "Not needed", badge: "bg-secondary-lt text-secondary" }, }; const average = (rows: { percent: number | null }[]) => { const known = rows.filter((r) => r.percent !== null); return known.length === 0 ? null : Math.round((known.reduce((n, r) => n + (r.percent as number), 0) / known.length) * 10) / 10; }; const percentBadge = (p: number | null) => (p === null ? "text-secondary" : p >= 99.9 ? "text-green" : p >= 99 ? "" : p >= 95 ? "text-yellow" : "text-red"); /** How each service-level target did over the stretch: its figure against the target, and the downtime against what it allowed. */ function ServiceLevelsSection({ rows, partial }: { rows: ServiceLevelResult[]; partial: boolean }) { if (rows.length === 0) return null; const metCount = rows.filter((l) => l.met).length; return (

Service levels

{metCount} of {rows.length} {rows.length === 1 ? "target was" : "targets were"} met{partial ? " so far" : ""}. Each is judged on the downtime it allowed over the whole stretch (the error budget).{" "} Set targets

{rows.map((l) => ( ))}
Target Target Achieved Down for Allowed
{l.name} {l.target}% {l.percent}% {l.downMinutes > 0 ? span(l.downMinutes) : "—"} {l.allowedMinutes >= 1 ? span(l.allowedMinutes) : "under a minute"} {l.met ? met : missed}
); } function Availability({ title, rows, hint }: { title: string; rows: AvailabilityRow[]; hint?: string }) { if (rows.length === 0) return null; return (

{title}

{hint &&
{hint}
}
{rows.map((r) => ( ))}
Name Up Down for
{r.name} {r.percent === null ? "—" : `${r.percent}%`} {r.downMinutes > 0 ? span(r.downMinutes) : "—"}
); } /** * How a month went, in one page that can be read, printed or sent: how available the servers and endpoints were, the incidents and how long they took, the * updates applied, restore tests and the state of the backups, and what was renewed. The same report can be sent on a day of the month (Settings → * Notifications → Monthly report). */ export default function MonthlyReport({ user }: { user: CurrentUser }) { const [params, setParams] = useSearchParams(); const month = params.get("month") ?? undefined; const [data, setData] = useState<{ report: Report; months: { id: string; label: string }[]; quarters: { id: string; label: string }[]; years: { id: string; label: string }[] } | null>(null); const [error, setError] = useState(null); useEffect(() => { let alive = true; setData(null); api.reports .monthly(month) .then((res) => { if (!alive) return; setData(res); setError(null); }) .catch((err) => alive && setError(readableError(err))); return () => { alive = false; }; }, [month]); async function copyText() { try { const t = await api.reports.monthlyText(data?.report.month); await navigator.clipboard.writeText(`${t.title}\n\n${t.message}`); toast.success("Copied the report as text."); } catch (err) { toast.error(readableError(err)); } } const r = data?.report; const kind = r?.period ?? (month ? (/Q/.test(month) ? "quarter" : /^\d{4}$/.test(month) ? "year" : "month") : "month"); const noun = kind === "year" ? "Annual" : kind === "quarter" ? "Quarterly" : "Monthly"; const stretch = kind === "year" ? "year" : kind === "quarter" ? "quarter" : "month"; const options = data ? (kind === "year" ? data.years : kind === "quarter" ? data.quarters : data.months) : []; /** The newest finished one of a kind, which is what is shown when nothing is asked for. */ const lastWhole = (list: { id: string }[]) => list[1]?.id ?? list[0]?.id; const serverAvg = r ? average(r.servers) : null; const endpointAvg = r ? average(r.endpoints) : null; const cards = r ? [ { label: "Servers up, on average", value: serverAvg === null ? "—" : `${serverAvg}%`, color: percentBadge(serverAvg) }, { label: "Endpoints answering", value: endpointAvg === null ? "—" : `${endpointAvg}%`, color: percentBadge(endpointAvg) }, { label: "Incidents began", value: String(r.incidents.began), color: r.incidents.began > 0 ? "text-yellow" : "text-green" }, { label: "Update runs", value: String(r.updates.runs), color: r.updates.failed > 0 ? "text-yellow" : "" }, { label: "Renewed", value: String(r.renewals.length), color: "" }, ] : []; return (

{noun} report

{data && (
{([["month", "Month", data.months], ["quarter", "Quarter", data.quarters], ["year", "Year", data.years]] as const).map(([k, label, list]) => ( ))}
)} {data && ( )}
How the {stretch} went, in one page: availability, how each service-level target did, incidents and how long they took, updates applied, restore tests and backups, and what was renewed. {user.role === "admin" ? ( <> {" "} It can be sent on a day of the month, and a quarter's and year's report after the month that ends it: Settings → Notifications. ) : null} {!data && !error && } {r && ( <>

{r.label}

{formatDate(new Date(r.from))} – {formatDate(new Date(r.to))} {r.partial ? ` · the ${stretch} is not over, so this is the ${stretch} so far` : ""} · time zone {r.timezone}
{cards.map((c) => (
{c.value}
{c.label}
))}

Availability

{r.servers.length === 0 && r.endpoints.length === 0 && r.integrations.length === 0 ? (
Nothing was measured for this month. Servers are measured from when their agent first reported, endpoints from when they were first checked.
) : ( <> {r.endpoints.length > 0 && (

Endpoints

From every check's answers, day by day (the days are UTC days).
{r.endpoints.map((e) => ( ))}
Check Answered Average answer Times asked
{e.name} {e.percent === null ? "—" : `${e.percent}%`} {e.avgMs === null ? "—" : `${e.avgMs} ms`} {e.checks}
)} )}

Incidents

{r.incidents.began === 0 && r.incidents.resolved === 0 && r.incidents.stillOpen === 0 ? (
No incident began or ended this month.
) : ( <>

{r.incidents.began} began, {r.incidents.resolved} ended{r.incidents.stillOpen > 0 ? <>, {r.incidents.stillOpen} {r.partial ? "open" : "still open at the end of the month"} : null}. {r.incidents.averageMinutes !== null && <> One that began and ended in the month took {span(r.incidents.averageMinutes)} on average, {span(r.incidents.totalMinutes)} in all.}

{r.incidents.byCategory.length > 0 && (
{r.incidents.byCategory.map((c) => ( {CATEGORY_NAMES[c.category as keyof typeof CATEGORY_NAMES] ?? c.category} · {c.count} ))}
)}
{r.incidents.list.map((i) => ( ))}
Began Where What Worst Lasted
{formatDateTime(new Date(i.openedAt))} {i.where} {i.message} {i.severity} {span(i.minutes)} {!i.resolvedAt && and open}
{r.incidents.began > r.incidents.list.length &&
The {r.incidents.list.length} longest of {r.incidents.began}. All are under Alerts → History.
} )}

Updates

{r.updates.runs === 0 && r.updates.planRuns.runs === 0 ? (
No update run was made from here this month.
) : ( <>

{r.updates.runs} update run{r.updates.runs === 1 ? "" : "s"}: {r.updates.done} done{r.updates.failed > 0 ? `, ${r.updates.failed} failed` : ""} {r.updates.installed > 0 ? ` — ${r.updates.installed} update${r.updates.installed === 1 ? "" : "s"} installed` : ""}. {r.updates.planRuns.runs > 0 && ( <> {" "} Patch plans ran {r.updates.planRuns.runs} time{r.updates.planRuns.runs === 1 ? "" : "s"} {r.updates.planRuns.failed > 0 ? `, ${r.updates.planRuns.failed} not cleanly` : ", all cleanly"}. )}

{r.updates.byServer.length > 0 && (
{r.updates.byServer.map((s) => ( ))}
Server Runs Failed Installed
{s.name} {s.runs} 0 ? "text-red" : "text-secondary"}`}>{s.failed || "—"} {s.installed || "—"}
)} )}

Backups and restore tests

{r.restoreTests.length === 0 ? (

No restore test was recorded this month.

) : (
{r.restoreTests.map((t, i) => ( ))}
Tested What Result Note
{t.testedAt} {t.label} {RESULT_WORDS[t.result]?.label ?? t.result} {t.note ?? ""}
)} {r.backups ? (

Backups as they are now (read {formatDate(new Date(r.backups.asOf))}): {r.backups.ok} of {r.backups.total} guest{r.backups.total === 1 ? "" : "s"} have a recent one {r.backups.failed + r.backups.stale + r.backups.none + r.backups.unknown > 0 && ( <> ; {r.backups.failed} failed, {r.backups.stale} stale, {r.backups.none} without any{r.backups.unknown > 0 ? `, ${r.backups.unknown} unknown` : ""} )} . See Backup coverage.

) : (

The backups have not been read since this app started, so their state is not shown here. Open Backup coverage to read them.

)}

Renewed

{r.renewals.length === 0 ? (
No certificate or domain was seen to be renewed this month.
) : (
{r.renewals.map((x, i) => ( ))}
Seen What Was good until Is good until
{formatDate(new Date(x.at))} {x.kind === "domain" ? "Domain" : "Certificate"} {x.subject} {x.fromDate} {x.toDate}
)}
Renewals are noticed when the app re-reads an expiry date, so only those since it began watching are here.
)}
); }