merge: SP14 5-lane Inbox UI + acknowledge action into main

This commit is contained in:
Tyler
2026-06-21 00:13:57 -06:00
15 changed files with 704 additions and 18 deletions
+73 -1
View File
@@ -1105,6 +1105,78 @@ def inbox_dismiss_candidates(body: dict):
return {"ok": True, "dismissed_count": len(pairs)}
# ---------------------------------------------------------------------------
# SP14: Payer-Rejected acknowledge
#
# Operator hits "Acknowledge" on the Payer-Rejected Inbox lane to clear
# the claim from the working surface. We don't delete the rejection
# (the original payer_rejected_* fields stay for SP11 audit), we just
# set payer_rejected_acknowledged_at so the lane query filters it out.
#
# Idempotent: re-acknowledging an already-acknowledged claim is a noop
# (the timestamp is not bumped). Returns the count actually transitioned
# so the UI can show "3 of 5 were already acknowledged".
# ---------------------------------------------------------------------------
@app.post("/api/inbox/payer-rejected/acknowledge")
def inbox_acknowledge_payer_rejected(body: dict):
"""Mark Payer-Rejected claims as acknowledged by the operator."""
claim_ids = body.get("claim_ids") or []
actor = body.get("actor") or "operator"
if not isinstance(claim_ids, list) or not claim_ids:
raise HTTPException(400, "claim_ids must be a non-empty list")
if not all(isinstance(c, str) for c in claim_ids):
raise HTTPException(400, "claim_ids must be a list of strings")
with db.SessionLocal()() as session:
from cyclone.db import Claim
now = datetime.now(timezone.utc)
transitioned = 0
already_acked = 0
not_found = 0
not_rejected = 0
for cid in claim_ids:
claim = session.get(Claim, cid)
if claim is None:
not_found += 1
continue
if claim.payer_rejected_at is None:
not_rejected += 1
continue
if claim.payer_rejected_acknowledged_at is not None:
already_acked += 1
continue
claim.payer_rejected_acknowledged_at = now
claim.payer_rejected_acknowledged_actor = actor
transitioned += 1
# SP11: audit event for the acknowledge action.
try:
from cyclone.audit_log import append_event, AuditEvent
append_event(session, AuditEvent(
event_type="claim.payer_rejected_acknowledged",
entity_type="claim",
entity_id=claim.id,
actor=actor,
payload={
"payer_rejected_status_code": claim.payer_rejected_status_code,
"payer_rejected_by_277ca_id": claim.payer_rejected_by_277ca_id,
},
))
except Exception: # noqa: BLE001
# Audit append is best-effort; don't block the operator's
# acknowledge action on an audit-log failure.
pass
if transitioned:
session.commit()
return {
"ok": True,
"transitioned": transitioned,
"already_acked": already_acked,
"not_found": not_found,
"not_rejected": not_rejected,
}
@app.post("/api/inbox/rejected/resubmit")
def inbox_resubmit_rejected(
request: Request,
@@ -1202,7 +1274,7 @@ def inbox_resubmit_rejected(
@app.get("/api/inbox/export.csv")
def inbox_export_csv(lane: str):
"""Stream a CSV for a single lane."""
if lane not in {"rejected", "candidates", "unmatched", "done_today"}:
if lane not in {"rejected", "candidates", "unmatched", "done_today", "payer_rejected"}:
raise HTTPException(400, f"unknown lane: {lane}")
dismissed_pairs = getattr(app.state, "dismissed_pairs", set())
with db.SessionLocal()() as session:
+10
View File
@@ -239,6 +239,16 @@ class Claim(Base):
payer_rejected_by_277ca_id: Mapped[Optional[str]] = mapped_column(
String(64), nullable=True
)
# SP14: when the operator hits "Acknowledge" on the Payer-Rejected
# lane, we set this timestamp. The lane query filters on it being
# NULL so acknowledged claims drop out of the working surface. The
# original payer_rejected_* fields stay intact for audit (SP11).
payer_rejected_acknowledged_at: Mapped[Optional[datetime]] = mapped_column(
DateTime(timezone=True), nullable=True
)
payer_rejected_acknowledged_actor: Mapped[Optional[str]] = mapped_column(
String(64), nullable=True
)
resubmit_count: Mapped[int] = mapped_column(
Integer, nullable=False, default=0, server_default=text("0")
)
+14 -1
View File
@@ -73,6 +73,12 @@ def _claim_to_row(
"payer_rejected_reason": c.payer_rejected_reason,
"payer_rejected_status_code": c.payer_rejected_status_code,
"payer_rejected_by_277ca_id": c.payer_rejected_by_277ca_id,
# SP14: acknowledgment tracking. Always null on the lane
# (we filter acknowledged claims out) but exposed for
# forward-compat if we later add a "Recently acknowledged"
# inspector view.
"payer_rejected_acknowledged_at": _isoformat(c.payer_rejected_acknowledged_at),
"payer_rejected_acknowledged_actor": c.payer_rejected_acknowledged_actor,
}
@@ -192,8 +198,15 @@ def compute_lanes(session: Session, *, dismissed_pairs: Iterable[frozenset]) ->
# by the payer after we submitted a syntactically-valid file).
# We don't filter by Claim.state here because the claim may still
# be in SUBMITTED state — the payer just hasn't paid it yet.
#
# SP14: filter out claims the operator has already acknowledged.
# The original payer_rejected_* fields stay intact for audit;
# only the working surface (this lane) is filtered.
payer_rejected_claims = (
session.query(Claim).filter(Claim.payer_rejected_at.is_not(None)).all()
session.query(Claim)
.filter(Claim.payer_rejected_at.is_not(None))
.filter(Claim.payer_rejected_acknowledged_at.is_(None))
.all()
)
pr_matched, pr_total = _line_count_lookup(session, payer_rejected_claims)
matched_counts.update(pr_matched)
@@ -0,0 +1,22 @@
-- version: 10
-- SP14: Payer-Rejected lane acknowledge
-- When the operator reviews a payer-rejected claim, they hit the
-- "Acknowledge" bulk action. We mark the claim with the timestamp so
-- the lane query can filter it out (it stays in the DB for audit but
-- doesn't show up in the operator's working surface).
--
-- Why a separate column instead of clearing payer_rejected_at:
-- * Audit trail: SP11's hash-chained audit_log needs the *original*
-- rejection event intact. Clearing the timestamp would erase the
-- evidence of the payer saying "no" — exactly what auditors want
-- to see.
-- * Reconciliation: future SPs that match payer-rejected claims
-- against appeals (e.g. SP17) can still see the original status
-- code and reason.
ALTER TABLE claims ADD COLUMN payer_rejected_acknowledged_at TEXT;
ALTER TABLE claims ADD COLUMN payer_rejected_acknowledged_actor TEXT;
CREATE INDEX idx_claims_payer_rejected_unack
ON claims(payer_rejected_at)
WHERE payer_rejected_acknowledged_at IS NULL;
+5 -5
View File
@@ -51,18 +51,18 @@ def test_migration_0002_creates_acks_table():
def test_migration_latest_idempotent_on_fresh_db():
"""Re-running the migration on the same DB must be a no-op (PRAGMA
user_version already at the latest version currently 9 after
user_version already at the latest version currently 10 after
0004-0006 line_reconciliation, 0005 ta1_acks, SP9's 0007
providers/payers/clearhouse, SP10's 0008 payer_rejected, and
SP11's 0009 audit_log)."""
providers/payers/clearhouse, SP10's 0008 payer_rejected,
SP11's 0009 audit_log, and SP14's 0010 payer_rejected_acknowledged)."""
with db.engine().begin() as c:
v1 = c.exec_driver_sql("PRAGMA user_version").scalar() or 0
assert v1 == 9
assert v1 == 10
# A second run should not raise and should not bump the version.
db_migrate.run(db.engine())
with db.engine().begin() as c:
v2 = c.exec_driver_sql("PRAGMA user_version").scalar() or 0
assert v2 == 9
assert v2 == 10
def test_add_ack_persists_row():
@@ -0,0 +1,105 @@
"""SP14 — Lane filter drops acknowledged payer-rejected claims.
The Payer-Rejected Inbox lane must not include claims the operator
has already acknowledged. This is the working-surface UX: acknowledged
claims drop out so the operator only sees new rejections.
"""
from __future__ import annotations
from datetime import datetime, timezone
import pytest
from cyclone import db
from cyclone.db import Batch, Claim, ClaimState
from cyclone.inbox_lanes import compute_lanes
@pytest.fixture(autouse=True)
def _setup(tmp_path, monkeypatch):
monkeypatch.setenv("CYCLONE_DB_URL", f"sqlite:///{tmp_path}/test.db")
db._reset_for_tests()
db.init_db()
def _seed(*, acked: bool = False) -> str:
now = datetime.now(timezone.utc)
cid = "C1"
with db.SessionLocal()() as session:
batch = Batch(
id="b-1", kind="837p",
input_filename="t.x12", parsed_at=now,
)
session.add(batch)
session.flush()
claim = Claim(
id=cid, batch_id=batch.id, patient_control_number=cid,
state=ClaimState.SUBMITTED, charge_amount=100,
payer_rejected_at=now,
payer_rejected_status_code="A7",
payer_rejected_reason="invalid dx",
)
if acked:
claim.payer_rejected_acknowledged_at = now
claim.payer_rejected_acknowledged_actor = "operator"
session.add(claim)
session.commit()
return cid
def test_unacknowledged_claim_appears_in_lane():
_seed(acked=False)
with db.SessionLocal()() as session:
lanes = compute_lanes(session, dismissed_pairs=set())
assert len(lanes.payer_rejected) == 1
assert lanes.payer_rejected[0]["id"] == "C1"
def test_acknowledged_claim_drops_out_of_lane():
_seed(acked=True)
with db.SessionLocal()() as session:
lanes = compute_lanes(session, dismissed_pairs=set())
assert lanes.payer_rejected == []
def test_mix_of_acked_and_unacked():
"""Only the unacknowledged one shows up."""
now = datetime.now(timezone.utc)
with db.SessionLocal()() as session:
batch = Batch(
id="b-1", kind="837p",
input_filename="t.x12", parsed_at=now,
)
session.add(batch)
session.flush()
for i, acked in enumerate([True, False, True, False]):
claim = Claim(
id=f"C{i}", batch_id=batch.id,
patient_control_number=f"PCN-{i}",
state=ClaimState.SUBMITTED, charge_amount=100,
payer_rejected_at=now,
payer_rejected_status_code="A7",
)
if acked:
claim.payer_rejected_acknowledged_at = now
session.add(claim)
session.commit()
with db.SessionLocal()() as session:
lanes = compute_lanes(session, dismissed_pairs=set())
ids = [r["id"] for r in lanes.payer_rejected]
assert sorted(ids) == ["C1", "C3"]
def test_lane_row_carries_ack_fields_for_forward_compat():
"""The row payload still carries the ack fields (all null on the lane)
so future views that want a 'Recently acknowledged' section don't need
a schema change."""
_seed(acked=False)
with db.SessionLocal()() as session:
lanes = compute_lanes(session, dismissed_pairs=set())
row = lanes.payer_rejected[0]
assert "payer_rejected_acknowledged_at" in row
assert row["payer_rejected_acknowledged_at"] is None
assert "payer_rejected_acknowledged_actor" in row
assert row["payer_rejected_acknowledged_actor"] is None
@@ -0,0 +1,168 @@
"""SP14 — Payer-Rejected acknowledge endpoint tests.
The endpoint marks payer-rejected claims as acknowledged so the
working-surface lane query filters them out. The original
payer_rejected_* fields stay intact (SP11 audit).
"""
from __future__ import annotations
import pytest
from cyclone import db
from cyclone.db import Claim, ClaimState
from cyclone.audit_log import verify_chain
@pytest.fixture(autouse=True)
def _setup(tmp_path, monkeypatch):
monkeypatch.setenv("CYCLONE_DB_URL", f"sqlite:///{tmp_path}/test.db")
db._reset_for_tests()
db.init_db()
def _make_claim(claim_id: str, *, payer_rejected: bool = True) -> None:
"""Insert a minimal claim with optional payer_rejected markers."""
from datetime import datetime, timezone
from cyclone.db import Batch
with db.SessionLocal()() as session:
batch = Batch(
id=f"b-{claim_id}",
kind="837p",
input_filename="t.x12",
parsed_at=datetime.now(timezone.utc),
)
session.add(batch)
session.flush()
claim = Claim(
id=claim_id,
batch_id=batch.id,
patient_control_number=claim_id,
state=ClaimState.SUBMITTED,
charge_amount=100,
)
if payer_rejected:
now = datetime.now(timezone.utc)
claim.payer_rejected_at = now
claim.payer_rejected_reason = "invalid diagnosis code"
claim.payer_rejected_status_code = "A7"
session.add(claim)
session.commit()
def test_acknowledge_marks_unacknowledged_claim():
_make_claim("C1", payer_rejected=True)
from fastapi.testclient import TestClient
from cyclone.api import app
with TestClient(app) as client:
r = client.post(
"/api/inbox/payer-rejected/acknowledge",
json={"claim_ids": ["C1"], "actor": "operator"},
)
assert r.status_code == 200, r.text
body = r.json()
assert body["ok"] is True
assert body["transitioned"] == 1
assert body["already_acked"] == 0
assert body["not_found"] == 0
assert body["not_rejected"] == 0
with db.SessionLocal()() as session:
c = session.get(Claim, "C1")
assert c.payer_rejected_acknowledged_at is not None
assert c.payer_rejected_acknowledged_actor == "operator"
# Original fields stay intact for audit.
assert c.payer_rejected_at is not None
assert c.payer_rejected_status_code == "A7"
assert c.payer_rejected_reason == "invalid diagnosis code"
def test_acknowledge_is_idempotent():
_make_claim("C1", payer_rejected=True)
from fastapi.testclient import TestClient
from cyclone.api import app
with TestClient(app) as client:
r1 = client.post(
"/api/inbox/payer-rejected/acknowledge",
json={"claim_ids": ["C1"]},
)
assert r1.json()["transitioned"] == 1
r2 = client.post(
"/api/inbox/payer-rejected/acknowledge",
json={"claim_ids": ["C1"]},
)
assert r2.json()["transitioned"] == 0
assert r2.json()["already_acked"] == 1
def test_acknowledge_skips_non_payer_rejected_claims():
_make_claim("C1", payer_rejected=False)
from fastapi.testclient import TestClient
from cyclone.api import app
with TestClient(app) as client:
r = client.post(
"/api/inbox/payer-rejected/acknowledge",
json={"claim_ids": ["C1"]},
)
assert r.status_code == 200
body = r.json()
assert body["transitioned"] == 0
assert body["not_rejected"] == 1
def test_acknowledge_counts_missing_ids():
from fastapi.testclient import TestClient
from cyclone.api import app
with TestClient(app) as client:
r = client.post(
"/api/inbox/payer-rejected/acknowledge",
json={"claim_ids": ["nope"]},
)
assert r.status_code == 200
body = r.json()
assert body["transitioned"] == 0
assert body["not_found"] == 1
def test_acknowledge_empty_claim_ids_400():
from fastapi.testclient import TestClient
from cyclone.api import app
with TestClient(app) as client:
r = client.post(
"/api/inbox/payer-rejected/acknowledge",
json={"claim_ids": []},
)
assert r.status_code == 400
def test_acknowledge_writes_audit_event():
_make_claim("C1", payer_rejected=True)
from fastapi.testclient import TestClient
from cyclone.api import app
with TestClient(app) as client:
r = client.post(
"/api/inbox/payer-rejected/acknowledge",
json={"claim_ids": ["C1"], "actor": "alice"},
)
assert r.status_code == 200
# SP11: the chain is intact and includes the new event.
with db.SessionLocal()() as session:
result = verify_chain(session)
assert result.ok, f"chain broken: {result.reason} at {result.first_bad_id}"
# And the event itself is queryable.
import json as _json
from cyclone.db import AuditLog
with db.SessionLocal()() as session:
events = (
session.query(AuditLog)
.filter(AuditLog.event_type == "claim.payer_rejected_acknowledged")
.all()
)
assert len(events) == 1
e = events[0]
assert e.entity_type == "claim"
assert e.entity_id == "C1"
assert e.actor == "alice"
payload = _json.loads(e.payload_json) if e.payload_json else {}
assert payload["payer_rejected_status_code"] == "A7"
+27 -1
View File
@@ -1,6 +1,6 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, render, screen, fireEvent } from "@testing-library/react";
import { cleanup, render, fireEvent } from "@testing-library/react";
import { BulkBar } from "./BulkBar";
afterEach(() => cleanup());
@@ -12,6 +12,7 @@ describe("BulkBar", () => {
lane="rejected"
count={3}
onResubmit={vi.fn()}
onAcknowledge={() => {}}
onDismiss={vi.fn()}
onExport={vi.fn()}
/>,
@@ -28,6 +29,7 @@ describe("BulkBar", () => {
lane="rejected"
count={2}
onResubmit={onResubmit}
onAcknowledge={() => {}}
onDismiss={() => {}}
onExport={() => {}}
/>,
@@ -39,12 +41,36 @@ describe("BulkBar", () => {
expect(onResubmit).toHaveBeenCalledOnce();
});
it("SP14: payer_rejected lane shows Acknowledge (not Resubmit/Dismiss)", () => {
// Payer-rejected claims are not eligible for resubmit (the payer
// already said no); the operator can only acknowledge them as
// "I've seen this" and export the row set for follow-up.
const onAcknowledge = vi.fn();
const { container, getByTestId } = render(
<BulkBar
lane="payer_rejected"
count={4}
onResubmit={() => {}}
onAcknowledge={onAcknowledge}
onDismiss={() => {}}
onExport={() => {}}
/>,
);
expect(container.textContent).toMatch(/acknowledge/i);
expect(container.textContent).not.toMatch(/re-?submit/i);
expect(container.textContent).not.toMatch(/dismiss/i);
const ack = getByTestId("payer-rejected-acknowledge");
fireEvent.click(ack);
expect(onAcknowledge).toHaveBeenCalledOnce();
});
it("hides when count is zero", () => {
const { container } = render(
<BulkBar
lane="rejected"
count={0}
onResubmit={() => {}}
onAcknowledge={() => {}}
onDismiss={() => {}}
onExport={() => {}}
/>,
+38 -1
View File
@@ -1,13 +1,40 @@
// ---------------------------------------------------------------------------
// BulkBar
//
// Per-lane floating action bar. Each Inbox lane has its own BulkBar —
// the bar shows when the lane has a selection and exposes the actions
// appropriate to that lane:
//
// * rejected → Re-submit (move back to SUBMITTED)
// * payer_rejected → Acknowledge (drop from working surface; SP14)
// * candidates → Dismiss (suppress a remit/claim pair)
// * unmatched → (no destructive action; just export)
// * done_today → (read-only; just export)
//
// Every lane gets the Export CSV action so the operator can ship
// anything actionable to a file for off-system follow-up (appeals,
// re-keying, posting to the billing system of record, etc).
// ---------------------------------------------------------------------------
type LaneKey =
| "rejected"
| "payer_rejected"
| "candidates"
| "unmatched"
| "done_today";
export function BulkBar({
lane,
count,
onResubmit,
onAcknowledge,
onDismiss,
onExport,
}: {
lane: "rejected" | "candidates" | "unmatched" | "done_today";
lane: LaneKey;
count: number;
onResubmit: () => void;
onAcknowledge: () => void;
onDismiss: () => void;
onExport: () => void;
}) {
@@ -52,6 +79,16 @@ export function BulkBar({
Re-submit ({count})
</button>
)}
{lane === "payer_rejected" && (
<button
onClick={onAcknowledge}
data-testid="payer-rejected-acknowledge"
className="px-2.5 py-1 rounded-sm uppercase tracking-[0.12em] transition-colors hover:bg-[color:var(--tt-amber)]/10 focus-visible:outline-none focus-visible:bg-[color:var(--tt-amber)]/10"
style={{ color: "var(--tt-ink)", fontWeight: 600 }}
>
Acknowledge ({count})
</button>
)}
{lane === "candidates" && (
<button
onClick={onDismiss}
+13
View File
@@ -1,3 +1,16 @@
// ---------------------------------------------------------------------------
// InboxHeader
//
// Compact working-surface header: the day/date, a live clock, and the
// two top-line counts ("N items need eyes" and "N done today") that
// anchor the operator's day. "Need eyes" is computed by the Inbox
// page (sum of actionable lanes) and passed in.
//
// SP14: payer_rejected (277CA) is now part of the actionable lanes —
// it's a working-surface rejection that needs operator follow-up.
// The Inbox page sums it into the needEyes count.
// ---------------------------------------------------------------------------
export function InboxHeader({
needEyesCount,
doneTodayCount,
+3
View File
@@ -39,6 +39,8 @@ function emptyLanesPayload() {
ok: true,
json: async () => ({
rejected: [],
// SP14: payer-rejected lane was added to the working surface.
payer_rejected: [],
candidates: [],
unmatched: [],
done_today: [],
@@ -74,6 +76,7 @@ describe("useInboxLanes", () => {
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.lanes).toEqual({
rejected: [],
payer_rejected: [],
candidates: [],
unmatched: [],
done_today: [],
+2
View File
@@ -31,6 +31,8 @@ const REFETCH_DEBOUNCE_MS = 250;
export function useInboxLanes() {
const [lanes, setLanes] = useState<InboxLanes>({
rejected: [],
// SP14: the 5th working-surface lane (277CA STC A4/A6/A7).
payer_rejected: [],
candidates: [],
unmatched: [],
done_today: [],
+52 -4
View File
@@ -1,9 +1,13 @@
// ---------------------------------------------------------------------------
// Inbox API client (sub-project 6).
//
// Mirrors the four-lane working surface: rejected / candidates / unmatched /
// done_today. Plus the actions: manual match, dismiss, resubmit, export.
// All non-2xx responses throw (so callers can branch on status).
// Mirrors the five-lane working surface: rejected / payer_rejected /
// candidates / unmatched / done_today. Plus the actions: manual match,
// dismiss, resubmit, acknowledge, export. All non-2xx responses throw
// (so callers can branch on status).
//
// SP14: added the `payer_rejected` lane (277CA STC A4/A6/A7) and the
// `acknowledge` action — distinct from the 999 envelope `rejected` lane.
// ---------------------------------------------------------------------------
export type ScoreBreakdown = {
@@ -39,6 +43,17 @@ export type InboxClaimRow = {
matched_lines: number;
total_lines: number;
} | null;
// SP10/SP14: payer-side rejection fields. Populated on the
// `payer_rejected` lane with the 277CA STC category, reason,
// and source 277CA id. The ack fields are always null on the
// lane (we filter acknowledged claims out) but exposed for
// forward-compat.
payer_rejected_at?: string | null;
payer_rejected_reason?: string | null;
payer_rejected_status_code?: string | null;
payer_rejected_by_277ca_id?: string | null;
payer_rejected_acknowledged_at?: string | null;
payer_rejected_acknowledged_actor?: string | null;
};
export type InboxCandidateRow = {
@@ -59,6 +74,8 @@ export type InboxCandidateRow = {
export type InboxLanes = {
rejected: InboxClaimRow[];
/** SP14: 277CA STC A4/A6/A7 — payer-side rejection, distinct from 999. */
payer_rejected: InboxClaimRow[];
candidates: InboxCandidateRow[];
unmatched: InboxClaimRow[];
done_today: InboxClaimRow[];
@@ -173,7 +190,38 @@ export async function resubmitRejectedWithDownload(
}
export function exportInboxCsvUrl(
lane: "rejected" | "candidates" | "unmatched" | "done_today",
lane:
| "rejected"
| "payer_rejected"
| "candidates"
| "unmatched"
| "done_today",
): string {
return joinUrl(`/api/inbox/export.csv?lane=${lane}`);
}
// ---------------------------------------------------------------------------
// SP14: Payer-Rejected acknowledge
//
// Marks the listed claims as acknowledged by the operator. Acknowledged
// claims drop out of the Payer-Rejected Inbox lane. The original 277CA
// rejection event stays in the audit log (SP11) — we only flip a
// working-surface flag.
// ---------------------------------------------------------------------------
export type AcknowledgeResult = {
ok: boolean;
transitioned: number;
already_acked: number;
not_found: number;
not_rejected: number;
};
export async function acknowledgePayerRejected(
claimIds: string[],
actor: string = "operator",
): Promise<AcknowledgeResult> {
return postJson<AcknowledgeResult>(
"/api/inbox/payer-rejected/acknowledge",
{ claim_ids: claimIds, actor },
);
}
+111 -1
View File
@@ -12,13 +12,17 @@ afterEach(() => {
});
describe("Inbox page", () => {
it("renders the four lane headers", async () => {
it("renders the five lane headers", async () => {
// SP14: the Payer-Rejected lane was added (277CA STC A4/A6/A7).
// The Inbox now renders 5 lanes: REJECTED, PAYER REJECTED,
// CANDIDATES, UNMATCHED, DONE.
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
rejected: [],
payer_rejected: [],
candidates: [],
unmatched: [],
done_today: [],
@@ -28,12 +32,117 @@ describe("Inbox page", () => {
const { container } = render(<Inbox />);
await waitFor(() => {
expect(container.textContent).toContain("REJECTED");
expect(container.textContent).toContain("PAYER REJECTED");
expect(container.textContent).toContain("CANDIDATES");
expect(container.textContent).toContain("UNMATCHED");
expect(container.textContent).toContain("DONE");
});
});
it("SP14: payer-rejected row count rolls up into the need-eyes header", async () => {
// The "need eyes" total in the header is the operator's
// anchor for the day. Payer-rejected claims are actionable
// (operator must acknowledge or follow up), so they count
// toward the need-eyes total alongside 999 rejected, candidates,
// and unmatched.
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
rejected: [],
payer_rejected: [
{ id: "PR1", kind: "claim", patient_control_number: "PR1",
charge_amount: 250, payer_id: "CO_TXIX", provider_npi: "1881068062",
state: "submitted", rejection_reason: "A7 invalid dx",
service_date_from: null, payer_rejected_status_code: "A7",
payer_rejected_reason: "invalid diagnosis",
payer_rejected_at: "2026-06-20T10:00:00Z" },
],
candidates: [],
unmatched: [],
done_today: [],
}),
}),
);
const { container } = render(<Inbox />);
await waitFor(() => {
expect(container.textContent).toContain("1");
expect(container.textContent).toContain("items need eyes");
});
});
it("SP14: acknowledging selected payer-rejected claims calls the API and refetches", async () => {
// The user selects a payer-rejected claim, hits Acknowledge, and
// the inbox calls /api/inbox/payer-rejected/acknowledge with the
// claim id, then refetches the lane payload.
const fetchMock = vi.fn().mockImplementation(async (url: string) => {
if (url.includes("/api/inbox/lanes")) {
return {
ok: true,
json: async () => ({
rejected: [],
payer_rejected: [
{ id: "PR1", kind: "claim", patient_control_number: "PR1",
charge_amount: 250, payer_id: "CO_TXIX", provider_npi: "1881068062",
state: "submitted", rejection_reason: "A7 invalid dx",
service_date_from: null, payer_rejected_status_code: "A7",
payer_rejected_reason: "invalid diagnosis",
payer_rejected_at: "2026-06-20T10:00:00Z" },
],
candidates: [],
unmatched: [],
done_today: [],
}),
};
}
if (url.includes("/api/inbox/payer-rejected/acknowledge")) {
return {
ok: true,
json: async () => ({
ok: true,
transitioned: 1,
already_acked: 0,
not_found: 0,
not_rejected: 0,
}),
};
}
return { ok: true, json: async () => ({}) };
});
vi.stubGlobal("fetch", fetchMock);
const { container, getByTestId } = render(<Inbox />);
await waitFor(() => {
expect(container.textContent).toContain("PR1");
});
// Select the PR1 claim via its checkbox.
const checkbox = container.querySelector(
'input[type="checkbox"][aria-label="Select PR1"]',
) as HTMLInputElement;
expect(checkbox).toBeTruthy();
await act(async () => {
checkbox.click();
});
// Hit Acknowledge. The bulk action bar button is wired to the
// /api/inbox/payer-rejected/acknowledge endpoint.
const ackButton = getByTestId("payer-rejected-acknowledge");
await act(async () => {
ackButton.click();
});
// The mock was called with the acknowledge URL.
const ackCall = fetchMock.mock.calls.find(
(c) => typeof c[0] === "string" && c[0].includes("/api/inbox/payer-rejected/acknowledge"),
);
expect(ackCall).toBeTruthy();
expect(ackCall).toBeDefined();
const ackBody = JSON.parse(ackCall![1].body);
expect(ackBody.claim_ids).toEqual(["PR1"]);
});
it("SP8: multi-select resubmit opens bundle modal; Resubmit + Download triggers api + downloadBlob", async () => {
// Two rejected claims → user selects both → Re-submit → modal appears
// → user clicks Resubmit + Download → backend is hit with
@@ -53,6 +162,7 @@ describe("Inbox page", () => {
state: "rejected", rejection_reason: "old", service_date: null,
score: null },
],
payer_rejected: [],
candidates: [],
unmatched: [],
done_today: [],
+61 -4
View File
@@ -1,9 +1,15 @@
// ---------------------------------------------------------------------------
// Inbox page (sub-project 6).
// Inbox page (sub-project 6, SP14).
//
// Full-bleed dark working surface for the four-lane triage workflow.
// Full-bleed dark working surface for the five-lane triage workflow.
// Wires useInboxLanes + Lane + InboxHeader + BulkBar. Bulk actions call
// the inbox API client and refetch on completion.
//
// SP14: added the `payer_rejected` lane (277CA STC A4/A6/A7) and the
// Acknowledge bulk action. The Payer-Rejected lane sits between
// `rejected` (envelope) and `candidates` (recon opportunities) so the
// operator's eye flow is: envelope problems → payer problems →
// auto-recon opportunities → claims still in flight → done today.
// ---------------------------------------------------------------------------
import { useState } from "react";
@@ -16,10 +22,16 @@ import {
dismissCandidates,
resubmitRejected,
resubmitRejectedWithDownload,
acknowledgePayerRejected,
} from "@/lib/inbox-api";
import { downloadBlob } from "@/lib/download";
type LaneKey = "rejected" | "candidates" | "unmatched" | "done_today";
type LaneKey =
| "rejected"
| "payer_rejected"
| "candidates"
| "unmatched"
| "done_today";
function rowKey(row: LaneRow): string {
return row.kind === "remit" ? (row as { payer_claim_control_number: string }).payer_claim_control_number : row.id;
@@ -29,6 +41,7 @@ export default function Inbox() {
const { lanes, loading, error, refetch } = useInboxLanes();
const [selected, setSelected] = useState<Record<LaneKey, string[]>>({
rejected: [],
payer_rejected: [],
candidates: [],
unmatched: [],
done_today: [],
@@ -127,6 +140,18 @@ export default function Inbox() {
}
}
async function onAcknowledge() {
// SP14: drop selected payer-rejected claims from the working
// surface. The backend persists an `acknowledged_at` timestamp;
// the original 277CA rejection (status code, reason, source 277CA
// id) stays intact for the SP11 audit log.
const ids = selected.payer_rejected;
if (ids.length === 0) return;
await acknowledgePayerRejected(ids);
setSelected((prev) => ({ ...prev, payer_rejected: [] }));
await refetch();
}
function onExport(lane: LaneKey) {
if (selected[lane].length === 0) return;
window.open(exportInboxCsvUrl(lane), "_blank");
@@ -162,8 +187,15 @@ export default function Inbox() {
);
}
// SP14: payer_rejected is also actionable — a 277CA rejection that
// needs operator follow-up. Without it, payer-side rejections would
// hide behind the 999 envelope "rejected" lane and the operator
// could miss a high-value denial.
const needEyes =
lanes.rejected.length + lanes.candidates.length + lanes.unmatched.length;
lanes.rejected.length +
lanes.payer_rejected.length +
lanes.candidates.length +
lanes.unmatched.length;
return (
<div
@@ -179,6 +211,19 @@ export default function Inbox() {
onRowClick={() => {}}
onSelectionChange={(ids) => setLaneSelected("rejected", ids)}
/>
{/*
SP14: payer-rejected (277CA STC A4/A6/A7). Distinct accent
from the 999 envelope rejected lane the operator's eye
flow is: 999 problems payer problems reconciliation
opportunities claims still in flight done today.
*/}
<Lane
name="PAYER REJECTED"
accent="oxblood"
rows={lanes.payer_rejected}
onRowClick={() => {}}
onSelectionChange={(ids) => setLaneSelected("payer_rejected", ids)}
/>
<Lane
name="CANDIDATES"
accent="amber"
@@ -207,13 +252,23 @@ export default function Inbox() {
lane="rejected"
count={selected.rejected.length}
onResubmit={onResubmit}
onAcknowledge={() => {}}
onDismiss={() => {}}
onExport={() => onExport("rejected")}
/>
<BulkBar
lane="payer_rejected"
count={selected.payer_rejected.length}
onResubmit={() => {}}
onAcknowledge={onAcknowledge}
onDismiss={() => {}}
onExport={() => onExport("payer_rejected")}
/>
<BulkBar
lane="candidates"
count={selected.candidates.length}
onResubmit={() => {}}
onAcknowledge={() => {}}
onDismiss={onDismiss}
onExport={() => onExport("candidates")}
/>
@@ -221,6 +276,7 @@ export default function Inbox() {
lane="unmatched"
count={selected.unmatched.length}
onResubmit={() => {}}
onAcknowledge={() => {}}
onDismiss={() => {}}
onExport={() => onExport("unmatched")}
/>
@@ -228,6 +284,7 @@ export default function Inbox() {
lane="done_today"
count={selected.done_today.length}
onResubmit={() => {}}
onAcknowledge={() => {}}
onDismiss={() => {}}
onExport={() => onExport("done_today")}
/>