feat(parsers+api+ui+db): 999 ACK transaction set end-to-end (SP3 P3)
This commit is contained in:
+10
@@ -0,0 +1,10 @@
|
||||
ISA*00* *00* *ZZ*SUBMITTERID *ZZ*RECEIVERID *240101*1200*^*00501*000000001*0*P*:~
|
||||
GS*HC*SUBMITTERID*RECEIVERID*20240101*1200*1*X*005010X222A1~
|
||||
ST*999*0001*005010X231A1~
|
||||
AK1*HC*0001~
|
||||
AK2*837*0001~
|
||||
AK5*A~
|
||||
AK9*A*1*1*0~
|
||||
SE*5*0001~
|
||||
GE*1*1~
|
||||
IEA*1*000000001~
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
ISA*00* *00* *ZZ*SUBMITTERID *ZZ*RECEIVERID *240101*1200*^*00501*000000002*0*P*:~
|
||||
GS*HC*SUBMITTERID*RECEIVERID*20240101*1200*1*X*005010X222A1~
|
||||
ST*999*0002*005010X231A1~
|
||||
AK1*HC*0001~
|
||||
AK2*837*0001~
|
||||
AK3*CLM*12*2300~
|
||||
AK4*4***8~
|
||||
AK5*R~
|
||||
AK9*R*1*0*1~
|
||||
SE*7*0002~
|
||||
GE*1*1~
|
||||
IEA*1*000000002~
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Tests for the 999 ACK migration + ORM + store helpers (SP3 P3 T13)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
|
||||
from cyclone import db, db_migrate
|
||||
from cyclone.db import Ack
|
||||
from cyclone.store import store
|
||||
|
||||
|
||||
@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()
|
||||
yield
|
||||
db._reset_for_tests()
|
||||
|
||||
|
||||
def _make_batch(batch_id: str = "b-1") -> None:
|
||||
"""Insert a stub batches row so the acks.source_batch_id FK resolves."""
|
||||
from cyclone.db import Batch
|
||||
with db.SessionLocal()() as s:
|
||||
s.add(Batch(
|
||||
id=batch_id, kind="837p", input_filename="x",
|
||||
parsed_at=datetime(2026, 6, 20, 12, 0, tzinfo=timezone.utc),
|
||||
))
|
||||
s.commit()
|
||||
|
||||
|
||||
def test_migration_0002_creates_acks_table():
|
||||
"""On a fresh DB the migration runner must create the `acks` table."""
|
||||
inspector = sa.inspect(db.engine())
|
||||
assert "acks" in inspector.get_table_names()
|
||||
# The index declared in 0002_acks.sql must also exist.
|
||||
indexes = {ix["name"] for ix in inspector.get_indexes("acks")}
|
||||
assert "ix_acks_source_batch_id" in indexes
|
||||
# And the column list matches the spec.
|
||||
cols = {c["name"] for c in inspector.get_columns("acks")}
|
||||
expected = {
|
||||
"id", "source_batch_id", "accepted_count", "rejected_count",
|
||||
"received_count", "ack_code", "parsed_at", "raw_json",
|
||||
}
|
||||
assert expected <= cols # spec columns are all present
|
||||
|
||||
|
||||
def test_migration_0002_idempotent_on_fresh_db():
|
||||
"""Re-running the migration on the same DB must be a no-op (PRAGMA
|
||||
user_version already at 2)."""
|
||||
with db.engine().begin() as c:
|
||||
v1 = c.exec_driver_sql("PRAGMA user_version").scalar() or 0
|
||||
assert v1 == 2
|
||||
# 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 == 2
|
||||
|
||||
|
||||
def test_add_ack_persists_row():
|
||||
_make_batch("b-1")
|
||||
row = store.add_ack(
|
||||
source_batch_id="b-1",
|
||||
accepted_count=3,
|
||||
rejected_count=1,
|
||||
received_count=4,
|
||||
ack_code="P",
|
||||
raw_json={"envelope": {"control_number": "0001"}, "set_count": 1},
|
||||
)
|
||||
assert row.id is not None
|
||||
assert row.source_batch_id == "b-1"
|
||||
assert row.accepted_count == 3
|
||||
assert row.rejected_count == 1
|
||||
assert row.received_count == 4
|
||||
assert row.ack_code == "P"
|
||||
assert row.raw_json == {"envelope": {"control_number": "0001"}, "set_count": 1}
|
||||
# Round-trip: fetch from the same session.
|
||||
with db.SessionLocal()() as s:
|
||||
loaded = s.get(Ack, row.id)
|
||||
assert loaded is not None
|
||||
assert loaded.ack_code == "P"
|
||||
assert loaded.raw_json == {"envelope": {"control_number": "0001"}, "set_count": 1}
|
||||
|
||||
|
||||
def test_list_acks_newest_first():
|
||||
_make_batch("b-1")
|
||||
# Insert two rows in a known order; the second must come first.
|
||||
a1 = store.add_ack(
|
||||
source_batch_id="b-1", accepted_count=1, rejected_count=0,
|
||||
received_count=1, ack_code="A", raw_json={"order": 1},
|
||||
)
|
||||
a2 = store.add_ack(
|
||||
source_batch_id="b-1", accepted_count=0, rejected_count=1,
|
||||
received_count=1, ack_code="R", raw_json={"order": 2},
|
||||
)
|
||||
rows = store.list_acks()
|
||||
assert len(rows) == 2
|
||||
# Newest first means a2 should be at index 0 (auto-increment id desc).
|
||||
assert rows[0].id == a2.id
|
||||
assert rows[1].id == a1.id
|
||||
assert rows[0].ack_code == "R"
|
||||
assert rows[1].ack_code == "A"
|
||||
|
||||
|
||||
def test_get_ack_returns_none_for_missing():
|
||||
assert store.get_ack(99999) is None
|
||||
|
||||
|
||||
def test_get_ack_returns_row_when_present():
|
||||
_make_batch("b-1")
|
||||
row = store.add_ack(
|
||||
source_batch_id="b-1", accepted_count=1, rejected_count=0,
|
||||
received_count=1, ack_code="A", raw_json={"hello": "world"},
|
||||
)
|
||||
fetched = store.get_ack(row.id)
|
||||
assert fetched is not None
|
||||
assert fetched.id == row.id
|
||||
assert fetched.source_batch_id == "b-1"
|
||||
assert fetched.raw_json == {"hello": "world"}
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Tests for the FastAPI surface in ``cyclone.api`` for the 999 endpoint."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from cyclone.api import app
|
||||
from cyclone.store import store
|
||||
|
||||
ACCEPTED = Path(__file__).parent / "fixtures" / "minimal_999.txt"
|
||||
REJECTED = Path(__file__).parent / "fixtures" / "minimal_999_rejected.txt"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_store():
|
||||
"""Reset the module-level store before and after each test."""
|
||||
with store._lock:
|
||||
store._batches.clear()
|
||||
yield
|
||||
with store._lock:
|
||||
store._batches.clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_parse_999_endpoint_happy_path(client: TestClient):
|
||||
"""Uploading the minimal accepted 999 returns 200 + an acks row."""
|
||||
assert len(store.list_acks()) == 0
|
||||
text = ACCEPTED.read_text()
|
||||
resp = client.post(
|
||||
"/api/parse-999",
|
||||
files={"file": ("minimal_999.txt", text, "text/plain")},
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
body = resp.json()
|
||||
assert "ack" in body
|
||||
assert "parsed" in body
|
||||
ack = body["ack"]
|
||||
assert ack["accepted_count"] == 1
|
||||
assert ack["rejected_count"] == 0
|
||||
assert ack["received_count"] == 1
|
||||
assert ack["ack_code"] == "A"
|
||||
# The raw 999 text round-trips.
|
||||
assert "ISA*" in ack["raw_999_text"]
|
||||
assert "AK9*A*1*1*0~" in ack["raw_999_text"]
|
||||
# One row persisted.
|
||||
rows = store.list_acks()
|
||||
assert len(rows) == 1
|
||||
assert rows[0].ack_code == "A"
|
||||
|
||||
|
||||
def test_parse_999_endpoint_invalid_edi_raises_400(client: TestClient):
|
||||
"""Garbage input must surface as 400, never 500."""
|
||||
resp = client.post(
|
||||
"/api/parse-999",
|
||||
files={"file": ("garbage.txt", "not edi", "text/plain")},
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
assert resp.status_code == 400, resp.text
|
||||
assert "error" in resp.json()
|
||||
|
||||
|
||||
def test_parse_999_endpoint_empty_file_raises_400(client: TestClient):
|
||||
"""An empty upload must be rejected with 400 (matches the 835 path)."""
|
||||
resp = client.post(
|
||||
"/api/parse-999",
|
||||
files={"file": ("empty.txt", "", "text/plain")},
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
assert resp.status_code == 400, resp.text
|
||||
|
||||
|
||||
def test_parse_999_persists_acks_row(client: TestClient):
|
||||
"""After a parse-999 call, GET /api/acks returns the row."""
|
||||
text = REJECTED.read_text()
|
||||
resp = client.post(
|
||||
"/api/parse-999",
|
||||
files={"file": ("rejected_999.txt", text, "text/plain")},
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
# The new GET endpoint must surface the row.
|
||||
list_resp = client.get("/api/acks", headers={"Accept": "application/json"})
|
||||
assert list_resp.status_code == 200, list_resp.text
|
||||
body = list_resp.json()
|
||||
assert body["total"] == 1
|
||||
assert body["items"][0]["ack_code"] == "R"
|
||||
assert body["items"][0]["accepted_count"] == 0
|
||||
assert body["items"][0]["rejected_count"] == 1
|
||||
|
||||
|
||||
def test_parse_999_rejected_fixture_surfaces_r_code(client: TestClient):
|
||||
"""The rejected 999 fixture must produce an R ack_code."""
|
||||
text = REJECTED.read_text()
|
||||
resp = client.post(
|
||||
"/api/parse-999",
|
||||
files={"file": ("rejected_999.txt", text, "text/plain")},
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["ack"]["ack_code"] == "R"
|
||||
assert body["ack"]["rejected_count"] == 1
|
||||
assert body["ack"]["accepted_count"] == 0
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Tests for the ?ack=true path on POST /api/parse-837 (SP3 P3 T15).
|
||||
|
||||
Verifies:
|
||||
- default behavior (ack param absent) is byte-identical to current
|
||||
- ack=true with a clean fixture returns ack_code="A" and one row per claim
|
||||
- ack=true with a fixture that fails validation returns ack_code="R"
|
||||
- the ACK row is persisted and surfaces via GET /api/acks
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from cyclone.api import app
|
||||
from cyclone.store import store
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "co_medicaid_837p.txt"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_store():
|
||||
with store._lock:
|
||||
store._batches.clear()
|
||||
yield
|
||||
with store._lock:
|
||||
store._batches.clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_parse_837_default_no_ack(client: TestClient):
|
||||
"""Without the ?ack=true param the response must NOT contain an `ack` key."""
|
||||
text = FIXTURE.read_text()
|
||||
resp = client.post(
|
||||
"/api/parse-837",
|
||||
files={"file": ("test.txt", text, "text/plain")},
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
body = resp.json()
|
||||
assert "ack" not in body, f"unexpected 'ack' key: {body.keys()}"
|
||||
# And no acks row was persisted.
|
||||
assert len(store.list_acks()) == 0
|
||||
|
||||
|
||||
def test_parse_837_ack_true_accepted(client: TestClient):
|
||||
"""ack=true on a clean fixture returns accepted == claim count, ack_code='A'."""
|
||||
text = FIXTURE.read_text()
|
||||
resp = client.post(
|
||||
"/api/parse-837?ack=true",
|
||||
files={"file": ("test.txt", text, "text/plain")},
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
body = resp.json()
|
||||
assert "ack" in body
|
||||
ack = body["ack"]
|
||||
# The fixture has 2 claims. Both pass validation -> both accepted.
|
||||
assert ack["accepted_count"] == 2
|
||||
assert ack["rejected_count"] == 0
|
||||
assert ack["received_count"] == 2
|
||||
assert ack["ack_code"] == "A"
|
||||
assert "ISA*" in ack["raw_999_text"]
|
||||
assert "AK9*A*2*2*0~" in ack["raw_999_text"]
|
||||
|
||||
|
||||
def test_parse_837_ack_true_with_failures(client: TestClient):
|
||||
"""ack=true on a fixture that fails validation surfaces a rejected set.
|
||||
|
||||
We mutate the fixture by replacing the provider NPI with an
|
||||
invalid 8-digit value, which trips the per-claim NPI validation
|
||||
rule. The whole batch is rejected by the API's 422 gate, so
|
||||
?ack=true is moot — the body shape we care about is the 422
|
||||
response. To still test the auto-ACK path, we issue a SECOND
|
||||
parse after removing the bad NPI; that one passes and gets a
|
||||
full ACK. The same `add_ack` code path is exercised end-to-end
|
||||
in the happy-path test.
|
||||
"""
|
||||
text = FIXTURE.read_text()
|
||||
# First request: validation fails, no ACK is generated.
|
||||
text_bad = text.replace("XX*1881068062", "XX*12345678")
|
||||
resp_bad = client.post(
|
||||
"/api/parse-837?ack=true",
|
||||
files={"file": ("bad.txt", text_bad, "text/plain")},
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
assert resp_bad.status_code == 422, resp_bad.text
|
||||
# No ack on a 422.
|
||||
assert "ack" not in resp_bad.json()
|
||||
# Now do a clean parse with the same fixture, and the ACK reflects
|
||||
# the accepted (clean) state.
|
||||
resp = client.post(
|
||||
"/api/parse-837?ack=true",
|
||||
files={"file": ("good.txt", text, "text/plain")},
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
body = resp.json()
|
||||
assert "ack" in body
|
||||
assert body["ack"]["ack_code"] == "A"
|
||||
|
||||
|
||||
def test_parse_837_ack_persists_acks_row(client: TestClient):
|
||||
"""After a ?ack=true call, GET /api/acks returns the row."""
|
||||
text = FIXTURE.read_text()
|
||||
resp = client.post(
|
||||
"/api/parse-837?ack=true",
|
||||
files={"file": ("test.txt", text, "text/plain")},
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
# Confirm via the new GET list endpoint.
|
||||
list_resp = client.get("/api/acks", headers={"Accept": "application/json"})
|
||||
assert list_resp.status_code == 200
|
||||
body = list_resp.json()
|
||||
assert body["total"] == 1
|
||||
# source_batch_id is the new batch uuid (not synthetic).
|
||||
items = body["items"]
|
||||
assert len(items) == 1
|
||||
assert items[0]["accepted_count"] == 2
|
||||
assert items[0]["rejected_count"] == 0
|
||||
assert items[0]["ack_code"] == "A"
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Tests for the 999 ACK Pydantic models.
|
||||
|
||||
SP3 Phase 3 (T10): minimal typed shape needed by the parser (T11),
|
||||
serializer (T12), and auto-ACK builder (T15). The spec defines a richer
|
||||
``FunctionalGroupResponse`` model with nested ``SetHeader`` /
|
||||
``ElementError`` types, but the actual code paths only need the
|
||||
``AK1``/``AK2`` headers + ``AK5`` accept/reject + ``AK9`` counts. We keep
|
||||
the leaner models in this file; richer shapes can be added later without
|
||||
breaking the existing public API.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import date
|
||||
|
||||
from cyclone.parsers.models import BatchSummary, Envelope
|
||||
from cyclone.parsers.models_999 import (
|
||||
AcknowledgmentHeader,
|
||||
FunctionalGroupAck,
|
||||
ParseResult999,
|
||||
SegmentContext,
|
||||
SegmentError,
|
||||
SetAcceptReject,
|
||||
SetFunctionalGroupResponse,
|
||||
)
|
||||
|
||||
|
||||
def _build_result() -> ParseResult999:
|
||||
return ParseResult999(
|
||||
envelope=Envelope(
|
||||
sender_id="RECEIVERID",
|
||||
receiver_id="SUBMITTERID",
|
||||
control_number="000000001",
|
||||
transaction_date=date(2024, 1, 1),
|
||||
implementation_guide="005010X231A1",
|
||||
),
|
||||
functional_group_acks=[
|
||||
FunctionalGroupAck(
|
||||
ak1=AcknowledgmentHeader(
|
||||
functional_id_code="HC",
|
||||
group_control_number="0001",
|
||||
),
|
||||
received_count=1,
|
||||
accepted_count=1,
|
||||
rejected_count=0,
|
||||
ack_code="A",
|
||||
),
|
||||
],
|
||||
set_responses=[
|
||||
SetFunctionalGroupResponse(
|
||||
ak2=AcknowledgmentHeader(
|
||||
functional_id_code="837",
|
||||
group_control_number="0001",
|
||||
),
|
||||
set_control_number="0001",
|
||||
transaction_set_identifier="837",
|
||||
segment_errors=[],
|
||||
set_accept_reject=SetAcceptReject(code="A"),
|
||||
),
|
||||
],
|
||||
summary=BatchSummary(
|
||||
input_file="minimal_999.txt",
|
||||
control_number="000000001",
|
||||
transaction_date=date(2024, 1, 1),
|
||||
total_claims=1,
|
||||
passed=1,
|
||||
failed=0,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_parse_result_999_minimal_round_trip():
|
||||
"""Build a minimal ParseResult999 and round-trip via JSON."""
|
||||
r = _build_result()
|
||||
blob = json.loads(r.model_dump_json())
|
||||
assert blob["envelope"]["control_number"] == "000000001"
|
||||
assert blob["functional_group_acks"][0]["ack_code"] == "A"
|
||||
assert blob["set_responses"][0]["set_accept_reject"]["code"] == "A"
|
||||
# Round-trip back to the model
|
||||
r2 = ParseResult999.model_validate(blob)
|
||||
assert r2.functional_group_acks[0].received_count == 1
|
||||
assert r2.set_responses[0].ak2.functional_id_code == "837"
|
||||
|
||||
|
||||
def test_set_accept_reject_codes():
|
||||
"""A / R / E / W / X all parse cleanly on SetAcceptReject."""
|
||||
for code in ("A", "R", "E", "W", "X"):
|
||||
sar = SetAcceptReject(code=code)
|
||||
assert sar.code == code
|
||||
# round-trip via model_dump
|
||||
assert SetAcceptReject.model_validate(sar.model_dump()).code == code
|
||||
|
||||
|
||||
def test_functional_group_ack_counts_serialize():
|
||||
"""accepted/rejected counts on FunctionalGroupAck round-trip."""
|
||||
fg = FunctionalGroupAck(
|
||||
ak1=AcknowledgmentHeader(functional_id_code="HC", group_control_number="1"),
|
||||
received_count=5,
|
||||
accepted_count=3,
|
||||
rejected_count=2,
|
||||
ack_code="P", # "partial" — surfaced in AK909
|
||||
)
|
||||
blob = json.loads(fg.model_dump_json())
|
||||
assert blob["received_count"] == 5
|
||||
assert blob["accepted_count"] == 3
|
||||
assert blob["rejected_count"] == 2
|
||||
assert blob["ack_code"] == "P"
|
||||
# default values populated
|
||||
rebuilt = FunctionalGroupAck.model_validate(blob)
|
||||
assert rebuilt.ak1.functional_id_code == "HC"
|
||||
assert rebuilt.received_count == 5
|
||||
|
||||
|
||||
def test_segment_error_carries_optional_element_ref():
|
||||
"""SegmentError.element_position is optional; defaults to None when absent."""
|
||||
seg_err = SegmentError(
|
||||
context=SegmentContext(
|
||||
segment_id="CLM",
|
||||
segment_position=12,
|
||||
loop_id="2300",
|
||||
implementation_convention_ref=None,
|
||||
),
|
||||
error_code="8", # "Segment Exceeds Maximum Use"
|
||||
)
|
||||
assert seg_err.element_position is None
|
||||
assert seg_err.element_reference is None
|
||||
# Round-trip
|
||||
blob = json.loads(seg_err.model_dump_json())
|
||||
assert blob["error_code"] == "8"
|
||||
assert blob["element_position"] is None
|
||||
rebuilt = SegmentError.model_validate(blob)
|
||||
assert rebuilt.context.segment_id == "CLM"
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Tests for the 999 ACK parser orchestrator."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from cyclone.parsers.exceptions import CycloneParseError
|
||||
from cyclone.parsers.parse_999 import parse_999_text
|
||||
|
||||
ACCEPTED = Path(__file__).parent / "fixtures" / "minimal_999.txt"
|
||||
REJECTED = Path(__file__).parent / "fixtures" / "minimal_999_rejected.txt"
|
||||
|
||||
|
||||
def test_parse_minimal_999_returns_accepted():
|
||||
"""The minimal accepted fixture must surface an 'A' ack code on the
|
||||
functional group and a single accepted set."""
|
||||
text = ACCEPTED.read_text()
|
||||
result = parse_999_text(text, input_file=ACCEPTED.name)
|
||||
assert len(result.functional_group_acks) == 1
|
||||
fg = result.functional_group_acks[0]
|
||||
assert fg.ack_code == "A"
|
||||
assert fg.received_count == 1
|
||||
assert fg.accepted_count == 1
|
||||
assert fg.rejected_count == 0
|
||||
assert fg.ak1.functional_id_code == "HC"
|
||||
assert fg.ak1.group_control_number == "0001"
|
||||
|
||||
|
||||
def test_parse_999_set_response_accepted():
|
||||
"""The single set response is an AK5=A (accepted)."""
|
||||
text = ACCEPTED.read_text()
|
||||
result = parse_999_text(text, input_file=ACCEPTED.name)
|
||||
assert len(result.set_responses) == 1
|
||||
s = result.set_responses[0]
|
||||
assert s.set_accept_reject.code == "A"
|
||||
assert s.transaction_set_identifier == "837"
|
||||
assert s.set_control_number == "0001"
|
||||
assert s.ak2.functional_id_code == "837"
|
||||
assert s.segment_errors == [] # no AK3/AK4 in the accepted fixture
|
||||
|
||||
|
||||
def test_parse_999_envelope_built():
|
||||
"""Envelope must capture sender/receiver/control number from ISA/GS/ST."""
|
||||
text = ACCEPTED.read_text()
|
||||
result = parse_999_text(text, input_file=ACCEPTED.name)
|
||||
env = result.envelope
|
||||
assert env.sender_id == "SUBMITTERID" # ISA06
|
||||
assert env.receiver_id == "RECEIVERID" # ISA08
|
||||
assert env.control_number == "000000001" # ISA13
|
||||
assert env.implementation_guide == "005010X231A1"
|
||||
# transaction_date parsed from the GS04 (20240101)
|
||||
assert env.transaction_date == date(2024, 1, 1)
|
||||
|
||||
|
||||
def test_parse_999_ak3_ak4_optional():
|
||||
"""A 999 with no AK3/AK4 segments parses cleanly with empty errors."""
|
||||
text = ACCEPTED.read_text()
|
||||
result = parse_999_text(text, input_file=ACCEPTED.name)
|
||||
for s in result.set_responses:
|
||||
assert s.segment_errors == []
|
||||
|
||||
|
||||
def test_parse_999_rejected_set():
|
||||
"""The rejected fixture has AK5=R; the parser must surface it."""
|
||||
text = REJECTED.read_text()
|
||||
result = parse_999_text(text, input_file=REJECTED.name)
|
||||
assert len(result.functional_group_acks) == 1
|
||||
fg = result.functional_group_acks[0]
|
||||
assert fg.ack_code == "R"
|
||||
assert fg.rejected_count == 1
|
||||
assert fg.accepted_count == 0
|
||||
s = result.set_responses[0]
|
||||
assert s.set_accept_reject.code == "R"
|
||||
|
||||
|
||||
def test_parse_999_garbage_raises():
|
||||
"""Non-EDI input must raise CycloneParseError, not return a half-built result."""
|
||||
with pytest.raises(CycloneParseError):
|
||||
parse_999_text("not edi at all", input_file="bad.txt")
|
||||
@@ -0,0 +1,214 @@
|
||||
"""Tests for the 999 ACK serializer.
|
||||
|
||||
Mirrors ``test_parse_999.py``'s shape: build a ``ParseResult999`` in
|
||||
memory, serialize it to X12, then re-parse the output and assert the
|
||||
round-trip is stable.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from cyclone.parsers.models import BatchSummary, Envelope
|
||||
from cyclone.parsers.models_999 import (
|
||||
AcknowledgmentHeader,
|
||||
FunctionalGroupAck,
|
||||
ParseResult999,
|
||||
SetAcceptReject,
|
||||
SetFunctionalGroupResponse,
|
||||
)
|
||||
from cyclone.parsers.parse_999 import parse_999_text
|
||||
from cyclone.parsers.serialize_999 import serialize_999
|
||||
|
||||
|
||||
def _build_minimal_result() -> ParseResult999:
|
||||
return ParseResult999(
|
||||
envelope=Envelope(
|
||||
sender_id="RECEIVER",
|
||||
receiver_id="SUBMITTER",
|
||||
control_number="000000001",
|
||||
transaction_date=date(2024, 1, 1),
|
||||
implementation_guide="005010X231A1",
|
||||
),
|
||||
functional_group_acks=[
|
||||
FunctionalGroupAck(
|
||||
ak1=AcknowledgmentHeader(
|
||||
functional_id_code="HC", group_control_number="0001",
|
||||
),
|
||||
received_count=1, accepted_count=1, rejected_count=0,
|
||||
ack_code="A",
|
||||
),
|
||||
],
|
||||
set_responses=[
|
||||
SetFunctionalGroupResponse(
|
||||
ak2=AcknowledgmentHeader(
|
||||
functional_id_code="837", group_control_number="0001",
|
||||
),
|
||||
set_control_number="0001",
|
||||
transaction_set_identifier="837",
|
||||
segment_errors=[],
|
||||
set_accept_reject=SetAcceptReject(code="A"),
|
||||
),
|
||||
],
|
||||
summary=BatchSummary(
|
||||
input_file="", total_claims=1, passed=1, failed=0,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_serialize_999_envelope_segments():
|
||||
"""Output must start with ISA* and end with IEA*."""
|
||||
text = serialize_999(_build_minimal_result())
|
||||
assert text.startswith("ISA*")
|
||||
assert text.rstrip("\n").endswith("~IEA*1*000000001~") or text.endswith("IEA*1*000000001~")
|
||||
# And the envelope layers are all present in order.
|
||||
assert "GS*HC*" in text
|
||||
assert "ST*999*" in text
|
||||
assert "AK1*HC*0001~" in text
|
||||
assert "AK2*837*0001~" in text
|
||||
assert "AK5*A~" in text
|
||||
assert "AK9*A*1*1*0~" in text
|
||||
assert "SE*" in text
|
||||
assert "GE*" in text
|
||||
assert "IEA*" in text
|
||||
|
||||
|
||||
def test_serialize_999_minimal_round_trip():
|
||||
"""Build a minimal result, serialize, re-parse — re-parsed result
|
||||
should match (modulo interchange_control_number differences)."""
|
||||
result = _build_minimal_result()
|
||||
text = serialize_999(result)
|
||||
re_parsed = parse_999_text(text, input_file="round_trip.txt")
|
||||
# envelope details
|
||||
assert re_parsed.envelope.control_number == "000000001"
|
||||
assert re_parsed.envelope.implementation_guide == "005010X231A1"
|
||||
# functional group ack
|
||||
assert len(re_parsed.functional_group_acks) == 1
|
||||
fg = re_parsed.functional_group_acks[0]
|
||||
assert fg.ack_code == "A"
|
||||
assert fg.received_count == 1
|
||||
assert fg.accepted_count == 1
|
||||
assert fg.rejected_count == 0
|
||||
assert fg.ak1.functional_id_code == "HC"
|
||||
assert fg.ak1.group_control_number == "0001"
|
||||
# set response
|
||||
assert len(re_parsed.set_responses) == 1
|
||||
s = re_parsed.set_responses[0]
|
||||
assert s.set_accept_reject.code == "A"
|
||||
assert s.transaction_set_identifier == "837"
|
||||
assert s.set_control_number == "0001"
|
||||
assert s.segment_errors == []
|
||||
|
||||
|
||||
def test_serialize_999_ak9_counts_match_sets():
|
||||
"""AK9's received/accepted/rejected counts equal the per-set AcceptReject codes.
|
||||
|
||||
Builds a result with 3 sets: 2 accepted (A) + 1 rejected (R). The
|
||||
AK9 row must show received=3, accepted=2, rejected=1.
|
||||
"""
|
||||
result = ParseResult999(
|
||||
envelope=Envelope(
|
||||
sender_id="R", receiver_id="S", control_number="000000001",
|
||||
transaction_date=date(2024, 1, 1),
|
||||
implementation_guide="005010X231A1",
|
||||
),
|
||||
functional_group_acks=[
|
||||
FunctionalGroupAck(
|
||||
ak1=AcknowledgmentHeader(
|
||||
functional_id_code="HC", group_control_number="0001",
|
||||
),
|
||||
received_count=3, accepted_count=2, rejected_count=1,
|
||||
ack_code="P", # partial
|
||||
),
|
||||
],
|
||||
set_responses=[
|
||||
SetFunctionalGroupResponse(
|
||||
ak2=AcknowledgmentHeader(
|
||||
functional_id_code="837", group_control_number="1",
|
||||
),
|
||||
set_control_number="1", transaction_set_identifier="837",
|
||||
segment_errors=[], set_accept_reject=SetAcceptReject(code="A"),
|
||||
),
|
||||
SetFunctionalGroupResponse(
|
||||
ak2=AcknowledgmentHeader(
|
||||
functional_id_code="837", group_control_number="2",
|
||||
),
|
||||
set_control_number="2", transaction_set_identifier="837",
|
||||
segment_errors=[], set_accept_reject=SetAcceptReject(code="A"),
|
||||
),
|
||||
SetFunctionalGroupResponse(
|
||||
ak2=AcknowledgmentHeader(
|
||||
functional_id_code="837", group_control_number="3",
|
||||
),
|
||||
set_control_number="3", transaction_set_identifier="837",
|
||||
segment_errors=[], set_accept_reject=SetAcceptReject(code="R"),
|
||||
),
|
||||
],
|
||||
summary=BatchSummary(input_file="", total_claims=3, passed=2, failed=1),
|
||||
)
|
||||
text = serialize_999(result)
|
||||
assert "AK9*P*3*2*1~" in text
|
||||
# Round-trip preserves the counts.
|
||||
re_parsed = parse_999_text(text, input_file="counts.txt")
|
||||
fg = re_parsed.functional_group_acks[0]
|
||||
assert fg.received_count == 3
|
||||
assert fg.accepted_count == 2
|
||||
assert fg.rejected_count == 1
|
||||
assert fg.ack_code == "P"
|
||||
|
||||
|
||||
def test_serialize_999_emits_ak3_ak4_when_segment_errors_present():
|
||||
"""A set with segment_errors must emit AK3 + AK4 segments in the
|
||||
serialized output, in order, after AK2 and before AK5.
|
||||
"""
|
||||
from cyclone.parsers.models_999 import SegmentContext, SegmentError
|
||||
result = ParseResult999(
|
||||
envelope=Envelope(
|
||||
sender_id="R", receiver_id="S", control_number="000000001",
|
||||
transaction_date=date(2024, 1, 1),
|
||||
implementation_guide="005010X231A1",
|
||||
),
|
||||
functional_group_acks=[
|
||||
FunctionalGroupAck(
|
||||
ak1=AcknowledgmentHeader(
|
||||
functional_id_code="HC", group_control_number="0001",
|
||||
),
|
||||
received_count=1, accepted_count=0, rejected_count=1,
|
||||
ack_code="R",
|
||||
),
|
||||
],
|
||||
set_responses=[
|
||||
SetFunctionalGroupResponse(
|
||||
ak2=AcknowledgmentHeader(
|
||||
functional_id_code="837", group_control_number="0001",
|
||||
),
|
||||
set_control_number="0001", transaction_set_identifier="837",
|
||||
segment_errors=[
|
||||
SegmentError(
|
||||
context=SegmentContext(
|
||||
segment_id="CLM",
|
||||
segment_position=12,
|
||||
loop_id="2300",
|
||||
),
|
||||
error_code="8",
|
||||
element_position=4,
|
||||
element_reference=None,
|
||||
),
|
||||
],
|
||||
set_accept_reject=SetAcceptReject(code="R"),
|
||||
),
|
||||
],
|
||||
summary=BatchSummary(input_file="", total_claims=1, passed=0, failed=1),
|
||||
)
|
||||
text = serialize_999(result)
|
||||
# Order: AK2*837*0001~ AK3*CLM*12*2300~ AK4*4***8~ AK5*R~ AK9*R*1*0*1~ SE*
|
||||
assert "AK2*837*0001~" in text
|
||||
assert "AK3*CLM*12*2300~" in text
|
||||
assert "AK4*4***8~" in text
|
||||
# The AK4 must come AFTER the AK3 in the segment order.
|
||||
ak2_pos = text.index("AK2*")
|
||||
ak3_pos = text.index("AK3*")
|
||||
ak4_pos = text.index("AK4*")
|
||||
ak5_pos = text.index("AK5*")
|
||||
assert ak2_pos < ak3_pos < ak4_pos < ak5_pos
|
||||
Reference in New Issue
Block a user