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>
);
}