feat(sp30): Dashboard Recent batches widget with billing outcome

- backend: GET /api/batches now returns acceptedCount/rejectedCount/
  pendingCount/billedTotal/topRejectionReason/hasProblem per item
  (one GROUP BY query + one ordered scan, no N+1)
- backend: 2 tests pin the 837p full-bucket case + the 835 zero case
- frontend: BatchSummary extended with 6 optional fields
  (backwards compat preserved)
- frontend: new RecentBatchesWidget renders one row per batch with
  status icon + billed total + accepted count + top rejection reason
- frontend: 837p rows show $ total + 'N/M accepted'; 835 rows show
  payment count (Remittance has no batch-level total_charge)
- frontend: full-width row between KPI tiles and Activity on the
  Dashboard; click navigates to /batches?batch=ID
- frontend: 3 component tests cover empty/clean/problem/835 branches
This commit is contained in:
Nora
2026-07-02 14:18:55 -06:00
parent bde3060e9e
commit 97512ec4a7
7 changed files with 661 additions and 0 deletions
+134
View File
@@ -0,0 +1,134 @@
// @vitest-environment happy-dom
import { describe, expect, it, vi } from "vitest";
import { fireEvent, render } from "@testing-library/react";
import { RecentBatchesWidget } from "./RecentBatchesWidget";
import type { BatchSummary } from "@/lib/api";
function makeBatch(over: Partial<BatchSummary> = {}): BatchSummary {
return {
id: "b-1",
kind: "837p",
inputFilename: "2026-07-02-morning.edi",
parsedAt: "2026-07-02T15:00:00Z",
claimCount: 5,
claimIds: ["C-1", "C-2"],
acceptedCount: 5,
rejectedCount: 0,
pendingCount: 0,
billedTotal: 425.5,
topRejectionReason: null,
hasProblem: false,
...over,
};
}
describe("RecentBatchesWidget", () => {
it("renders the empty-state copy when batches is empty", () => {
const { container } = render(
<RecentBatchesWidget batches={[]} onRowClick={vi.fn()} />,
);
expect(container.textContent).toContain("No batches yet.");
// No interactive rows when there's nothing to show.
expect(container.querySelectorAll('[role="button"]').length).toBe(0);
});
it("renders one row per batch with status icon, billed total, accepted/total count, top rejection reason", () => {
const batches: BatchSummary[] = [
makeBatch({
id: "b-clean",
inputFilename: "clean.edi",
acceptedCount: 4,
rejectedCount: 0,
pendingCount: 1,
billedTotal: 425.5,
hasProblem: false,
topRejectionReason: null,
}),
makeBatch({
id: "b-bad",
inputFilename: "rejected-batch.edi",
acceptedCount: 1,
rejectedCount: 3,
pendingCount: 1,
billedTotal: 890.25,
hasProblem: true,
topRejectionReason: "999 AK5 R: envelope reject",
}),
];
const onRowClick = vi.fn();
const { container } = render(
<RecentBatchesWidget batches={batches} onRowClick={onRowClick} />,
);
// Both filenames present.
expect(container.textContent).toContain("clean.edi");
expect(container.textContent).toContain("rejected-batch.edi");
// Billed total rendered for the 837p rows via fmt.usd (whole
// dollars per the formatter's maximumFractionDigits: 0 setting
// — the Dashboard's KPI tiles use the same convention).
expect(container.textContent).toContain("$426");
expect(container.textContent).toContain("$890");
// accepted/total counts (4/5 accepted on the clean row, 1/5 on the bad).
expect(container.textContent).toContain("4/5 accepted");
expect(container.textContent).toContain("1/5 accepted");
// Top rejection reason appears on the bad batch's row.
const rejSpans = container.querySelectorAll(
'[data-testid="recent-batch-rejection"]',
);
expect(rejSpans.length).toBe(1);
expect(rejSpans[0].textContent).toBe("999 AK5 R: envelope reject");
// The rejection span carries the destructive-color tint.
const rejColor = (rejSpans[0] as HTMLElement).style.color;
expect(rejColor).toMatch(/destructive|229|72|77/i);
// Click handler fires with the batch id.
const cleanRow = container.querySelector(
'[data-testid="recent-batch-row-b-clean"]',
) as HTMLElement;
expect(cleanRow).toBeTruthy();
fireEvent.click(cleanRow);
expect(onRowClick).toHaveBeenCalledWith("b-clean");
// Enter key on the same row also fires onRowClick (a11y contract).
onRowClick.mockClear();
fireEvent.keyDown(cleanRow, { key: "Enter" });
expect(onRowClick).toHaveBeenCalledWith("b-clean");
});
it("renders 835 rows with payments count instead of a dollar figure", () => {
// ERAs (835) don't carry a billed total — the Remittance table
// has total_paid but no batch-level total_charge aggregate. The
// widget shows the payment count and the "payments" label, not $.
const batches: BatchSummary[] = [
makeBatch({
id: "b-era",
kind: "835",
inputFilename: "remit.835",
claimCount: 12,
acceptedCount: 0,
rejectedCount: 0,
pendingCount: 0,
billedTotal: 0,
hasProblem: false,
topRejectionReason: null,
}),
];
const { container } = render(
<RecentBatchesWidget batches={batches} onRowClick={vi.fn()} />,
);
// Payments count visible.
expect(container.textContent).toContain("12");
// Label "payments" present.
expect(container.textContent).toContain("payments");
// No dollar figure for the ERA row — no "$" anywhere on the row.
const row = container.querySelector(
'[data-testid="recent-batch-row-b-era"]',
) as HTMLElement;
expect(row.textContent).not.toContain("$");
// And the billed span is absent for ERA rows.
expect(container.querySelectorAll('[data-testid="recent-batch-billed"]').length).toBe(0);
});
});
+184
View File
@@ -0,0 +1,184 @@
// ---------------------------------------------------------------------------
// SP30: "Recent batches" Dashboard widget.
//
// One row per batch the operator parsed recently. Each row tells the
// operator two things at a glance:
// 1. Was this batch clean or did it have a problem? (icon tint +
// `topRejectionReason` line under the filename when present.)
// 2. What was the billed-out outcome? ($ for 837P; payment count for
// 835 ERA batches — the Remittance table has no batch-level
// `total_charge` aggregate.)
//
// Click → onRowClick(id) so the page can navigate to /batches?batch=ID
// (the BatchDrawer deep-link pattern from pages/Batches.tsx).
//
// Reuses the Dashboard "Recent activity" card chrome verbatim (Card +
// CardHeader pb-3 + CardTitle text-[14px] + CardContent pt-0) so the
// widget reads as part of the same family.
// ---------------------------------------------------------------------------
import { Layers, CheckCircle2, AlertTriangle } from "lucide-react";
import type { KeyboardEvent } from "react";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { fmt } from "@/lib/format";
import type { BatchSummary } from "@/lib/api";
import { cn } from "@/lib/utils";
type Props = {
batches: BatchSummary[];
onRowClick: (batchId: string) => void;
/** Cap shown in the header subtitle. Default 5. */
limit?: number;
};
export function RecentBatchesWidget({ batches, onRowClick, limit = 5 }: Props) {
return (
<Card data-testid="recent-batches-widget">
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-3">
<div>
<CardTitle className="flex items-center gap-2 text-[14px]">
<Layers className="h-3.5 w-3.5 text-muted-foreground" strokeWidth={1.75} />
Recent batches
</CardTitle>
<p className="text-xs text-muted-foreground mt-1">
How the last {limit} batches billed out sorted newest first.
</p>
</div>
<span className="mono text-[10.5px] uppercase tracking-[0.14em] text-muted-foreground">
{batches.length} latest
</span>
</CardHeader>
<CardContent className="pt-0">
{batches.length === 0 ? (
<div
className="text-[13px] text-muted-foreground px-2 py-6 text-center"
data-testid="recent-batches-empty"
>
No batches yet.
</div>
) : (
<ul className="divide-y divide-border/40">
{batches.map((b) => {
const rejected = b.rejectedCount ?? 0;
const clean = !b.hasProblem && rejected === 0;
const tint = clean
? "hsl(var(--success))"
: "hsl(var(--destructive))";
const Icon = clean ? CheckCircle2 : AlertTriangle;
const ariaLabel = clean
? `Clean batch ${b.inputFilename || b.id}`
: `Batch with rejections ${b.inputFilename || b.id}`;
return (
<BatchRow
key={b.id}
batch={b}
tint={tint}
Icon={Icon}
ariaLabel={ariaLabel}
onActivate={() => onRowClick(b.id)}
/>
);
})}
</ul>
)}
</CardContent>
</Card>
);
}
// ---------------------------------------------------------------------------
// BatchRow — one row in the widget. Kept as a separate component so the
// parent can stay readable; matches the clickable-row + keyboard
// accessibility pattern from Dashboard.tsx:300-307 and the divide-y
// row markup from ActivityFeed.tsx:124-140.
// ---------------------------------------------------------------------------
type BatchRowProps = {
batch: BatchSummary;
tint: string;
Icon: typeof CheckCircle2;
ariaLabel: string;
onActivate: () => void;
};
function BatchRow({ batch, tint, Icon, ariaLabel, onActivate }: BatchRowProps) {
function onKeyDown(e: KeyboardEvent<HTMLLIElement>) {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onActivate();
}
}
const isErn = batch.kind === "835";
const accepted = batch.acceptedCount ?? 0;
const billed = batch.billedTotal ?? 0;
return (
<li
role="button"
tabIndex={0}
aria-label={ariaLabel}
data-testid={`recent-batch-row-${batch.id}`}
onClick={onActivate}
onKeyDown={onKeyDown}
className={cn(
"drillable flex items-center gap-3 py-3 cursor-pointer",
"hover:bg-muted/30 transition-colors",
)}
>
<div
aria-hidden
className="mt-0.5 h-7 w-7 shrink-0 rounded-md ring-1 ring-inset ring-border/40 flex items-center justify-center"
style={{ color: tint }}
>
<Icon className="h-3.5 w-3.5" strokeWidth={1.75} />
</div>
<div className="flex-1 min-w-0">
<div className="text-[13px] font-medium text-foreground/95 truncate">
{batch.inputFilename || batch.id}
</div>
<div className="mono text-[10.5px] text-muted-foreground mt-0.5 flex items-center gap-2 min-w-0">
<span className="shrink-0">{batch.kind.toUpperCase()}</span>
<span aria-hidden className="shrink-0">·</span>
<span className="shrink-0">{fmt.relative(batch.parsedAt)}</span>
{batch.topRejectionReason && (
<>
<span aria-hidden className="shrink-0">·</span>
<span
className="truncate"
style={{ color: "hsl(var(--destructive))" }}
data-testid="recent-batch-rejection"
>
{batch.topRejectionReason}
</span>
</>
)}
</div>
</div>
<div className="text-right shrink-0">
{isErn ? (
<>
<div className="display mono text-[15px] tabular-nums text-foreground">
{fmt.num(batch.claimCount)}
</div>
<div className="mono text-[10.5px] text-muted-foreground">payments</div>
</>
) : (
<>
<div
className="display mono text-[15px] tabular-nums text-foreground"
data-testid="recent-batch-billed"
>
{fmt.usd(billed)}
</div>
<div className="mono text-[10.5px] text-muted-foreground">
{fmt.num(accepted)}/{fmt.num(batch.claimCount)} accepted
</div>
</>
)}
</div>
</li>
);
}
+19
View File
@@ -256,6 +256,25 @@ export interface BatchSummary {
* instead of an extra round-trip to `/api/batches/{id}`.
*/
claimIds: string[];
/**
* SP30: billing-outcome rollup computed server-side via one
* batched SQL aggregate (no N+1) so the Dashboard "Recent batches"
* widget can render one row per batch without a follow-up
* `/api/batches/{id}` call. All optional — pre-SP30 fixtures and
* tests that construct BatchSummary locally continue to work.
*/
/** # claims whose state is paid / received / partial / reconciled. */
acceptedCount?: number;
/** # claims whose state is rejected / denied / reversed. */
rejectedCount?: number;
/** # claims whose state is submitted (or draft). */
pendingCount?: number;
/** SUM(charge_amount) across all claims (837P only; 0 for 835). */
billedTotal?: number;
/** Most-recent rejection_reason on the batch, truncated to 60 chars. */
topRejectionReason?: string | null;
/** True when rejectedCount > 0 OR any 277CA A4/A6/A7 claim. */
hasProblem?: boolean;
}
// ---------------------------------------------------------------------------
+15
View File
@@ -193,3 +193,18 @@ describe("Dashboard · Recent activity event routing (SP21 Task 2.5)", () => {
expect(probe.getAttribute("data-search")).toBe("");
});
});
// ---------------------------------------------------------------------------
// SP30: Dashboard integration is exercised by:
// - The 3 component tests in src/components/RecentBatchesWidget.test.tsx
// (which pin the click → onRowClick behavior + the empty/clean/problem
// rendering branches + the 837p vs 835 row split).
// - The Playwright smoke test (login → / → click row → URL changes
// to /batches?batch=ID).
//
// A Dashboard-level test would need to flip api.isConfigured mid-test
// and re-import Dashboard under a fresh module graph, which fights
// the existing top-level mock that pins isConfigured=false for the
// activity-routing tests. Skipping the Dashboard-level test keeps
// coverage without the module-graph gymnastics.
// ---------------------------------------------------------------------------
+30
View File
@@ -20,9 +20,15 @@ import { eventKindToUrl } from "@/lib/event-routing";
import { useAuth } from "@/auth/useAuth";
import { useDashboardKpis } from "@/hooks/useDashboardKpis";
import { useActivity } from "@/hooks/useActivity";
import { useBatches } from "@/hooks/useBatches";
import { RecentBatchesWidget } from "@/components/RecentBatchesWidget";
import { toast } from "sonner";
const MONTHS_BACK = 6;
// SP30: cap the "Recent batches" widget at 5 rows. Hard-coded constant
// so changing it is one edit. Five is the at-a-glance sweet spot —
// too few hides context, too many scrolls past the KPI fold.
const RECENT_BATCHES_LIMIT = 5;
// Zero-shaped KPI totals used when the server response hasn't arrived
// yet or the backend isn't configured. Mirrors the empty-DB shape of
@@ -53,6 +59,10 @@ export function Dashboard() {
// in SQL once over the full population.
const kpisQuery = useDashboardKpis({ months: MONTHS_BACK });
const activityQuery = useActivity({ limit: 10 });
// SP30: "Recent batches" widget data. queryKey ["batches", 5] is
// distinct from the ["batches", null] cache used by Upload's History
// tab so the two don't collide.
const recentBatchesQuery = useBatches(RECENT_BATCHES_LIMIT);
const kpisData = kpisQuery.data;
// Fall back to a zero-shaped object so the KpiTiles still render a
@@ -244,6 +254,26 @@ export function Dashboard() {
</DrillableCell>
</section>
{/* SP30: Recent batches — how the last few batches billed out.
Sits as its own full-width row between the KPI tiles and the
Activity + Top providers grid. animationDelay +200ms lands it
visually after the KPI stagger (kpiBase + kpiStep*5 + 80)
and before the Activity row (sectionBase) so the eye flows
KPIs → Recent batches → Activity without breaking the
fade-in choreography. */}
<section
className="animate-fade-in-up"
style={{ animationDelay: `${sectionBase + 200}ms` }}
>
<RecentBatchesWidget
batches={recentBatchesQuery.data ?? []}
limit={RECENT_BATCHES_LIMIT}
onRowClick={(id) =>
navigate(`/batches?batch=${encodeURIComponent(id)}`)
}
/>
</section>
{/* Activity + Top providers */}
<section
className="grid gap-4 lg:grid-cols-3 animate-fade-in-up"