Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions apps/web/src/app/routes.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,18 @@ describe("AppRoutes", () => {
});

it("renders the dashboard with primary navigation once authenticated", async () => {
(fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
ok: true,
json: async () => ({
accessToken: "token-123",
user: { id: "u1", email: "operator@example.com", role: "operator" },
}),
// /login returns a token; the dashboard's data requests get empty pages.
(fetch as ReturnType<typeof vi.fn>).mockImplementation(async (input: string) => {
if (String(input).endsWith("/login")) {
return {
ok: true,
json: async () => ({
accessToken: "token-123",
user: { id: "u1", email: "operator@example.com", role: "operator" },
}),
};
}
return { ok: true, status: 200, json: async () => ({ items: [], nextCursor: null }) };
});

function LoginThenRoutes() {
Expand Down
37 changes: 37 additions & 0 deletions apps/web/src/components/DataStates.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Button } from "@/components/ui/button";
import { errorMessage } from "@/lib/apiError";

/** LoadingState is a polite live region shown while a view's data is loading. */
export function LoadingState({ label }: { label: string }) {
return (
<p role="status" className="py-6 text-sm text-muted-foreground">
{label}
</p>
);
}

/** EmptyState explains that a successful request returned nothing to show. */
export function EmptyState({ children }: { children: string }) {
return <p className="py-6 text-sm text-muted-foreground">{children}</p>;
}

/** ErrorState announces a failed request with a display-safe message and a retry. */
export function ErrorState({
title,
error,
onRetry,
}: {
title: string;
error: unknown;
onRetry: () => void;
}) {
return (
<div role="alert" className="space-y-2 rounded-md border border-border p-4 text-sm">
<p className="font-medium">{title}</p>
<p className="text-muted-foreground">{errorMessage(error)}</p>
<Button type="button" variant="outline" size="sm" onClick={onRetry}>
Retry
</Button>
</div>
);
}
52 changes: 52 additions & 0 deletions apps/web/src/features/alerts/AlertActions.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Button } from "@/components/ui/button";
import type { Alert } from "@/lib/apiTypes";
import {
transitionFailureMessage,
useAlertTransition,
type AlertTransition,
} from "@/features/alerts/useAlertTransition";

const labels: Record<AlertTransition, string> = {
acknowledge: "Acknowledge",
resolve: "Resolve",
};

interface AlertActionsProps {
alert: Alert;
/** Called with a display message when a transition fails. */
onFailure: (message: string) => void;
}

/**
* AlertActions shows the one transition valid for the alert's status:
* Acknowledge for open alerts, Resolve for acknowledged ones, nothing otherwise.
*/
export function AlertActions({ alert, onFailure }: AlertActionsProps) {
const transition = useAlertTransition({
onError: (error, vars) => onFailure(transitionFailureMessage(error, vars.action)),
});

const action: AlertTransition | null =
alert.status === "open" ? "acknowledge" : alert.status === "acknowledged" ? "resolve" : null;
if (!action) {
return (
<span className="text-muted-foreground">
<span aria-hidden="true">—</span>
<span className="sr-only">No actions available</span>
</span>
);
}

return (
<Button
type="button"
size="sm"
variant="outline"
disabled={transition.isPending}
aria-label={`${labels[action]} alert ${alert.id.slice(0, 8)}`}
onClick={() => transition.mutate({ id: alert.id, action })}
>
{transition.isPending ? "Working…" : labels[action]}
</Button>
);
}
54 changes: 54 additions & 0 deletions apps/web/src/features/alerts/AlertSummary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { ErrorState, LoadingState } from "@/components/DataStates";
import type { UseQueryResult } from "@tanstack/react-query";
import { SeverityChart } from "@/features/alerts/SeverityChart";
import { SUMMARY_LIMIT, countBySeverity, formatCount } from "@/features/alerts/summary";
import { useAlertPage } from "@/features/alerts/useAlerts";
import type { Alert, Page } from "@/lib/apiTypes";

function Tile({ label, query }: { label: string; query: UseQueryResult<Page<Alert>> }) {
return (
<section aria-label={label} className="rounded-lg border border-border p-4">
<p className="text-sm text-muted-foreground">{label}</p>
{query.isPending ? (
<p role="status" className="text-sm text-muted-foreground">Loading…</p>
) : query.isError ? (
<p role="alert" className="text-sm">Unavailable</p>
) : (
<p className="text-3xl font-semibold">{formatCount(query.data)}</p>
)}
</section>
);
}

/** AlertSummary is the dashboard's alert tiles plus the open-alerts-by-severity chart. */
export function AlertSummary() {
const open = useAlertPage("open", SUMMARY_LIMIT);
const acknowledged = useAlertPage("acknowledged", SUMMARY_LIMIT);

return (
<>
<div className="grid gap-4 sm:grid-cols-2">
<Tile label="Open alerts" query={open} />
<Tile label="Acknowledged alerts" query={acknowledged} />
</div>

<section aria-labelledby="severity-heading" className="space-y-3">
<h2 id="severity-heading" className="text-lg font-semibold">Open alerts by severity</h2>
{open.isPending ? (
<LoadingState label="Loading severity breakdown…" />
) : open.isError ? (
<ErrorState
title="Could not load open alerts"
error={open.error}
onRetry={() => void open.refetch()}
/>
) : (
<SeverityChart
counts={countBySeverity(open.data.items)}
truncated={open.data.nextCursor !== null}
/>
)}
</section>
</>
);
}
75 changes: 75 additions & 0 deletions apps/web/src/features/alerts/SeverityChart.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { Bar, BarChart, CartesianGrid, LabelList, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { ALERT_SEVERITIES, type AlertSeverity } from "@/lib/apiTypes";
import type { SeverityCounts } from "@/features/alerts/summary";

const label = (s: AlertSeverity) => s.charAt(0).toUpperCase() + s.slice(1);

const TICK = { fill: "var(--chart-text)", fontSize: 12 };

function ChartTooltip({ active, payload }: { active?: boolean; payload?: { payload?: { name: string; count: number } }[] }) {
const row = payload?.[0]?.payload;
if (!active || !row) return null;
return (
<div className="rounded-md border border-border bg-background px-3 py-2 text-sm shadow-sm">
<p className="font-semibold">{row.count}</p>
<p className="text-muted-foreground">{row.name}</p>
</div>
);
}

/**
* SeverityChart is a single-series column chart of alert counts by severity
* (always all four, in severity order). The chart is a visual aid only; the
* same numbers are always present in the table below it, which is what
* assistive technology reads.
*/
export function SeverityChart({ counts, truncated }: { counts: SeverityCounts; truncated: boolean }) {
const data = ALERT_SEVERITIES.map((s) => ({ name: label(s), count: counts[s] }));
const total = data.reduce((sum, d) => sum + d.count, 0);

return (
<figure className="space-y-3">
<div aria-hidden="true" className="h-56 w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} margin={{ top: 20, right: 8, bottom: 0, left: 0 }} accessibilityLayer={false}>
<CartesianGrid vertical={false} stroke="var(--chart-grid)" strokeWidth={1} />
<XAxis dataKey="name" tick={TICK} tickLine={false} axisLine={{ stroke: "var(--chart-axis)" }} />
<YAxis allowDecimals={false} tick={TICK} tickLine={false} axisLine={false} width={32} />
<Tooltip content={<ChartTooltip />} cursor={{ fill: "var(--chart-grid)", fillOpacity: 0.4 }} />
<Bar
dataKey="count"
fill="var(--chart-bar)"
maxBarSize={24}
radius={[4, 4, 0, 0]}
activeBar={{ fill: "var(--chart-bar-hover)" }}
isAnimationActive={false}
>
<LabelList dataKey="count" position="top" fill="var(--chart-text)" fontSize={12} />
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
<figcaption className="text-sm text-muted-foreground">
{total === 0 ? "No open alerts. " : ""}
{truncated ? "Based on the 200 most recent open alerts." : ""}
</figcaption>
<table className="w-full max-w-sm text-left text-sm">
<caption className="sr-only">Open alerts by severity</caption>
<thead>
<tr className="border-b border-border">
<th scope="col" className="py-1 pr-4 font-medium">Severity</th>
<th scope="col" className="py-1 text-right font-medium">Open alerts</th>
</tr>
</thead>
<tbody>
{data.map((d) => (
<tr key={d.name} className="border-b border-border last:border-0">
<th scope="row" className="py-1 pr-4 font-normal">{d.name}</th>
<td className="py-1 text-right tabular-nums">{d.count}</td>
</tr>
))}
</tbody>
</table>
</figure>
);
}
141 changes: 141 additions & 0 deletions apps/web/src/features/alerts/hooks.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, renderHook, waitFor } from "@testing-library/react";
import { useAlertPage, useAlerts } from "@/features/alerts/useAlerts";
import { useAlertTransition } from "@/features/alerts/useAlertTransition";
import { useTransactions } from "@/features/transactions/useTransactions";
import { ApiError } from "@/lib/apiError";
import { queryKeys } from "@/lib/queryKeys";
import {
errorResponse,
hookWrapper,
jsonResponse,
makeAlert,
makeQueryClient,
makeTransaction,
requestedUrls,
stubApi,
} from "@/test/api";

afterEach(() => {
vi.unstubAllGlobals();
});

describe("useAlerts", () => {
it("requests all alerts with the default page size and no status param", async () => {
const api = stubApi(() => jsonResponse({ items: [makeAlert(1)], nextCursor: null }));
const { result } = renderHook(() => useAlerts(), { wrapper: hookWrapper() });
await waitFor(() => expect(result.current.isSuccess).toBe(true));

const url = requestedUrls(api)[0];
expect(url.pathname).toBe("/alerts");
expect(url.searchParams.get("status")).toBeNull();
expect(url.searchParams.get("limit")).toBe("50");
expect(url.searchParams.get("cursor")).toBeNull();
expect(result.current.hasNextPage).toBe(false);
});

it("sends the status filter and follows nextCursor for the next page", async () => {
const api = stubApi((url) =>
url.searchParams.get("cursor") === "cur-2"
? jsonResponse({ items: [makeAlert(2)], nextCursor: null })
: jsonResponse({ items: [makeAlert(1)], nextCursor: "cur-2" }),
);
const { result } = renderHook(() => useAlerts("open"), { wrapper: hookWrapper() });
await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(requestedUrls(api)[0].searchParams.get("status")).toBe("open");
expect(result.current.hasNextPage).toBe(true);

await act(async () => {
await result.current.fetchNextPage();
});

const second = requestedUrls(api)[1];
expect(second.searchParams.get("status")).toBe("open");
expect(second.searchParams.get("cursor")).toBe("cur-2");
await waitFor(() => expect(result.current.data?.pages).toHaveLength(2));
expect(result.current.data?.pages.flatMap((p) => p.items)).toHaveLength(2);
expect(result.current.hasNextPage).toBe(false);
});

it("builds its key on the shared alerts prefix", async () => {
stubApi(() => jsonResponse({ items: [], nextCursor: null }));
const client = makeQueryClient();
const { result } = renderHook(() => useAlerts("resolved"), { wrapper: hookWrapper(client) });
await waitFor(() => expect(result.current.isSuccess).toBe(true));
const keys = client.getQueryCache().findAll({ queryKey: queryKeys.alerts });
expect(keys).toHaveLength(1);
});

it("surfaces the error envelope as a typed ApiError", async () => {
stubApi(() => errorResponse(400, "INVALID_QUERY", "limit must be between 1 and 200"));
const { result } = renderHook(() => useAlerts(), { wrapper: hookWrapper() });
await waitFor(() => expect(result.current.isError).toBe(true));
expect(result.current.error).toBeInstanceOf(ApiError);
expect((result.current.error as ApiError).code).toBe("INVALID_QUERY");
});
});

describe("useAlertPage", () => {
it("requests a single page with status and limit", async () => {
const api = stubApi(() => jsonResponse({ items: [], nextCursor: null }));
const { result } = renderHook(() => useAlertPage("acknowledged", 200), {
wrapper: hookWrapper(),
});
await waitFor(() => expect(result.current.isSuccess).toBe(true));
const url = requestedUrls(api)[0];
expect(url.searchParams.get("status")).toBe("acknowledged");
expect(url.searchParams.get("limit")).toBe("200");
});
});

describe("useTransactions", () => {
it("requests the given number of transactions", async () => {
const api = stubApi(() => jsonResponse({ items: [makeTransaction(1)], nextCursor: null }));
const client = makeQueryClient();
const { result } = renderHook(() => useTransactions(10), { wrapper: hookWrapper(client) });
await waitFor(() => expect(result.current.isSuccess).toBe(true));
const url = requestedUrls(api)[0];
expect(url.pathname).toBe("/transactions");
expect(url.searchParams.get("limit")).toBe("10");
expect(client.getQueryCache().findAll({ queryKey: queryKeys.transactions })).toHaveLength(1);
});
});

describe("useAlertTransition", () => {
it("POSTs the transition and invalidates the alerts queries on success", async () => {
const alert = makeAlert(1, { status: "acknowledged" });
const api = stubApi(() => jsonResponse(alert));
const client = makeQueryClient();
const invalidate = vi.spyOn(client, "invalidateQueries");
const { result } = renderHook(() => useAlertTransition(), { wrapper: hookWrapper(client) });

await act(async () => {
await result.current.mutateAsync({ id: alert.id, action: "acknowledge" });
});

const [input, init] = api.mock.calls[0];
expect(new URL(String(input)).pathname).toBe(`/alerts/${alert.id}/acknowledge`);
expect(init?.method).toBe("POST");
expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.alerts });
});

it("reports a 409 as a typed error and still invalidates", async () => {
stubApi(() => errorResponse(409, "INVALID_TRANSITION", "not allowed"));
const client = makeQueryClient();
const invalidate = vi.spyOn(client, "invalidateQueries");
const onError = vi.fn();
const { result } = renderHook(() => useAlertTransition({ onError }), {
wrapper: hookWrapper(client),
});

await act(async () => {
await result.current.mutateAsync({ id: "x", action: "resolve" }).catch(() => undefined);
});

expect(onError).toHaveBeenCalledTimes(1);
const err = onError.mock.calls[0][0] as ApiError;
expect(err.status).toBe(409);
expect(err.code).toBe("INVALID_TRANSITION");
expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.alerts });
});
});
Loading