fix(835): drop over-constraining UNIQUE constraints, add multi-BPR warning

Three related changes for real CO Medicaid data:

1. Drop UNIQUE(batch_id, patient_control_number) on claims and
   UNIQUE(batch_id, payer_claim_control_number) on remittances. The X12
   spec allows multiple CLM segments per 2000B subscriber loop and 835
   ERAs can repeat a payer_claim_control_number for reversals. Claim/
   remittance identity is provided by the primary key (claims.id = CLM01,
   remittances.id = CLP01).

2. Add validator rule R835_MULTI_BPR warning for files with multiple BPR
   segments (CO Medicaid split-payment pattern). The parser already sums
   BPR02 paid_amounts; this surfaces the non-standard data to operators.

3. Skip R835_BAL_BPR_vs_CLP04 when BPR01='I' (Information Only 835).
   In that mode BPR02 is informational and the per-claim CLP04 totals
   are authoritative — a diff is expected, not an error.

Migration 0003 handles the drop with IF EXISTS so fresh DBs skip cleanly.
Updates affected tests to reflect new schema (no UNIQUE constraint on
batch_id + patient_control_number / payer_claim_control_number).

Fixes test_api_835::test_prodfile_round_trip_persists_separately which
was failing on real production data.
This commit is contained in:
Tyler
2026-06-20 18:10:07 -06:00
parent 66da69baa0
commit b5e27927e0
12 changed files with 371 additions and 23 deletions
+13 -5
View File
@@ -7,7 +7,6 @@ from datetime import date, datetime, timezone
from decimal import Decimal
import pytest
from sqlalchemy.exc import IntegrityError
from cyclone import db
from cyclone.db import ActivityEvent, Base, Batch, CasAdjustment, Claim, ClaimState, Match, Remittance
@@ -240,8 +239,13 @@ def test_remittance_raw_json_round_trips_dict():
assert loaded.raw_json == {"x12_segments": ["CLP", "NM1", "SVC"], "version": "005010X221A1"}
def test_remittance_unique_constraint_rejects_duplicate_pcn():
"""UNIQUE (batch_id, payer_claim_control_number) blocks duplicates."""
def test_remittance_allows_duplicate_pcn_in_same_batch():
"""An 835 ERA can carry multiple CLP segments with the same
payer_claim_control_number (e.g. reversals re-referencing the
original PCN). Remittance identity is by ``id`` (CLP01), not by
(batch_id, PCN). This test documents the absence of the constraint
removed in migration 0003.
"""
with db.SessionLocal()() as s:
s.add(Batch(
id="b1", kind="835", input_filename="x",
@@ -260,8 +264,12 @@ def test_remittance_unique_constraint_rejects_duplicate_pcn():
status_code="2",
received_at=datetime(2026, 6, 19, tzinfo=timezone.utc),
))
with pytest.raises(IntegrityError):
s.commit()
s.commit() # no IntegrityError — duplicates are allowed
with db.SessionLocal()() as s:
rows = s.query(Remittance).filter(Remittance.batch_id == "b1").all()
assert {r.id for r in rows} == {"CLP-1", "CLP-2"}
assert {r.payer_claim_control_number for r in rows} == {"SAME"}
def test_remittance_cascade_delete_drops_cas_adjustments():