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
3 changes: 2 additions & 1 deletion apps/web/src/app/AppShell.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
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";

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 },
];

Expand Down
1 change: 1 addition & 0 deletions apps/web/src/app/routes.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/app/routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -21,6 +22,7 @@ export function AppRoutes() {
<Route index element={<Navigate to="/dashboard" replace />} />
<Route path="/dashboard" element={<DashboardPage />} />
<Route path="/alerts" element={<AlertsPage />} />
<Route path="/rules" element={<RulesPage />} />
<Route path="/ops" element={<OpsPage />} />
</Route>
</Route>
Expand Down
28 changes: 28 additions & 0 deletions apps/web/src/features/rules/RuleToggle.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<Button
type="button"
size="sm"
variant="outline"
disabled={toggle.isPending}
aria-label={`${label} rule ${rule.name}`}
onClick={() => toggle.mutate({ id: rule.id, enabled: !rule.enabled })}
>
{label}
</Button>
);
}
35 changes: 35 additions & 0 deletions apps/web/src/features/rules/condition.test.ts
Original file line number Diff line number Diff line change
@@ -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}`);
});
});
24 changes: 24 additions & 0 deletions apps/web/src/features/rules/condition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const symbols: Record<string, string> = { 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}`;
}
39 changes: 39 additions & 0 deletions apps/web/src/features/rules/useRuleToggle.ts
Original file line number Diff line number Diff line change
@@ -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<Rule, ApiError, ToggleVars>({
mutationFn: ({ id, enabled }) =>
requestJson<Rule>(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 }),
});
}
14 changes: 14 additions & 0 deletions apps/web/src/features/rules/useRules.ts
Original file line number Diff line number Diff line change
@@ -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,
});
}
13 changes: 13 additions & 0 deletions apps/web/src/lib/apiTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T> {
items: T[];
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/lib/queryKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@
export const queryKeys = {
transactions: ["transactions"] as const,
alerts: ["alerts"] as const,
rules: ["rules"] as const,
};
Loading