diff --git a/apps/web/src/app/routes.test.tsx b/apps/web/src/app/routes.test.tsx index b64adf3..a6c66f4 100644 --- a/apps/web/src/app/routes.test.tsx +++ b/apps/web/src/app/routes.test.tsx @@ -37,12 +37,18 @@ describe("AppRoutes", () => { }); it("renders the dashboard with primary navigation once authenticated", async () => { - (fetch as ReturnType).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).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() { diff --git a/apps/web/src/components/DataStates.tsx b/apps/web/src/components/DataStates.tsx new file mode 100644 index 0000000..f27aeaa --- /dev/null +++ b/apps/web/src/components/DataStates.tsx @@ -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 ( +

+ {label} +

+ ); +} + +/** EmptyState explains that a successful request returned nothing to show. */ +export function EmptyState({ children }: { children: string }) { + return

{children}

; +} + +/** 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 ( +
+

{title}

+

{errorMessage(error)}

+ +
+ ); +} diff --git a/apps/web/src/features/alerts/AlertActions.tsx b/apps/web/src/features/alerts/AlertActions.tsx new file mode 100644 index 0000000..6a82857 --- /dev/null +++ b/apps/web/src/features/alerts/AlertActions.tsx @@ -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 = { + 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 ( + + + No actions available + + ); + } + + return ( + + ); +} diff --git a/apps/web/src/features/alerts/AlertSummary.tsx b/apps/web/src/features/alerts/AlertSummary.tsx new file mode 100644 index 0000000..d5ad443 --- /dev/null +++ b/apps/web/src/features/alerts/AlertSummary.tsx @@ -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> }) { + return ( +
+

{label}

+ {query.isPending ? ( +

Loading…

+ ) : query.isError ? ( +

Unavailable

+ ) : ( +

{formatCount(query.data)}

+ )} +
+ ); +} + +/** 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 ( + <> +
+ + +
+ +
+

Open alerts by severity

+ {open.isPending ? ( + + ) : open.isError ? ( + void open.refetch()} + /> + ) : ( + + )} +
+ + ); +} diff --git a/apps/web/src/features/alerts/SeverityChart.tsx b/apps/web/src/features/alerts/SeverityChart.tsx new file mode 100644 index 0000000..30de2ee --- /dev/null +++ b/apps/web/src/features/alerts/SeverityChart.tsx @@ -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 ( +
+

{row.count}

+

{row.name}

+
+ ); +} + +/** + * 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 ( +
+ +
+ {total === 0 ? "No open alerts. " : ""} + {truncated ? "Based on the 200 most recent open alerts." : ""} +
+ + + + + + + + + + {data.map((d) => ( + + + + + ))} + +
Open alerts by severity
SeverityOpen alerts
{d.name}{d.count}
+
+ ); +} diff --git a/apps/web/src/features/alerts/hooks.test.tsx b/apps/web/src/features/alerts/hooks.test.tsx new file mode 100644 index 0000000..4107b27 --- /dev/null +++ b/apps/web/src/features/alerts/hooks.test.tsx @@ -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 }); + }); +}); diff --git a/apps/web/src/features/alerts/summary.ts b/apps/web/src/features/alerts/summary.ts new file mode 100644 index 0000000..a937623 --- /dev/null +++ b/apps/web/src/features/alerts/summary.ts @@ -0,0 +1,18 @@ +import { type Alert, type AlertSeverity, type Page } from "@/lib/apiTypes"; + +/** SUMMARY_LIMIT is the largest page the API allows; more than this shows as "200+". */ +export const SUMMARY_LIMIT = 200; + +export type SeverityCounts = Record; + +/** countBySeverity always returns all four severities, zero-filled. */ +export function countBySeverity(alerts: Alert[]): SeverityCounts { + const counts: SeverityCounts = { low: 0, medium: 0, high: 0, critical: 0 }; + for (const a of alerts) counts[a.severity] += 1; + return counts; +} + +/** formatCount shows an exact count, or "200+" when more pages exist. */ +export function formatCount(page: Page): string { + return page.nextCursor !== null ? `${SUMMARY_LIMIT}+` : String(page.items.length); +} diff --git a/apps/web/src/features/alerts/useAlertTransition.ts b/apps/web/src/features/alerts/useAlertTransition.ts new file mode 100644 index 0000000..60bb264 --- /dev/null +++ b/apps/web/src/features/alerts/useAlertTransition.ts @@ -0,0 +1,41 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { useApiFetch } from "@/app/useApiFetch"; +import { requestJson, type ApiError } from "@/lib/apiError"; +import type { Alert } from "@/lib/apiTypes"; +import { queryKeys } from "@/lib/queryKeys"; + +export type AlertTransition = "acknowledge" | "resolve"; + +/** transitionFailureMessage is the non-fatal inline message for a failed transition. */ +export function transitionFailureMessage(error: ApiError, action: AlertTransition): string { + if (error.status === 409 && error.code === "INVALID_TRANSITION") { + const past = action === "acknowledge" ? "acknowledged" : "resolved"; + return `This alert can no longer be ${past}: its status has changed. The list has been refreshed.`; + } + return `Could not ${action} the alert: ${error.message}`; +} + +interface TransitionVars { + id: string; + action: AlertTransition; +} + +/** + * useAlertTransition acknowledges or resolves an alert. The alerts queries + * are invalidated whether the call succeeds or fails: a 409 means the list + * was stale, and the refetch brings it back in line with the server. + */ +export function useAlertTransition(options: { onError?: (error: ApiError, vars: TransitionVars) => void } = {}) { + const apiFetch = useApiFetch(); + const queryClient = useQueryClient(); + const { onError } = options; + + return useMutation({ + mutationFn: ({ id, action }) => + requestJson(apiFetch, `/alerts/${encodeURIComponent(id)}/${action}`, { + method: "POST", + }), + onError: (error, vars) => onError?.(error, vars), + onSettled: () => queryClient.invalidateQueries({ queryKey: queryKeys.alerts }), + }); +} diff --git a/apps/web/src/features/alerts/useAlerts.ts b/apps/web/src/features/alerts/useAlerts.ts new file mode 100644 index 0000000..9eea8d7 --- /dev/null +++ b/apps/web/src/features/alerts/useAlerts.ts @@ -0,0 +1,40 @@ +import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; +import { useApiFetch } from "@/app/useApiFetch"; +import { requestJson } from "@/lib/apiError"; +import type { Alert, AlertStatus, Page } from "@/lib/apiTypes"; +import { queryKeys } from "@/lib/queryKeys"; + +export const ALERTS_PAGE_SIZE = 50; + +/** alertsPath builds the GET /alerts URL; omitted filters are not sent. */ +function alertsPath(status: AlertStatus | undefined, limit: number, cursor?: string): string { + const params = new URLSearchParams(); + if (status) params.set("status", status); + params.set("limit", String(limit)); + if (cursor) params.set("cursor", cursor); + return `/alerts?${params.toString()}`; +} + +/** + * useAlerts lists alerts, most-recent first, with cursor ("Load more") + * pagination. Keys extend queryKeys.alerts so realtime events refresh them. + */ +export function useAlerts(status?: AlertStatus, limit = ALERTS_PAGE_SIZE) { + const apiFetch = useApiFetch(); + return useInfiniteQuery({ + queryKey: [...queryKeys.alerts, "list", { status: status ?? null, limit }], + initialPageParam: undefined as string | undefined, + queryFn: ({ pageParam }) => + requestJson>(apiFetch, alertsPath(status, limit, pageParam)), + getNextPageParam: (last) => last.nextCursor ?? undefined, + }); +} + +/** useAlertPage fetches a single page of alerts (no pagination), e.g. for dashboard counts. */ +export function useAlertPage(status: AlertStatus, limit: number) { + const apiFetch = useApiFetch(); + return useQuery({ + queryKey: [...queryKeys.alerts, "page", { status, limit }], + queryFn: () => requestJson>(apiFetch, alertsPath(status, limit)), + }); +} diff --git a/apps/web/src/features/transactions/RecentTransactions.tsx b/apps/web/src/features/transactions/RecentTransactions.tsx new file mode 100644 index 0000000..aa4a7ac --- /dev/null +++ b/apps/web/src/features/transactions/RecentTransactions.tsx @@ -0,0 +1,53 @@ +import { EmptyState, ErrorState, LoadingState } from "@/components/DataStates"; +import { useTransactions } from "@/features/transactions/useTransactions"; +import { formatMoney } from "@/lib/money"; +import { formatTimestamp } from "@/lib/time"; + +const RECENT_COUNT = 10; + +/** RecentTransactions is a table of the most recent synthetic transactions. */ +export function RecentTransactions() { + const query = useTransactions(RECENT_COUNT); + + if (query.isPending) return ; + if (query.isError) { + return ( + void query.refetch()} + /> + ); + } + if (query.data.items.length === 0) return No transactions yet.; + + return ( +
+ + + + + + + + + + + + {query.data.items.map((tx) => ( + + + + + + + ))} + +
Most recent transactions
OccurredAccountDirectionAmount
+ + {tx.accountId}{tx.direction} + {formatMoney(tx.amountMinor, tx.currency)} +
+
+ ); +} diff --git a/apps/web/src/features/transactions/useTransactions.ts b/apps/web/src/features/transactions/useTransactions.ts new file mode 100644 index 0000000..0784569 --- /dev/null +++ b/apps/web/src/features/transactions/useTransactions.ts @@ -0,0 +1,14 @@ +import { useQuery } from "@tanstack/react-query"; +import { useApiFetch } from "@/app/useApiFetch"; +import { requestJson } from "@/lib/apiError"; +import type { Page, Transaction } from "@/lib/apiTypes"; +import { queryKeys } from "@/lib/queryKeys"; + +/** useTransactions fetches the most recent page of transactions (most-recent first). */ +export function useTransactions(limit = 10) { + const apiFetch = useApiFetch(); + return useQuery({ + queryKey: [...queryKeys.transactions, { limit }], + queryFn: () => requestJson>(apiFetch, `/transactions?limit=${limit}`), + }); +} diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 1deeb20..4087d06 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -23,6 +23,13 @@ --input: 214.3 31.8% 91.4%; --ring: 222.2 84% 4.9%; --radius: 0.5rem; + + /* Chart tokens (validated with the dataviz palette script). */ + --chart-bar: #2a78d6; + --chart-bar-hover: #5598e7; + --chart-grid: #e1e0d9; + --chart-axis: #c3c2b7; + --chart-text: #52514e; } .dark { @@ -43,6 +50,12 @@ --border: 217.2 32.6% 17.5%; --input: 217.2 32.6% 17.5%; --ring: 212.7 26.8% 83.9%; + + --chart-bar: #3987e5; + --chart-bar-hover: #6da7ec; + --chart-grid: #2c2c2a; + --chart-axis: #383835; + --chart-text: #c3c2b7; } * { diff --git a/apps/web/src/lib/apiError.test.ts b/apps/web/src/lib/apiError.test.ts new file mode 100644 index 0000000..4b9a997 --- /dev/null +++ b/apps/web/src/lib/apiError.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vitest"; +import { ApiError, errorMessage, toApiError } from "@/lib/apiError"; + +describe("toApiError", () => { + it("parses the canonical error envelope", async () => { + const res = new Response( + JSON.stringify({ error: { code: "INVALID_TRANSITION", message: "not allowed" } }), + { status: 409 }, + ); + const err = await toApiError(res); + expect(err).toBeInstanceOf(ApiError); + expect(err.status).toBe(409); + expect(err.code).toBe("INVALID_TRANSITION"); + expect(err.message).toBe("not allowed"); + }); + + it("falls back to a generic error for a non-JSON body", async () => { + const err = await toApiError(new Response("bad gateway", { status: 502 })); + expect(err.status).toBe(502); + expect(err.code).toBe("UNKNOWN"); + expect(err.message).toBe("Request failed (502)"); + }); + + it("ignores an envelope with the wrong shape", async () => { + const err = await toApiError(new Response(JSON.stringify({ error: "nope" }), { status: 500 })); + expect(err.code).toBe("UNKNOWN"); + }); +}); + +describe("errorMessage", () => { + it("shows an ApiError message and hides unexpected error details", () => { + expect(errorMessage(new ApiError(400, "INVALID_QUERY", "limit must be between 1 and 200"))).toBe( + "limit must be between 1 and 200", + ); + expect(errorMessage(new TypeError("Failed to fetch"))).toMatch(/something went wrong/i); + }); +}); diff --git a/apps/web/src/lib/apiError.ts b/apps/web/src/lib/apiError.ts new file mode 100644 index 0000000..7175f91 --- /dev/null +++ b/apps/web/src/lib/apiError.ts @@ -0,0 +1,48 @@ +/** + * ApiError is a failed API response parsed from the canonical error envelope + * `{"error":{"code","message"}}` (contracts/openapi.yaml, Error schema). + */ +export class ApiError extends Error { + readonly status: number; + readonly code: string; + + constructor(status: number, code: string, message: string) { + super(message); + this.name = "ApiError"; + this.status = status; + this.code = code; + } +} + +/** toApiError reads a non-2xx response; a malformed body still yields an ApiError. */ +export async function toApiError(res: Response): Promise { + let code = "UNKNOWN"; + let message = `Request failed (${res.status})`; + try { + const body: unknown = await res.json(); + const err = (body as { error?: { code?: unknown; message?: unknown } } | null)?.error; + if (typeof err?.code === "string") code = err.code; + if (typeof err?.message === "string") message = err.message; + } catch { + // Body was not JSON; keep the generic message. + } + return new ApiError(res.status, code, message); +} + +/** requestJson runs a request and returns its JSON body, throwing ApiError on non-2xx. */ +export async function requestJson( + apiFetch: (path: string, init?: RequestInit) => Promise, + path: string, + init?: RequestInit, +): Promise { + const res = await apiFetch(path, init); + if (!res.ok) throw await toApiError(res); + return (await res.json()) as T; +} + +/** errorMessage is a display-safe message for any thrown value. */ +export function errorMessage(error: unknown): string { + return error instanceof ApiError + ? error.message + : "Something went wrong. Check your connection and try again."; +} diff --git a/apps/web/src/lib/apiTypes.ts b/apps/web/src/lib/apiTypes.ts new file mode 100644 index 0000000..31abf50 --- /dev/null +++ b/apps/web/src/lib/apiTypes.ts @@ -0,0 +1,38 @@ +// Types mirroring the schemas in contracts/openapi.yaml. Keep them aligned. + +export type AlertStatus = "open" | "acknowledged" | "resolved"; +export type AlertSeverity = "low" | "medium" | "high" | "critical"; + +export const ALERT_STATUSES: readonly AlertStatus[] = ["open", "acknowledged", "resolved"]; +export const ALERT_SEVERITIES: readonly AlertSeverity[] = ["low", "medium", "high", "critical"]; + +export interface Transaction { + id: string; + accountId: string; + /** Integer minor units (e.g. cents). Always positive. */ + amountMinor: number; + /** ISO 4217 currency code. */ + currency: string; + direction: "debit" | "credit"; + status: "posted"; + /** RFC 3339 (UTC). */ + occurredAt: string; +} + +export interface Alert { + id: string; + ruleId: string; + transactionId: string; + status: AlertStatus; + severity: AlertSeverity; + /** RFC 3339 (UTC). */ + createdAt: string; + /** RFC 3339 (UTC). */ + updatedAt: string; +} + +/** Cursor-paginated response shared by TransactionPage and AlertPage. */ +export interface Page { + items: T[]; + nextCursor: string | null; +} diff --git a/apps/web/src/lib/money.test.ts b/apps/web/src/lib/money.test.ts new file mode 100644 index 0000000..03387db --- /dev/null +++ b/apps/web/src/lib/money.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vitest"; +import { formatMoney } from "@/lib/money"; + +describe("formatMoney", () => { + it.each([ + [1234, "USD", "$12.34"], + [5, "USD", "$0.05"], + [0, "USD", "$0.00"], + [100, "USD", "$1.00"], + [-250, "USD", "-$2.50"], + [1234, "JPY", "¥1,234"], // 0 minor-unit digits + [12345, "KWD", "KWD 12.345"], // 3 minor-unit digits + ])("formats %s %s as %s", (minor, currency, expected) => { + expect(formatMoney(minor, currency).replaceAll("\u00a0", " ")).toBe(expected); + }); + + it("keeps every digit of a value beyond Number.MAX_SAFE_INTEGER", () => { + // 2^53 + 1 cannot be represented as a number; bigint and string inputs stay exact. + expect(formatMoney(9007199254740993n, "USD")).toBe("$90,071,992,547,409.93"); + expect(formatMoney("9007199254740993", "USD")).toBe("$90,071,992,547,409.93"); + expect(formatMoney(9223372036854775807n, "JPY")).toBe("¥9,223,372,036,854,775,807"); + }); + + it("formats a large safe integer without float drift", () => { + expect(formatMoney(Number.MAX_SAFE_INTEGER, "USD")).toBe("$90,071,992,547,409.91"); + }); + + it("rejects non-integer amounts", () => { + expect(() => formatMoney(12.5, "USD")).toThrow(RangeError); + }); + + it("falls back to the currency code for an unrecognised code", () => { + expect(formatMoney(1234, "ZZ")).toBe("12.34 ZZ"); + }); +}); diff --git a/apps/web/src/lib/money.ts b/apps/web/src/lib/money.ts new file mode 100644 index 0000000..4656e54 --- /dev/null +++ b/apps/web/src/lib/money.ts @@ -0,0 +1,54 @@ +/** + * Money is carried as integer minor units. Display scaling is done on a + * decimal string built from a bigint, never with float division, so very + * large amounts keep every digit. + */ + +/** minorUnitDigits is the currency's minor-unit exponent as known to Intl. */ +function minorUnitDigits(formatter: Intl.NumberFormat): number { + return formatter.resolvedOptions().maximumFractionDigits as number; +} + +/** scaleMinor turns integer minor units into an exact decimal string. */ +function scaleMinor(minor: bigint, digits: number): string { + const negative = minor < 0n; + const abs = (negative ? -minor : minor).toString().padStart(digits + 1, "0"); + const whole = abs.slice(0, abs.length - digits); + const fraction = abs.slice(abs.length - digits); + return `${negative ? "-" : ""}${whole}${digits > 0 ? `.${fraction}` : ""}`; +} + +/** formatDecimal formats an exact decimal string. Intl accepts these (ES2023); lib typings predate it. */ +function formatDecimal(formatter: Intl.NumberFormat, decimal: string): string { + return (formatter.format as unknown as (value: string) => string)(decimal); +} + +/** + * formatMoney formats an integer amount of minor units for an ISO 4217 + * currency, e.g. (1234, "USD") -> "$12.34" and (1234, "JPY") -> "¥1,234". + * Pass a bigint or an integer string for values beyond Number.MAX_SAFE_INTEGER. + * Throws RangeError for non-integer input; falls back to " " + * (2 decimals) if the currency code is not recognised by Intl. + */ +export function formatMoney( + amountMinor: number | bigint | string, + currency: string, + locale = "en-US", +): string { + if (typeof amountMinor === "number" && !Number.isInteger(amountMinor)) { + throw new RangeError("amountMinor must be an integer"); + } + const minor = BigInt(amountMinor); + let formatter: Intl.NumberFormat; + try { + formatter = new Intl.NumberFormat(locale, { style: "currency", currency }); + } catch (e) { + if (!(e instanceof RangeError)) throw e; + const plain = new Intl.NumberFormat(locale, { + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }); + return `${formatDecimal(plain, scaleMinor(minor, 2))} ${currency}`; + } + return formatDecimal(formatter, scaleMinor(minor, minorUnitDigits(formatter))); +} diff --git a/apps/web/src/lib/time.test.ts b/apps/web/src/lib/time.test.ts new file mode 100644 index 0000000..4f4bc88 --- /dev/null +++ b/apps/web/src/lib/time.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vitest"; +import { formatTimestamp } from "@/lib/time"; + +describe("formatTimestamp", () => { + it("renders an RFC 3339 UTC value in UTC", () => { + expect(formatTimestamp("2026-01-02T03:04:05Z")).toBe("2 Jan 2026, 03:04:05 UTC"); + }); + + it("converts an offset timestamp to UTC", () => { + expect(formatTimestamp("2026-01-02T03:04:05+02:00")).toBe("2 Jan 2026, 01:04:05 UTC"); + }); + + it("returns an unparseable value unchanged", () => { + expect(formatTimestamp("not-a-date")).toBe("not-a-date"); + }); +}); diff --git a/apps/web/src/lib/time.ts b/apps/web/src/lib/time.ts new file mode 100644 index 0000000..4427c72 --- /dev/null +++ b/apps/web/src/lib/time.ts @@ -0,0 +1,16 @@ +const formatter = new Intl.DateTimeFormat("en-GB", { + dateStyle: "medium", + timeStyle: "medium", + timeZone: "UTC", +}); + +/** + * formatTimestamp renders an RFC 3339 timestamp for display, always in UTC + * (e.g. "6 Oct 2026, 14:03:22 UTC"). Values stay RFC 3339 strings everywhere + * else; an unparseable value is returned unchanged. + */ +export function formatTimestamp(rfc3339: string): string { + const date = new Date(rfc3339); + if (Number.isNaN(date.getTime())) return rfc3339; + return `${formatter.format(date)} UTC`; +} diff --git a/apps/web/src/pages/AlertsPage.test.tsx b/apps/web/src/pages/AlertsPage.test.tsx new file mode 100644 index 0000000..b7a0436 --- /dev/null +++ b/apps/web/src/pages/AlertsPage.test.tsx @@ -0,0 +1,198 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { AlertsPage } from "@/pages/AlertsPage"; +import type { Alert } from "@/lib/apiTypes"; +import { + errorResponse, + jsonResponse, + makeAlert, + renderPage, + requestedUrls, + stubApi, +} from "@/test/api"; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +const open = makeAlert(1, { status: "open", severity: "high" }); +const acked = makeAlert(2, { status: "acknowledged", severity: "medium" }); +const resolved = makeAlert(3, { status: "resolved", severity: "low" }); + +/** listHandler serves GET /alerts from a mutable array, honouring the status filter. */ +function listHandler(alerts: Alert[]) { + return (url: URL) => { + const status = url.searchParams.get("status"); + return jsonResponse({ + items: alerts.filter((a) => !status || a.status === status), + nextCursor: null, + }); + }; +} + +describe("AlertsPage", () => { + it("shows a loading state, then a captioned table with the alert fields", async () => { + stubApi(listHandler([open])); + renderPage(, "/alerts"); + expect(screen.getByRole("status")).toHaveTextContent(/loading alerts/i); + + const table = await screen.findByRole("table", { name: /all alerts, most recent first/i }); + const row = within(table).getAllByRole("row")[1]; + expect(within(row).getByText("high")).toBeInTheDocument(); + expect(within(row).getByText("open")).toBeInTheDocument(); + expect(within(row).getByText(open.transactionId)).toBeInTheDocument(); + expect(within(row).getByText("2 Jan 2026, 03:04:05 UTC")).toHaveAttribute( + "datetime", + "2026-01-02T03:04:05Z", + ); + expect(within(row).getByText("2 Jan 2026, 03:05:06 UTC")).toBeInTheDocument(); + for (const name of ["Severity", "Status", "Created", "Updated", "Transaction", "Actions"]) { + expect(within(table).getByRole("columnheader", { name })).toBeInTheDocument(); + } + }); + + it("offers Acknowledge only for open alerts and Resolve only for acknowledged ones", async () => { + stubApi(listHandler([open, acked, resolved])); + renderPage(, "/alerts"); + await screen.findByRole("table"); + + expect(screen.getByRole("button", { name: `Acknowledge alert ${open.id.slice(0, 8)}` })).toBeEnabled(); + expect(screen.getByRole("button", { name: `Resolve alert ${acked.id.slice(0, 8)}` })).toBeEnabled(); + expect(screen.getAllByRole("button", { name: /^acknowledge alert/i })).toHaveLength(1); + expect(screen.getAllByRole("button", { name: /^resolve alert/i })).toHaveLength(1); + expect(screen.getAllByText("No actions available")).toHaveLength(1); + }); + + it("acknowledges an alert, disables the button while pending and refreshes the list", async () => { + const alerts = [{ ...open }]; + let release: () => void = () => {}; + const gate = new Promise((r) => (release = r)); + const api = stubApi(async (url, init) => { + if (init?.method === "POST") { + await gate; + alerts[0].status = "acknowledged"; + return jsonResponse(alerts[0]); + } + return listHandler(alerts)(url); + }); + renderPage(, "/alerts"); + + const button = await screen.findByRole("button", { name: /^acknowledge alert/i }); + await userEvent.click(button); + await waitFor(() => expect(button).toBeDisabled()); + + release(); + expect( + await screen.findByRole("button", { name: `Resolve alert ${open.id.slice(0, 8)}` }), + ).toBeEnabled(); + const post = api.mock.calls.find(([, init]) => init?.method === "POST"); + expect(new URL(String(post?.[0])).pathname).toBe(`/alerts/${open.id}/acknowledge`); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + }); + + it("shows a non-fatal inline message on 409 INVALID_TRANSITION and refreshes the list", async () => { + // The server already moved the alert on; the page's list is stale until the refetch. + let serverStatus: Alert["status"] = "open"; + let listCalls = 0; + stubApi((_url, init) => { + if (init?.method === "POST") { + serverStatus = "resolved"; + return errorResponse(409, "INVALID_TRANSITION", "alert is not in a state that allows this transition"); + } + listCalls += 1; + return jsonResponse({ items: [{ ...open, status: listCalls === 1 ? "open" : serverStatus }], nextCursor: null }); + }); + renderPage(, "/alerts"); + + await userEvent.click(await screen.findByRole("button", { name: /^acknowledge alert/i })); + + expect(await screen.findByRole("alert")).toHaveTextContent( + /can no longer be acknowledged.*list has been refreshed/i, + ); + await waitFor(() => expect(listCalls).toBeGreaterThanOrEqual(2)); + await waitFor(() => + expect(screen.queryByRole("button", { name: /^acknowledge alert/i })).not.toBeInTheDocument(), + ); + // The table is still there: the failure is not fatal. + expect(screen.getByRole("table")).toBeInTheDocument(); + + await userEvent.click(screen.getByRole("button", { name: "Dismiss" })); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + }); + + it("stores the status filter in the URL and requests it", async () => { + const api = stubApi(listHandler([open, acked, resolved])); + renderPage(, "/alerts"); + await screen.findByRole("table"); + expect(requestedUrls(api)[0].searchParams.get("status")).toBeNull(); + + await userEvent.selectOptions(screen.getByLabelText("Status"), "acknowledged"); + + expect(screen.getByTestId("location")).toHaveTextContent("/alerts?status=acknowledged"); + await waitFor(() => { + const last = requestedUrls(api).at(-1); + expect(last?.searchParams.get("status")).toBe("acknowledged"); + }); + expect(await screen.findByRole("table", { name: /status acknowledged/i })).toBeInTheDocument(); + expect(screen.getAllByRole("row")).toHaveLength(2); + + await userEvent.selectOptions(screen.getByLabelText("Status"), ""); + expect(screen.getByTestId("location")).toHaveTextContent(/^\/alerts$/); + }); + + it("reads the initial filter from the URL and ignores unknown values", async () => { + const api = stubApi(listHandler([open])); + renderPage(, "/alerts?status=open"); + await screen.findByRole("table"); + expect(screen.getByLabelText("Status")).toHaveValue("open"); + expect(requestedUrls(api)[0].searchParams.get("status")).toBe("open"); + }); + + it("falls back to all alerts for an invalid status in the URL", async () => { + const api = stubApi(listHandler([open])); + renderPage(, "/alerts?status=bogus"); + await screen.findByRole("table"); + expect(screen.getByLabelText("Status")).toHaveValue(""); + expect(requestedUrls(api)[0].searchParams.get("status")).toBeNull(); + }); + + it("loads more with the cursor and hides the button on the last 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" }), + ); + renderPage(, "/alerts"); + await screen.findByRole("table"); + expect(screen.getAllByRole("row")).toHaveLength(2); + + await userEvent.click(screen.getByRole("button", { name: "Load more" })); + await waitFor(() => expect(screen.getAllByRole("row")).toHaveLength(3)); + expect(requestedUrls(api).at(-1)?.searchParams.get("cursor")).toBe("cur-2"); + expect(screen.queryByRole("button", { name: "Load more" })).not.toBeInTheDocument(); + }); + + it("shows an empty state", async () => { + stubApi(listHandler([])); + renderPage(, "/alerts?status=resolved"); + expect(await screen.findByText("No resolved alerts.")).toBeInTheDocument(); + expect(screen.queryByRole("table")).not.toBeInTheDocument(); + }); + + it("shows an error state with retry", async () => { + let fail = true; + stubApi((url) => + fail ? errorResponse(500, "INTERNAL", "database unavailable") : listHandler([open])(url), + ); + renderPage(, "/alerts"); + + const alert = await screen.findByRole("alert"); + expect(alert).toHaveTextContent("Could not load alerts"); + expect(alert).toHaveTextContent("database unavailable"); + + fail = false; + await userEvent.click(screen.getByRole("button", { name: "Retry" })); + expect(await screen.findByRole("table")).toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/pages/AlertsPage.tsx b/apps/web/src/pages/AlertsPage.tsx index 218e900..ffd0b65 100644 --- a/apps/web/src/pages/AlertsPage.tsx +++ b/apps/web/src/pages/AlertsPage.tsx @@ -1,10 +1,133 @@ -import { PagePlaceholder } from "@/pages/PagePlaceholder"; +import { useState } from "react"; +import { useSearchParams } from "react-router-dom"; +import { Button } from "@/components/ui/button"; +import { EmptyState, ErrorState, LoadingState } from "@/components/DataStates"; +import { AlertActions } from "@/features/alerts/AlertActions"; +import { useAlerts } from "@/features/alerts/useAlerts"; +import { ALERT_STATUSES, type AlertStatus } from "@/lib/apiTypes"; +import { formatTimestamp } from "@/lib/time"; + +/** parseStatus accepts only contract status values from the URL; anything else means "all". */ +function parseStatus(raw: string | null): AlertStatus | undefined { + return ALERT_STATUSES.find((s) => s === raw); +} export function AlertsPage() { + const [searchParams, setSearchParams] = useSearchParams(); + const status = parseStatus(searchParams.get("status")); + const [failure, setFailure] = useState(null); + + const alerts = useAlerts(status); + const items = alerts.data?.pages.flatMap((p) => p.items) ?? []; + + function onStatusChange(value: string) { + setFailure(null); + setSearchParams(parseStatus(value) ? { status: value } : {}); + } + return ( - +
+
+

