diff --git a/apps/web/src/app/AppShell.tsx b/apps/web/src/app/AppShell.tsx index 217ab1b..6ef3b18 100644 --- a/apps/web/src/app/AppShell.tsx +++ b/apps/web/src/app/AppShell.tsx @@ -1,6 +1,6 @@ import { useState } from "react"; import { NavLink, Outlet } from "react-router-dom"; -import { Activity, Bell, LayoutDashboard, Menu, Wrench } from "lucide-react"; +import { Activity, Bell, LayoutDashboard, ListChecks, Menu, Wrench } from "lucide-react"; import { cn } from "@/lib/utils"; import { ConnectionStatus } from "@/app/ConnectionStatus"; import { useRealtimeEvents } from "@/app/useRealtimeEvents"; @@ -8,6 +8,7 @@ import { useRealtimeEvents } from "@/app/useRealtimeEvents"; const navItems = [ { to: "/dashboard", label: "Dashboard", icon: LayoutDashboard }, { to: "/alerts", label: "Alerts", icon: Bell }, + { to: "/rules", label: "Rules", icon: ListChecks }, { to: "/ops", label: "Ops", icon: Wrench }, ]; diff --git a/apps/web/src/app/routes.test.tsx b/apps/web/src/app/routes.test.tsx index a6c66f4..b15483a 100644 --- a/apps/web/src/app/routes.test.tsx +++ b/apps/web/src/app/routes.test.tsx @@ -82,6 +82,7 @@ describe("AppRoutes", () => { expect(await screen.findByRole("heading", { name: /dashboard/i })).toBeInTheDocument(); expect(screen.getByRole("navigation", { name: /primary/i })).toBeInTheDocument(); expect(screen.getByRole("status")).toHaveTextContent(/connecting/i); + expect(screen.getByRole("link", { name: "Rules" })).toHaveAttribute("href", "/rules"); }); it("renders a not-found page for unknown routes", () => { diff --git a/apps/web/src/app/routes.tsx b/apps/web/src/app/routes.tsx index 6cf725c..25e1adc 100644 --- a/apps/web/src/app/routes.tsx +++ b/apps/web/src/app/routes.tsx @@ -3,6 +3,7 @@ import { AppShell } from "@/app/AppShell"; import { ProtectedRoute } from "@/app/ProtectedRoute"; import { DashboardPage } from "@/pages/DashboardPage"; import { AlertsPage } from "@/pages/AlertsPage"; +import { RulesPage } from "@/pages/RulesPage"; import { OpsPage } from "@/pages/OpsPage"; import { LoginPage } from "@/pages/LoginPage"; import { NotFoundPage } from "@/pages/NotFoundPage"; @@ -21,6 +22,7 @@ export function AppRoutes() { } /> } /> } /> + } /> } /> diff --git a/apps/web/src/features/rules/RuleToggle.tsx b/apps/web/src/features/rules/RuleToggle.tsx new file mode 100644 index 0000000..ee5a92c --- /dev/null +++ b/apps/web/src/features/rules/RuleToggle.tsx @@ -0,0 +1,28 @@ +import { Button } from "@/components/ui/button"; +import type { Rule } from "@/lib/apiTypes"; +import { toggleFailureMessage, useRuleToggle } from "@/features/rules/useRuleToggle"; + +interface RuleToggleProps { + rule: Rule; + /** Called with a display message when the toggle fails. */ + onFailure: (message: string) => void; +} + +/** RuleToggle is the admin-only Enable/Disable button for one rule row. */ +export function RuleToggle({ rule, onFailure }: RuleToggleProps) { + const toggle = useRuleToggle({ onError: (error) => onFailure(toggleFailureMessage(error)) }); + const label = rule.enabled ? "Disable" : "Enable"; + + return ( + + ); +} diff --git a/apps/web/src/features/rules/condition.test.ts b/apps/web/src/features/rules/condition.test.ts new file mode 100644 index 0000000..5c3126a --- /dev/null +++ b/apps/web/src/features/rules/condition.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vitest"; +import { describeCondition } from "@/features/rules/condition"; + +describe("describeCondition", () => { + it.each([ + ["amount_minor", "gte", "500000", "Amount ≥ 500,000 minor units"], + ["amount_minor", "lte", "999", "Amount ≤ 999 minor units"], + ["amount_minor", "eq", "1000", "Amount = 1,000 minor units"], + ["amount_minor", "gte", "0", "Amount ≥ 0 minor units"], + ["amount_minor", "gte", "007500", "Amount ≥ 7,500 minor units"], + ["currency", "eq", "GBP", "Currency = GBP"], + ["direction", "eq", "debit", "Direction = debit"], + ])("renders %s %s %s", (field, operator, value, expected) => { + expect(describeCondition(field, operator, value)).toBe(expected); + }); + + it("keeps every digit of a value beyond Number.MAX_SAFE_INTEGER", () => { + expect(describeCondition("amount_minor", "gte", "9007199254740993123")).toBe( + "Amount ≥ 9,007,199,254,740,993,123 minor units", + ); + }); + + it.each([ + ["amount_minor", "gte", "12.5"], + ["amount_minor", "gte", "abc"], + ["amount_minor", "gte", "-5"], + ["currency", "gte", "GBP"], + ["direction", "lte", "debit"], + ["currency", "eq", ""], + ["account", "eq", "ACC-1"], + ["amount_minor", "neq", "100"], + ])("falls back to the raw text for %s %s %s", (field, operator, value) => { + expect(describeCondition(field, operator, value)).toBe(`${field} ${operator} ${value}`); + }); +}); diff --git a/apps/web/src/features/rules/condition.ts b/apps/web/src/features/rules/condition.ts new file mode 100644 index 0000000..9f26561 --- /dev/null +++ b/apps/web/src/features/rules/condition.ts @@ -0,0 +1,24 @@ +const symbols: Record = { gte: "≥", lte: "≤", eq: "=" }; + +/** groupDigits inserts thousands separators into a string of digits without any Number math. */ +function groupDigits(integer: string): string { + return integer.replace(/\B(?=(\d{3})+(?!\d))/g, ","); +} + +/** + * describeCondition renders a rule's condition for display, e.g. + * "Amount ≥ 500,000 minor units". Rules carry no currency, so amounts stay in + * integer minor units (grouped via BigInt/string handling, never float math). + * Unrecognised combinations fall back to the raw "field operator value". + */ +export function describeCondition(field: string, operator: string, value: string): string { + const symbol = symbols[operator]; + if (symbol) { + if (field === "amount_minor" && /^\d+$/.test(value)) { + return `Amount ${symbol} ${groupDigits(BigInt(value).toString())} minor units`; + } + if (operator === "eq" && field === "currency" && value !== "") return `Currency = ${value}`; + if (operator === "eq" && field === "direction" && value !== "") return `Direction = ${value}`; + } + return `${field} ${operator} ${value}`; +} diff --git a/apps/web/src/features/rules/useRuleToggle.ts b/apps/web/src/features/rules/useRuleToggle.ts new file mode 100644 index 0000000..a4d3980 --- /dev/null +++ b/apps/web/src/features/rules/useRuleToggle.ts @@ -0,0 +1,39 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { useApiFetch } from "@/app/useApiFetch"; +import { requestJson, type ApiError } from "@/lib/apiError"; +import type { Rule } from "@/lib/apiTypes"; +import { queryKeys } from "@/lib/queryKeys"; + +/** toggleFailureMessage is the non-fatal inline message for a failed enable/disable. */ +export function toggleFailureMessage(error: ApiError): string { + if (error.status === 403) return "Your role can't change rules."; + if (error.status === 404) return "This rule no longer exists. The list has been refreshed."; + return `Could not update the rule: ${error.message}`; +} + +interface ToggleVars { + id: string; + enabled: boolean; +} + +/** + * useRuleToggle enables or disables a rule (admin only on the server). The + * rules query is invalidated whether the call succeeds or fails: a 404 means + * the list was stale, and the refetch brings it back in line with the server. + */ +export function useRuleToggle(options: { onError?: (error: ApiError) => void } = {}) { + const apiFetch = useApiFetch(); + const queryClient = useQueryClient(); + const { onError } = options; + + return useMutation({ + mutationFn: ({ id, enabled }) => + requestJson(apiFetch, `/rules/${encodeURIComponent(id)}`, { + method: "PATCH", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ enabled }), + }), + onError: (error) => onError?.(error), + onSettled: () => queryClient.invalidateQueries({ queryKey: queryKeys.rules }), + }); +} diff --git a/apps/web/src/features/rules/useRules.ts b/apps/web/src/features/rules/useRules.ts new file mode 100644 index 0000000..174b9e8 --- /dev/null +++ b/apps/web/src/features/rules/useRules.ts @@ -0,0 +1,14 @@ +import { useQuery } from "@tanstack/react-query"; +import { useApiFetch } from "@/app/useApiFetch"; +import { requestJson } from "@/lib/apiError"; +import type { Rule } from "@/lib/apiTypes"; +import { queryKeys } from "@/lib/queryKeys"; + +/** useRules lists every rule, enabled or not. The rule set is small and unpaginated. */ +export function useRules() { + const apiFetch = useApiFetch(); + return useQuery({ + queryKey: [...queryKeys.rules], + queryFn: async () => (await requestJson<{ items: Rule[] }>(apiFetch, "/rules")).items, + }); +} diff --git a/apps/web/src/lib/apiTypes.ts b/apps/web/src/lib/apiTypes.ts index 31abf50..1b10a87 100644 --- a/apps/web/src/lib/apiTypes.ts +++ b/apps/web/src/lib/apiTypes.ts @@ -31,6 +31,19 @@ export interface Alert { updatedAt: string; } +export interface Rule { + id: string; + name: string; + field: "amount_minor" | "currency" | "direction"; + operator: "gte" | "lte" | "eq"; + /** Text interpreted per field: integer minor units for amount_minor, a literal otherwise. */ + value: string; + severity: AlertSeverity; + enabled: boolean; + /** RFC 3339 (UTC). */ + createdAt: string; +} + /** Cursor-paginated response shared by TransactionPage and AlertPage. */ export interface Page { items: T[]; diff --git a/apps/web/src/lib/queryKeys.ts b/apps/web/src/lib/queryKeys.ts index e62a293..e1583c8 100644 --- a/apps/web/src/lib/queryKeys.ts +++ b/apps/web/src/lib/queryKeys.ts @@ -4,4 +4,5 @@ export const queryKeys = { transactions: ["transactions"] as const, alerts: ["alerts"] as const, + rules: ["rules"] as const, }; diff --git a/apps/web/src/pages/RulesPage.test.tsx b/apps/web/src/pages/RulesPage.test.tsx new file mode 100644 index 0000000..9e7bb57 --- /dev/null +++ b/apps/web/src/pages/RulesPage.test.tsx @@ -0,0 +1,202 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { RulesPage } from "@/pages/RulesPage"; +import type { Rule } from "@/lib/apiTypes"; +import { + errorResponse, + jsonResponse, + makeRule, + renderPage, + requestedUrls, + stubApi, +} from "@/test/api"; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +const amountRule = makeRule(1, { name: "Large amount", severity: "high" }); +const currencyRule = makeRule(2, { + name: "Watched currency", + field: "currency", + operator: "eq", + value: "GBP", + severity: "low", + enabled: false, +}); + +/** listHandler serves GET /rules from a mutable array. */ +function listHandler(rules: Rule[]) { + return () => jsonResponse({ items: rules }); +} + +describe("RulesPage", () => { + it("shows a loading state, then a captioned table with the rule fields", async () => { + stubApi(listHandler([amountRule, currencyRule])); + renderPage(, "/rules", { role: "operator" }); + expect(await screen.findByRole("status")).toHaveTextContent(/loading rules/i); + + const table = await screen.findByRole("table", { name: /monitoring rules/i }); + const rows = within(table).getAllByRole("row"); + expect(rows).toHaveLength(3); + expect(within(rows[1]).getByText("Large amount")).toBeInTheDocument(); + expect(within(rows[1]).getByText("Amount ≥ 500,000 minor units")).toBeInTheDocument(); + expect(within(rows[1]).getByText("high")).toBeInTheDocument(); + expect(within(rows[1]).getByText("Enabled")).toBeInTheDocument(); + expect(within(rows[1]).getByText("2 Jan 2026, 03:04:05 UTC")).toHaveAttribute( + "datetime", + "2026-01-02T03:04:05Z", + ); + expect(within(rows[2]).getByText("Currency = GBP")).toBeInTheDocument(); + expect(within(rows[2]).getByText("Disabled")).toBeInTheDocument(); + for (const name of ["Name", "Condition", "Severity", "Status", "Created"]) { + expect(within(table).getByRole("columnheader", { name })).toBeInTheDocument(); + } + }); + + it("shows admins an Actions column with Disable/Enable buttons", async () => { + stubApi(listHandler([amountRule, currencyRule])); + renderPage(, "/rules", { role: "admin" }); + + const table = await screen.findByRole("table"); + expect(within(table).getByRole("columnheader", { name: "Actions" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Disable rule Large amount" })).toBeEnabled(); + expect(screen.getByRole("button", { name: "Enable rule Watched currency" })).toBeEnabled(); + expect(screen.queryByText("Only admins can enable or disable rules.")).not.toBeInTheDocument(); + }); + + it("shows operators no toggles and a note", async () => { + stubApi(listHandler([amountRule, currencyRule])); + renderPage(, "/rules", { role: "operator" }); + + const table = await screen.findByRole("table"); + expect(within(table).queryByRole("columnheader", { name: "Actions" })).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: /rule/i })).not.toBeInTheDocument(); + expect(screen.getByText("Only admins can enable or disable rules.")).toBeInTheDocument(); + }); + + it("disables a rule with PATCH {enabled:false}, disables the button while pending and refetches", async () => { + const rules = [{ ...amountRule }]; + let release: () => void = () => {}; + const gate = new Promise((r) => (release = r)); + const api = stubApi(async (_url, init) => { + if (init?.method === "PATCH") { + await gate; + rules[0].enabled = false; + return jsonResponse(rules[0]); + } + return jsonResponse({ items: rules }); + }); + renderPage(, "/rules", { role: "admin" }); + + const button = await screen.findByRole("button", { name: "Disable rule Large amount" }); + await userEvent.click(button); + await waitFor(() => expect(button).toBeDisabled()); + + release(); + expect(await screen.findByRole("button", { name: "Enable rule Large amount" })).toBeEnabled(); + expect(screen.getByText("Disabled")).toBeInTheDocument(); + + const patch = api.mock.calls.find(([, init]) => init?.method === "PATCH"); + expect(new URL(String(patch?.[0])).pathname).toBe(`/rules/${amountRule.id}`); + expect(patch?.[1]?.body).toBe('{"enabled":false}'); + const headers = new Headers(patch?.[1]?.headers); + expect(headers.get("Content-Type")).toBe("application/json"); + expect(headers.get("Authorization")).toBe("Bearer test-token"); + const listCalls = requestedUrls(api).filter((u) => u.pathname === "/rules"); + expect(listCalls.length).toBeGreaterThanOrEqual(2); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + }); + + it("enables a disabled rule with PATCH {enabled:true}", async () => { + const api = stubApi((_url, init) => + init?.method === "PATCH" ? jsonResponse({ ...currencyRule, enabled: true }) : jsonResponse({ items: [currencyRule] }), + ); + renderPage(, "/rules", { role: "admin" }); + + await userEvent.click(await screen.findByRole("button", { name: "Enable rule Watched currency" })); + + await waitFor(() => { + const patch = api.mock.calls.find(([, init]) => init?.method === "PATCH"); + expect(patch?.[1]?.body).toBe('{"enabled":true}'); + }); + }); + + it("explains a 403 and lets the message be dismissed", async () => { + stubApi((_url, init) => + init?.method === "PATCH" + ? errorResponse(403, "FORBIDDEN", "admin role required") + : jsonResponse({ items: [amountRule] }), + ); + renderPage(, "/rules", { role: "admin" }); + + await userEvent.click(await screen.findByRole("button", { name: "Disable rule Large amount" })); + + expect(await screen.findByRole("alert")).toHaveTextContent("Your role can't change rules."); + expect(screen.getByRole("table")).toBeInTheDocument(); + + await userEvent.click(screen.getByRole("button", { name: "Dismiss" })); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + }); + + it("explains a 404 and refreshes the list", async () => { + let gone = false; + let listCalls = 0; + stubApi((_url, init) => { + if (init?.method === "PATCH") { + gone = true; + return errorResponse(404, "NOT_FOUND", "rule not found"); + } + listCalls += 1; + return jsonResponse({ items: gone ? [] : [amountRule] }); + }); + renderPage(, "/rules", { role: "admin" }); + + await userEvent.click(await screen.findByRole("button", { name: "Disable rule Large amount" })); + + expect(await screen.findByRole("alert")).toHaveTextContent( + "This rule no longer exists. The list has been refreshed.", + ); + await waitFor(() => expect(listCalls).toBeGreaterThanOrEqual(2)); + expect(await screen.findByText("No rules configured.")).toBeInTheDocument(); + }); + + it("shows the server message for any other toggle failure", async () => { + stubApi((_url, init) => + init?.method === "PATCH" + ? errorResponse(500, "INTERNAL", "database unavailable") + : jsonResponse({ items: [amountRule] }), + ); + renderPage(, "/rules", { role: "admin" }); + + await userEvent.click(await screen.findByRole("button", { name: "Disable rule Large amount" })); + + expect(await screen.findByRole("alert")).toHaveTextContent( + "Could not update the rule: database unavailable", + ); + }); + + it("shows an empty state", async () => { + stubApi(listHandler([])); + renderPage(, "/rules", { role: "admin" }); + expect(await screen.findByText("No rules configured.")).toBeInTheDocument(); + expect(screen.queryByRole("table")).not.toBeInTheDocument(); + }); + + it("shows an error state with retry", async () => { + let fail = true; + stubApi(() => + fail ? errorResponse(500, "INTERNAL", "database unavailable") : jsonResponse({ items: [amountRule] }), + ); + renderPage(, "/rules", { role: "operator" }); + + const alert = await screen.findByRole("alert"); + expect(alert).toHaveTextContent("Could not load rules"); + 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/RulesPage.tsx b/apps/web/src/pages/RulesPage.tsx new file mode 100644 index 0000000..1c6a72b --- /dev/null +++ b/apps/web/src/pages/RulesPage.tsx @@ -0,0 +1,84 @@ +import { useState } from "react"; +import { useAuth } from "@/app/AuthContext"; +import { Button } from "@/components/ui/button"; +import { EmptyState, ErrorState, LoadingState } from "@/components/DataStates"; +import { describeCondition } from "@/features/rules/condition"; +import { RuleToggle } from "@/features/rules/RuleToggle"; +import { useRules } from "@/features/rules/useRules"; +import { formatTimestamp } from "@/lib/time"; + +export function RulesPage() { + const { user } = useAuth(); + const isAdmin = user?.role === "admin"; + const [failure, setFailure] = useState(null); + const rules = useRules(); + + return ( +
+
+

