feat(sp29): inbox rejected-row 999 ack chips + per-row Resubmit

- backend: _ack_summary_for_claims helper attaches claim_acks payload
  to inbox rejected-lane rows (3 tests)
- frontend: InboxRow renders newest 3 AK2 chips + '+N more' overflow
  under the rejection reason, with '999 not linked' marker when an
  ack couldn't be linked to a claim
- frontend: per-row Resubmit button downloads a single corrected 837
  via api.serializeClaim837 (no bulk modal, no zip — one click, one
  .x12 file)
- frontend: 2 new tests for the chip rendering and the per-row
  download flow
This commit is contained in:
Nora
2026-07-02 13:16:38 -06:00
parent 9cc13e7940
commit ffacfd8665
8 changed files with 596 additions and 8 deletions
+87
View File
@@ -175,6 +175,82 @@ def _line_count_lookup(session: Session, claims: list[Claim]) -> tuple[dict, dic
return matched_counts, total_lines_by_claim
def _ack_summary_for_claims(
session: Session, claim_ids: list[str],
) -> dict[str, dict]:
"""Build a {claim_id: {total, rejected, items: [...]}} map for 999 acks.
SP29: the Inbox `rejected` lane needs to render AK2 evidence
inline per row, plus a per-row Resubmit button. The data lives
in ``claim_acks`` (SP28) — we don't want to N+1 fetch per row,
so the whole rejected-claim set is summarized in one batched
query here.
Filters to ``ack_kind='999'`` because the rejected lane is the
999 envelope reject lane; the 277CA STC A4/A6/A7 evidence flows
through the ``payer_rejected_*`` fields on a separate lane and
isn't part of this scope (see SP29 spec D4 / scope).
Returns:
``{claim_id: {"total": int, "rejected": int, "items": [...]}, ...}``
Claims with zero linked 999 acks are NOT in the returned
dict — the caller maps via ``.get(cid)`` and treats absence
as "no 999 acks linked" (renders as ``null`` in the
payload, ``999 not linked`` in the UI).
Args:
session: SQLAlchemy session the caller owns.
claim_ids: list of claim.id values to summarize. Typically
the rejected-lane claim ids. Empty list → empty dict.
"""
if not claim_ids:
return {}
from cyclone.db import ClaimAck # late import — DB model registered
rows = (
session.query(
ClaimAck.claim_id,
ClaimAck.ack_id,
ClaimAck.set_control_number,
ClaimAck.set_accept_reject_code,
ClaimAck.ak2_index,
ClaimAck.linked_at,
)
.filter(
ClaimAck.claim_id.in_(claim_ids),
ClaimAck.ack_kind == "999",
)
.order_by(ClaimAck.linked_at.desc(), ClaimAck.id.desc())
.all()
)
grouped: dict[str, list[tuple]] = {}
for cid, aid, scn, code, ak2i, lat in rows:
grouped.setdefault(cid, []).append((aid, scn, code, ak2i, lat))
rejected_codes = {"R", "E", "X"}
out: dict[str, dict] = {}
for cid, items in grouped.items():
total = len(items)
rejected_count = sum(1 for it in items if (it[2] or "") in rejected_codes)
# Keep 5 most recent items for the chip column. The full count
# is in ``total`` so the UI can show ``+N more`` honestly.
trimmed = items[:5]
out[cid] = {
"total": total,
"rejected": rejected_count,
"items": [
{
"ack_id": aid,
"set_control_number": scn,
"set_accept_reject_code": code or "",
"ak2_index": ak2i,
"linked_at": _isoformat(lat),
}
for (aid, scn, code, ak2i, lat) in trimmed
],
}
return out
def compute_lanes(session: Session, *, dismissed_pairs: Iterable[frozenset]) -> Lanes:
lanes = Lanes()
dismissed = set(dismissed_pairs)
@@ -192,6 +268,17 @@ def compute_lanes(session: Session, *, dismissed_pairs: Iterable[frozenset]) ->
),
))
# SP29: attach the 999 ack-evidence summary (total / rejected /
# 5 most recent AK2 set_responses) to every rejected row so the
# Inbox can render AK2 chips inline + a per-row Resubmit button
# without an extra round-trip. One batched query, keyed off the
# rejected-claim id set.
rejected_ack_summary = _ack_summary_for_claims(
session, [r["id"] for r in lanes.rejected]
)
for row in lanes.rejected:
row["claim_acks"] = rejected_ack_summary.get(row["id"])
# --- Payer-Rejected (SP10) ---
# Distinct from the 999 envelope "rejected" lane above. A claim
# lands here when a 277CA STC category code is A4/A6/A7 (rejected
+109 -1
View File
@@ -12,7 +12,7 @@ import pytest
from cyclone import db
from cyclone.db import (
Base, Batch, Claim, ClaimState, Remittance, init_db,
Base, Batch, Claim, Ack, ClaimAck, ClaimState, Remittance, init_db,
)
from cyclone.inbox_lanes import compute_lanes
@@ -142,3 +142,111 @@ def test_done_today_includes_recent_terminal_states():
ids = {r["id"] for r in lanes.done_today}
assert "C1" in ids
assert "C2" not in ids
# ---------------------------------------------------------------------------
# SP29: rejected-lane rows must carry the per-claim 999 ack-evidence summary
# so the Inbox can render AK2 chips inline + a per-row Resubmit button
# without an extra round-trip.
# ---------------------------------------------------------------------------
def _add_999_ack(*, ack_id: int, parsed_at=None) -> None:
"""Persist a minimal Ack row (the 999 envelope)."""
with db.SessionLocal()() as s:
if s.get(Ack, ack_id) is not None:
return
s.add(Ack(
id=ack_id, source_batch_id="B-1",
accepted_count=0, rejected_count=0, received_count=1,
ack_code="A",
parsed_at=parsed_at or datetime.now(timezone.utc),
raw_json={"set_responses": []},
))
s.commit()
def _link_claim_ack(
*, ack_id: int, claim_id: str, ak2_index: int,
set_accept_reject_code: str,
linked_at=None, set_control_number: str = "991102989",
) -> None:
"""Persist a single ClaimAck row linking an Ack to a Claim."""
with db.SessionLocal()() as s:
s.add(ClaimAck(
claim_id=claim_id, ack_id=ack_id, ack_kind="999",
ak2_index=ak2_index,
set_control_number=set_control_number,
set_accept_reject_code=set_accept_reject_code,
linked_at=linked_at or datetime.now(timezone.utc),
linked_by="auto",
))
s.commit()
def test_inbox_lanes_attaches_claim_acks_summary_for_rejected():
"""A rejected-lane row gets a `claim_acks` field with total /
rejected counts + 5 most recent AK2 set_responses. Newest first.
"""
_add_claim(claim_id="REJ-1", state=ClaimState.REJECTED)
# 3 linked 999 acks: 2 accepted, 1 rejected
_add_999_ack(ack_id=1)
_add_999_ack(ack_id=2)
_add_999_ack(ack_id=3)
t0 = datetime.now(timezone.utc)
_link_claim_ack(ack_id=1, claim_id="REJ-1", ak2_index=0,
set_accept_reject_code="A",
linked_at=t0 - timedelta(minutes=10))
_link_claim_ack(ack_id=2, claim_id="REJ-1", ak2_index=1,
set_accept_reject_code="R",
linked_at=t0 - timedelta(minutes=5))
_link_claim_ack(ack_id=3, claim_id="REJ-1", ak2_index=2,
set_accept_reject_code="A",
linked_at=t0 - timedelta(minutes=1))
with db.SessionLocal()() as s:
lanes = compute_lanes(s, dismissed_pairs=set())
rows = [r for r in lanes.rejected if r["id"] == "REJ-1"]
assert len(rows) == 1
row = rows[0]
assert "claim_acks" in row
summary = row["claim_acks"]
assert summary is not None
assert summary["total"] == 3
assert summary["rejected"] == 1
assert len(summary["items"]) == 3
# Newest first (descending linked_at)
assert summary["items"][0]["set_accept_reject_code"] == "A" # ack 3 (most recent)
assert summary["items"][1]["set_accept_reject_code"] == "R" # ack 2 (middle)
assert summary["items"][2]["set_accept_reject_code"] == "A" # ack 1 (oldest)
# The R code is the one rejected entry
codes = [it["set_accept_reject_code"] for it in summary["items"]]
assert codes.count("R") == 1
# ak2_index is preserved
assert summary["items"][0]["ak2_index"] == 2
assert summary["items"][1]["ak2_index"] == 1
def test_inbox_lanes_claim_acks_is_null_when_no_links():
"""A rejected claim with zero linked 999 acks renders
`claim_acks: null` (the UI shows '999 not linked')."""
_add_claim(claim_id="REJ-2", state=ClaimState.REJECTED)
with db.SessionLocal()() as s:
lanes = compute_lanes(s, dismissed_pairs=set())
rows = [r for r in lanes.rejected if r["id"] == "REJ-2"]
assert len(rows) == 1
assert rows[0]["claim_acks"] is None
def test_inbox_lanes_claim_acks_does_not_attach_to_other_lanes():
"""The ack summary is only on `rejected`, not `payer_rejected` /
`unmatched` / `done_today` — those lanes have their own evidence
shape (payer_rejected_*, no linked 999s by construction)."""
_add_claim(claim_id="SUB-1", state=ClaimState.SUBMITTED)
_add_claim(claim_id="DEN-1", state=ClaimState.DENIED)
with db.SessionLocal()() as s:
lanes = compute_lanes(s, dismissed_pairs=set())
for r in lanes.unmatched:
assert "claim_acks" not in r
for r in lanes.done_today:
assert "claim_acks" not in r