+ Alerts +

+

Operational alerts raised from synthetic activity.

+
+ +
+ + +
+ + {failure && ( +
+

{failure}

+ +
+ )} + + {alerts.isPending ? ( + + ) : alerts.isError ? ( + void alerts.refetch()} + /> + ) : items.length === 0 ? ( + + {status ? `No ${status} alerts.` : "No alerts yet."} + + ) : ( + <> +
+ + + + + + + + + + + + + + {items.map((alert) => ( + + + + + + + + + ))} + +
+ {status ? `Alerts with status ${status}` : "All alerts"}, most recent first +
SeverityStatusCreatedUpdatedTransactionActions
{alert.severity}{alert.status} + + + + {alert.transactionId} + +
+
+ {alerts.hasNextPage && ( + + )} + {alerts.isFetchNextPageError && ( +

+ Could not load more alerts. Try again. +

+ )} + + )} +
); } diff --git a/apps/web/src/pages/DashboardPage.test.tsx b/apps/web/src/pages/DashboardPage.test.tsx new file mode 100644 index 0000000..3925f05 --- /dev/null +++ b/apps/web/src/pages/DashboardPage.test.tsx @@ -0,0 +1,132 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { screen, within } from "@testing-library/react"; +import { DashboardPage } from "@/pages/DashboardPage"; +import type { Alert } from "@/lib/apiTypes"; +import { + errorResponse, + jsonResponse, + makeAlert, + makeTransaction, + renderPage, + requestedUrls, + stubApi, +} from "@/test/api"; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +interface Fixture { + open?: Alert[]; + openNext?: string | null; + acknowledged?: Alert[]; + acknowledgedNext?: string | null; + transactions?: ReturnType[]; +} + +function serve(f: Fixture) { + return stubApi((url) => { + if (url.pathname === "/transactions") { + return jsonResponse({ items: f.transactions ?? [], nextCursor: null }); + } + if (url.searchParams.get("status") === "open") { + return jsonResponse({ items: f.open ?? [], nextCursor: f.openNext ?? null }); + } + return jsonResponse({ items: f.acknowledged ?? [], nextCursor: f.acknowledgedNext ?? null }); + }); +} + +const tile = (name: string) => screen.getByRole("region", { name }); + +describe("DashboardPage", () => { + it("shows alert counts, a severity breakdown with all four severities, and transactions", async () => { + const api = serve({ + open: [ + makeAlert(1, { severity: "critical" }), + makeAlert(2, { severity: "low" }), + makeAlert(3, { severity: "low" }), + ], + acknowledged: [makeAlert(4, { status: "acknowledged" })], + transactions: [ + makeTransaction(1, { amountMinor: 1234, currency: "USD", direction: "credit" }), + makeTransaction(2, { amountMinor: 5000, currency: "JPY" }), + ], + }); + renderPage(, "/dashboard"); + + expect(await within(tile("Open alerts")).findByText("3")).toBeInTheDocument(); + expect(await within(tile("Acknowledged alerts")).findByText("1")).toBeInTheDocument(); + + // The chart's accessible equivalent is a table with every severity, zero-filled. + const table = await screen.findByRole("table", { name: "Open alerts by severity" }); + const counts = within(table) + .getAllByRole("row") + .slice(1) + .map((r) => [ + within(r).getByRole("rowheader").textContent, + within(r).getByRole("cell").textContent, + ]); + expect(counts).toEqual([ + ["Low", "2"], + ["Medium", "0"], + ["High", "0"], + ["Critical", "1"], + ]); + + const txTable = await screen.findByRole("table", { name: "Most recent transactions" }); + expect(within(txTable).getByText("$12.34")).toBeInTheDocument(); + expect(within(txTable).getByText("¥5,000")).toBeInTheDocument(); + expect(within(txTable).getByText("ACC-1001")).toBeInTheDocument(); + + const urls = requestedUrls(api); + const alertUrls = urls.filter((u) => u.pathname === "/alerts"); + expect(alertUrls.map((u) => u.searchParams.get("status")).sort()).toEqual(["acknowledged", "open"]); + expect(alertUrls.every((u) => u.searchParams.get("limit") === "200")).toBe(true); + expect(urls.find((u) => u.pathname === "/transactions")?.searchParams.get("limit")).toBe("10"); + }); + + it('shows "200+" when more alerts exist beyond the first page', async () => { + serve({ + open: Array.from({ length: 200 }, (_, i) => makeAlert(i + 1)), + openNext: "more", + acknowledged: [makeAlert(500, { status: "acknowledged" })], + }); + renderPage(, "/dashboard"); + + expect(await within(tile("Open alerts")).findByText("200+")).toBeInTheDocument(); + expect(within(tile("Acknowledged alerts")).getByText("1")).toBeInTheDocument(); + expect(await screen.findByText(/200 most recent open alerts/i)).toBeInTheDocument(); + }); + + it("shows loading states, then empty states with zeroed counts", async () => { + serve({}); + renderPage(, "/dashboard"); + expect(screen.getByText("Loading transactions…")).toBeInTheDocument(); + + expect(await screen.findByText("No transactions yet.")).toBeInTheDocument(); + expect(await within(tile("Open alerts")).findByText("0")).toBeInTheDocument(); + expect(within(tile("Acknowledged alerts")).getByText("0")).toBeInTheDocument(); + expect(screen.getByText(/no open alerts/i)).toBeInTheDocument(); + // All four severities are still listed when there is nothing open. + const table = screen.getByRole("table", { name: "Open alerts by severity" }); + expect(within(table).getAllByRole("row")).toHaveLength(5); + }); + + it("shows error states per section without breaking the page", async () => { + stubApi((url) => + url.pathname === "/transactions" + ? errorResponse(500, "INTERNAL", "transactions store unavailable") + : errorResponse(503, "NOT_READY", "alerts store unavailable"), + ); + renderPage(, "/dashboard"); + + expect(await screen.findByText("Could not load transactions")).toBeInTheDocument(); + expect(screen.getByText("transactions store unavailable")).toBeInTheDocument(); + expect(await screen.findByText("Could not load open alerts")).toBeInTheDocument(); + expect(screen.getByText("alerts store unavailable")).toBeInTheDocument(); + expect(within(tile("Open alerts")).getByText("Unavailable")).toBeInTheDocument(); + expect(within(tile("Acknowledged alerts")).getByText("Unavailable")).toBeInTheDocument(); + expect(screen.getAllByRole("button", { name: "Retry" })).toHaveLength(2); + expect(screen.getByRole("heading", { name: "Dashboard" })).toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/pages/DashboardPage.tsx b/apps/web/src/pages/DashboardPage.tsx index e98c018..95339c5 100644 --- a/apps/web/src/pages/DashboardPage.tsx +++ b/apps/web/src/pages/DashboardPage.tsx @@ -1,10 +1,24 @@ -import { PagePlaceholder } from "@/pages/PagePlaceholder"; +import { AlertSummary } from "@/features/alerts/AlertSummary"; +import { RecentTransactions } from "@/features/transactions/RecentTransactions"; export function DashboardPage() { return ( - +
+
+

+ Dashboard +

+

+ Operational overview of synthetic transaction monitoring. +

+
+ + + +
+

Recent transactions

+ +
+
); } diff --git a/apps/web/src/test/api.tsx b/apps/web/src/test/api.tsx new file mode 100644 index 0000000..d9ab1e4 --- /dev/null +++ b/apps/web/src/test/api.tsx @@ -0,0 +1,98 @@ +/* eslint-disable react-refresh/only-export-components -- test helpers, not app modules */ +import { vi } from "vitest"; +import { render } from "@testing-library/react"; +import { MemoryRouter, useLocation } from "react-router-dom"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import type { ReactElement, ReactNode } from "react"; +import { AuthProvider } from "@/app/AuthContext"; +import type { Alert, Transaction } from "@/lib/apiTypes"; + +// Synthetic fixtures only. +export function makeAlert(n: number, overrides: Partial = {}): Alert { + const id = String(n).padStart(12, "0"); + return { + id: `a0000000-0000-4000-8000-${id}`, + ruleId: `b0000000-0000-4000-8000-${id}`, + transactionId: `c0000000-0000-4000-8000-${id}`, + status: "open", + severity: "low", + createdAt: "2026-01-02T03:04:05Z", + updatedAt: "2026-01-02T03:05:06Z", + ...overrides, + }; +} + +export function makeTransaction(n: number, overrides: Partial = {}): Transaction { + return { + id: `d0000000-0000-4000-8000-${String(n).padStart(12, "0")}`, + accountId: `ACC-${1000 + n}`, + amountMinor: 1234, + currency: "USD", + direction: "debit", + status: "posted", + occurredAt: "2026-01-02T03:04:05Z", + ...overrides, + }; +} + +export function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json" }, + }); +} + +export function errorResponse(status: number, code: string, message: string): Response { + return jsonResponse({ error: { code, message } }, status); +} + +export type ApiHandler = (url: URL, init: RequestInit | undefined) => Response | Promise; + +/** stubApi replaces global fetch with a handler that receives parsed URLs. */ +export function stubApi(handler: ApiHandler) { + const mock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => + handler(new URL(String(input)), init), + ); + vi.stubGlobal("fetch", mock); + return mock; +} + +/** requestedUrls lists the URLs fetch was called with, in order. */ +export function requestedUrls(mock: ReturnType): URL[] { + return mock.mock.calls.map(([input]) => new URL(String(input))); +} + +export function makeQueryClient() { + return new QueryClient({ defaultOptions: { queries: { retry: false } } }); +} + +/** wrapper provides auth + query client for hook tests. */ +export function hookWrapper(client = makeQueryClient()) { + return function Wrapper({ children }: { children: ReactNode }) { + return ( + + {children} + + ); + }; +} + +function LocationProbe() { + const { pathname, search } = useLocation(); + return
{`${pathname}${search}`}
; +} + +/** renderPage mounts a page at a path with auth, query client, router and a location probe. */ +export function renderPage(ui: ReactElement, path = "/") { + const client = makeQueryClient(); + return render( + + + + {ui} + + + + , + ); +}