+ Rules +

+

Monitoring rules applied to synthetic transactions.

+ {!isAdmin && ( +

Only admins can enable or disable rules.

+ )} +
+ + {failure && ( +
+

{failure}

+ +
+ )} + + {rules.isPending ? ( + + ) : rules.isError ? ( + void rules.refetch()} + /> + ) : rules.data.length === 0 ? ( + No rules configured. + ) : ( +
+ + + + + + + + + + {isAdmin && } + + + + {rules.data.map((rule) => ( + + + + + + + {isAdmin && ( + + )} + + ))} + +
Monitoring rules, oldest first
NameConditionSeverityStatusCreatedActions
{rule.name}{describeCondition(rule.field, rule.operator, rule.value)}{rule.severity}{rule.enabled ? "Enabled" : "Disabled"} + + + +
+
+ )} +
+ ); +} diff --git a/apps/web/src/test/api.tsx b/apps/web/src/test/api.tsx index d9ab1e4..09ae7fa 100644 --- a/apps/web/src/test/api.tsx +++ b/apps/web/src/test/api.tsx @@ -3,9 +3,10 @@ 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 { useEffect, type ReactElement, type ReactNode } from "react"; import { AuthProvider } from "@/app/AuthContext"; -import type { Alert, Transaction } from "@/lib/apiTypes"; +import { useAuth, type AuthUser } from "@/app/AuthContext"; +import type { Alert, Rule, Transaction } from "@/lib/apiTypes"; // Synthetic fixtures only. export function makeAlert(n: number, overrides: Partial = {}): Alert { @@ -22,6 +23,20 @@ export function makeAlert(n: number, overrides: Partial = {}): Alert { }; } +export function makeRule(n: number, overrides: Partial = {}): Rule { + return { + id: `e0000000-0000-4000-8000-${String(n).padStart(12, "0")}`, + name: `Example rule ${n}`, + field: "amount_minor", + operator: "gte", + value: "500000", + severity: "high", + enabled: true, + createdAt: "2026-01-02T03:04:05Z", + ...overrides, + }; +} + export function makeTransaction(n: number, overrides: Partial = {}): Transaction { return { id: `d0000000-0000-4000-8000-${String(n).padStart(12, "0")}`, @@ -48,11 +63,21 @@ export function errorResponse(status: number, code: string, message: string): Re export type ApiHandler = (url: URL, init: RequestInit | undefined) => Response | Promise; -/** stubApi replaces global fetch with a handler that receives parsed URLs. */ +/** + * stubApi replaces global fetch with a handler that receives parsed URLs. + * POST /login is answered here (the role is the email's local part, see + * renderPage) so tests can sign in as a given role. + */ export function stubApi(handler: ApiHandler) { - const mock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => - handler(new URL(String(input)), init), - ); + const mock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(String(input)); + if (url.pathname === "/login" && init?.method === "POST") { + const { email } = JSON.parse(String(init.body)) as { email: string }; + const role = email.split("@")[0] as AuthUser["role"]; + return jsonResponse({ accessToken: "test-token", user: { id: "u1", email, role } }); + } + return handler(url, init); + }); vi.stubGlobal("fetch", mock); return mock; } @@ -82,16 +107,31 @@ function LocationProbe() { 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 = "/") { +/** SignedInAs logs in with the stubbed /login and renders its children once signed in. */ +function SignedInAs({ role, children }: { role: AuthUser["role"]; children: ReactNode }) { + const { user, login } = useAuth(); + useEffect(() => { + void login(`${role}@example.com`, "example-password"); + }, [login, role]); + return user ? <>{children} : null; +} + +/** + * renderPage mounts a page at a path with auth, query client, router and a + * location probe. Pass `role` to sign in first (requires stubApi to be set up). + */ +export function renderPage(ui: ReactElement, path = "/", options: { role?: AuthUser["role"] } = {}) { const client = makeQueryClient(); + const page = ( + + {ui} + + + ); return render( - - {ui} - - + {options.role ? {page} : page} , );