API reference

The public modules, from their docstrings. The transaction models themselves (x12sdk.v5010.*) mirror the implementation guides loop by loop and are best explored from a parsed file, or with x12sdk -m -p file.

Tables

x12sdk.tables.spreadsheet_safe(value)[source]

value, made safe to open in a spreadsheet.

A text value starting with =, +, -, @, a tab or a carriage return is prefixed with an apostrophe, so Excel, LibreOffice and Google Sheets show it as text instead of running it as a formula. Numbers, and text that is a plain number such as -12.50, are returned unchanged.

Parameters:

value (Any)

Return type:

Any

x12sdk.tables.REMITTANCE_COLUMNS: Sequence[str] = ('transaction_set', 'transaction_control_number', 'payer_name', 'payer_id', 'payee_name', 'payee_npi', 'payment_trace_number', 'payment_method', 'payment_amount', 'payment_date', 'patient_control_number', 'payer_claim_control_number', 'claim_status_code', 'claim_filing_indicator', 'claim_charge', 'claim_paid', 'claim_patient_responsibility', 'claim_adjustment_codes', 'patient_last_name', 'patient_first_name', 'member_id', 'line_number', 'procedure_qualifier', 'procedure_code', 'modifiers', 'revenue_code', 'units_paid', 'line_charge', 'line_paid', 'service_date', 'co_amount', 'pr_amount', 'oa_amount', 'pi_amount', 'cr_amount', 'adjustment_codes', 'remark_codes')

The columns of an 835 row, one row per paid service line, in order.

x12sdk.tables.CLAIM_COLUMNS: Sequence[str] = ('transaction_set', 'transaction_control_number', 'implementation', 'billing_provider_name', 'billing_provider_npi', 'payer_name', 'subscriber_last_name', 'subscriber_first_name', 'member_id', 'patient_last_name', 'patient_first_name', 'is_dependent', 'relationship_code', 'patient_control_number', 'claim_charge', 'facility_code', 'claim_frequency_code', 'principal_diagnosis', 'diagnosis_codes', 'claim_service_date', 'line_number', 'procedure_qualifier', 'procedure_code', 'modifiers', 'revenue_code', 'units', 'line_charge', 'line_service_date', 'tooth_number', 'tooth_surfaces')

The columns of an 837 row, one row per billed service line, in order.

x12sdk.tables.remittance_lines(transaction)[source]

One row per service line of an 835, in file order.

A claim paid without line detail (no 2110 loops) still gets one row, with the line columns empty, so no payment is lost from the table.

Return type:

Iterator[Dict[str, Any]]

x12sdk.tables.claim_lines(transaction)[source]

One row per service line of an 837 (P, I or D), in file order, from both the subscriber and the dependent branch of the hierarchy.

Return type:

Iterator[Dict[str, Any]]

x12sdk.tables.iter_lines(source, *, allow_paths=True)[source]

Rows for every 835 and 837 transaction in source, one per service line.

Other transaction sets in the same interchange are skipped. Rows from an 835 have REMITTANCE_COLUMNS; rows from an 837 have CLAIM_COLUMNS. A file normally holds one kind; to split a mixed one, filter on transaction_set.

Parameters:

allow_paths (bool) – Treat a string naming an X12 file as that file. Pass False for input from someone else, so it is only read as X12 text.

Return type:

Iterator[Dict[str, Any]]

x12sdk.tables.read_lines(source, *, allow_paths=True)[source]

iter_lines() as a list.

Parameters:

allow_paths (bool)

Return type:

List[Dict[str, Any]]

x12sdk.tables.to_dataframe(source, *, allow_paths=True)[source]

The service-line rows of source as a pandas DataFrame.

Requires the optional pandas dependency: pip install 'x12sdk[pandas]'.

Parameters:

allow_paths (bool)

x12sdk.tables.write_csv(source, out, escape_formulas=True, *, allow_paths=True)[source]

Writes the service-line rows of source as CSV to out.

Parameters:
  • escape_formulas (bool) – Prefix text that a spreadsheet would run as a formula with an apostrophe (see spreadsheet_safe()). Leave it on for any file you did not create yourself; turn it off only when the CSV goes to a program, not a spreadsheet.

  • allow_paths (bool) – Treat a string naming an X12 file as that file. Pass False for input from someone else, so it is only read as X12 text.

  • out (TextIO)

Returns:

The number of rows written, not counting the header.

Return type:

int

x12sdk.tables.main(argv=None)[source]

The x12sdk-table entry point.

Parameters:

argv (List[str] | None)

Return type:

int

Validation

x12sdk.validation.READ_ERRORS = (<class 'pydantic_core._pydantic_core.ValidationError'>, <class 'ValueError'>, <class 'KeyError'>, <class 'IndexError'>)

The exceptions reading a file can raise for bad input, as opposed to bugs.

class x12sdk.validation.Problem(location, where, message)[source]

One reason a file is invalid.

Parameters:
location: str
where: str
message: str
class x12sdk.validation.Transaction(transaction_set: 'str', control_number: 'Optional[str]', implementation: 'Optional[str]', claims: 'Optional[int]')[source]
Parameters:
  • transaction_set (str)

  • control_number (str | None)

  • implementation (str | None)

  • claims (int | None)

transaction_set: str
control_number: str | None
implementation: str | None
claims: int | None
class x12sdk.validation.CheckResult(valid, transactions=<factory>, problems=<factory>)[source]

The outcome of checking one source.

Parameters:
valid: bool
transactions: List[Transaction]
problems: List[Problem]
x12sdk.validation.problems(error)[source]

The problems behind a failed read, in words, without the file content.

Parameters:

error (Exception)

Return type:

List[Problem]

x12sdk.validation.check(source, *, allow_paths=True)[source]

Checks X12 text, or the file at a path.

Parameters:
  • allow_paths (bool) – Treat source as a file path when it names one. Pass False for input from someone else: it is then only read as X12 text, and the result never says whether a path exists.

  • source (str)

Returns:

whether it is valid, the transactions found, and the problems.

Return type:

CheckResult

x12sdk.validation.main(argv=None)[source]

The x12sdk-validate entry point.

Returns:

0 when every file is valid, 1 when any is not.

Parameters:

argv (List[str] | None)

Return type:

int

Matching

x12sdk.matching.OUTCOMES = ('paid', 'denied', 'no remittance', 'no claim')

The outcomes Match.outcome can take.

x12sdk.matching.MATCH_COLUMNS: Sequence[str] = ('patient_control_number', 'outcome', 'billed', 'paid', 'patient_responsibility', 'payment_count', 'claim_status_codes', 'payer_claim_control_numbers', 'claim_count')

The columns of a match_rows() row, in order.

class x12sdk.matching.Match(patient_control_number, claims, payments)[source]

One patient control number, with every claim and payment that carries it.

claims is usually one claim; more than one means the same number was submitted again. payments holds every CLP for the number, in the order the remittances were given.

Parameters:
patient_control_number: str
claims: Tuple[SubmittedClaim, ...]
payments: Tuple[PaidClaim, ...]
property billed: Decimal | None

CLM02 of the first claim, or the 835’s CLP03 when no claim was given.

property paid: Decimal

CLP04 over every payment; a reversal’s negative amount nets out.

property patient_responsibility: Decimal
property outcome: str

no remittance when nothing answered the claim, no claim when a payment’s claim is not among the 837s given, otherwise paid or denied by whether the payments net to more than zero.

x12sdk.matching.match_claims(claims, remittances, *, allow_paths=True)[source]

Pairs every claim with every payment that answers it.

Parameters:
  • claims – 837 files, text or models (one or an iterable).

  • remittances – 835 files, text or models (one or an iterable).

  • allow_paths (bool) – Treat a string naming an X12 file as that file. Pass False for input from someone else, so it is only read as X12 text.

Returns:

One Match per patient control number: the claims’ numbers in file order, then numbers only the remittances carry.

Return type:

List[Match]

x12sdk.matching.match_rows(claims, remittances, *, allow_paths=True)[source]

match_claims() as flat rows with MATCH_COLUMNS, ready for a CSV or a DataFrame.

Parameters:

allow_paths (bool)

Return type:

Iterable[Dict[str, Any]]

Reading and writing

x12sdk.io.FUNCTIONAL_IDENTIFIER_CODES: Dict[str, str] = {'270': 'HS', '271': 'HB', '276': 'HR', '277': 'HN', '834': 'BE', '835': 'HP', '837': 'HC'}

Transaction set code -> GS01 functional identifier code.

class x12sdk.io.X12SegmentReader(x12_input, *, allow_paths=True)[source]

Streams segments from a X12 message or file.

with X12Reader(x12_data) as r:
for segment_name, segment_fields in r.segments():

# do something interesting

Segments are streamed in order received using a buffered generator function. Buffer size is configured using the config/env variable X12_READER_BUFFER_SIZE (default = 1MB).

Parameters:
  • x12_input (str)

  • allow_paths (bool)

delimiters: X12Delimiters | None
segments()[source]

Iterator function used to return X12 models from the underlying X12 stream. The read buffer size may be configured using X12_READER_BUFFER_SIZE.

Returns:

Iterator containing segment name and segment fields.

Return type:

Iterator[Tuple[str, List[str]]]

class x12sdk.io.X12ModelReader(x12_input, output_delimiters=False, *, allow_paths=True)[source]

The X12ModelReader parses X12 segments into transactional models. Data is buffered using a X12SegmentReader.

with X12ModelReader(x12_data) as r:
for model in r.model():

# do something interesting

Parameters:
  • x12_input (str)

  • output_delimiters (bool)

  • allow_paths (bool)

models()[source]

Creates a stream of X12 models from a X12 segment stream. The stream returns transaction specific implementations of the X12SegmentGroup base class.

Returns:

X12SegmentGroup model iterator

Return type:

Iterator[X12SegmentGroup]

x12sdk.io.write_transactions(transactions, *, sender_id, receiver_id, sender_qualifier='30', receiver_qualifier='30', interchange_control_number='000000001', group_control_number='1', created=None, usage_indicator='T', path=None)[source]

Writes transaction models as a complete X12 interchange.

Transaction models cover ST through SE; this adds the ISA/IEA interchange and GS/GE functional group envelopes around them. Consecutive transactions of the same type share a functional group, so a mixed list produces one group per run of like transactions.

Control numbers are kept consistent for you: IEA02 matches ISA13 and GE02 matches GS06, and both counts reflect what was actually written.

Parameters:
  • transactions (Iterable[X12SegmentGroup]) – Transaction set models, e.g. from X12ModelReader.

  • sender_id (str) – ISA06 interchange sender id, padded to 15 characters.

  • receiver_id (str) – ISA08 interchange receiver id, padded to 15 characters.

  • sender_qualifier (str) – ISA05, defaults to 30 (US federal tax id).

  • receiver_qualifier (str) – ISA07, defaults to 30.

  • interchange_control_number (str) – ISA13/IEA02, padded to 9 digits.

  • group_control_number (str) – GS06/GE02 for the first group; later groups increment.

  • created (datetime | None) – Timestamp for ISA09/10 and GS04/05. Defaults to now.

  • usage_indicator (str) – ISA15, T for test or P for production.

  • path (str | None) – Optional file to write to. The interchange is returned either way.

Returns:

The complete X12 interchange.

Raises:

ValueError – if a transaction’s type cannot be determined, or an interchange id is not 2 to 15 characters.

Return type:

str

class x12sdk.io.X12ModelWriter(destination=None, *, sender_id, receiver_id, sender_qualifier='30', receiver_qualifier='30', interchange_control_number='000000001', group_control_number='1', created=None, usage_indicator='T')[source]

Collects transaction models and writes them out as one X12 interchange.

The mirror image of X12ModelReader: where the reader yields models from a file, the writer takes models and produces a file.

with X12ModelReader(“in.835”) as reader, X12ModelWriter(

“out.835”, sender_id=”SENDERID”, receiver_id=”RECEIVERID”

) as writer:
for model in reader.models():

writer.write(model)

The interchange is assembled and written when the with block exits normally, through write_transactions(), so the envelopes and control numbers follow the same rules. If the block raises, nothing is written: a half-built interchange never reaches disk. The result is also kept on interchange after closing.

Parameters:
interchange: str | None

The complete interchange, set when the writer closes.

write(transaction)[source]

Adds a transaction set model to the interchange.

Parameters:

transaction (X12SegmentGroup) – A transaction model, e.g. from X12ModelReader or x12sdk.generate.

Raises:

ValueError – if the model is not a transaction set, so the error points at the offending write rather than at the close.

Return type:

None

write_all(transactions)[source]

Adds each transaction in turn.

Parameters:

transactions (Iterable[X12SegmentGroup]) – Transaction set models.

Return type:

None

close()[source]

Assembles the interchange and writes it to the destination.

Called for you when a with block exits normally; call it yourself when not using with.

Returns:

The complete X12 interchange.

Raises:

ValueError – if nothing was written, or an interchange id is not 2 to 15 characters.

Return type:

str

Accessors

class x12sdk.access.ClaimStatusAccess[source]

claims() for the 276 and 277 transaction models.

The inquiry and the response have identical loop names at every level this walks, so one traversal serves both.

claims()[source]

Yields every tracked claim in the transaction, in file order.

A claim hangs off the subscriber when the subscriber is the patient and off the dependent otherwise, never both.

Return type:

Iterator[TrackedClaim]

class x12sdk.access.ClaimSubmissionAccess[source]

claims() and subscribers() for the 837 transaction models.

The professional, institutional and dental implementations have identical loop names down every level this walks, so one traversal serves all three.

subscribers()[source]

Yields every subscriber in the transaction, in file order.

Return type:

Iterator[Subscriber]

claims()[source]

Yields every claim in the transaction, in file order.

Claims filed for the subscriber and claims filed for a dependent both appear; SubmittedClaim.is_dependent says which, and patient already points at the right loop either way.

Return type:

Iterator[SubmittedClaim]

class x12sdk.access.EligibilityAccess[source]

members() for the 270 and 271 transaction models.

The inquiry and the response have identical loop names at every level this walks, so one traversal serves both.

members()[source]

Yields every person the transaction is about, in file order.

Subscribers who are themselves the patient and dependents both appear; EligibilityMember.is_dependent says which, and member already points at the right loop either way.

Return type:

Iterator[EligibilityMember]

class x12sdk.access.EligibilityMember(member, subscriber, payer, provider, benefits, is_dependent)[source]

One person an eligibility transaction is about, with its context.

member is the loop describing whoever the question is about: loop 2100D when they are a dependent, and the subscriber’s own loop 2100C when they are not. Reading it does not require knowing which.

Parameters:
member: Any
subscriber: Any
payer: Any
provider: Any
benefits: Tuple[Any, ...]
is_dependent: bool
property name: Tuple[str | None, str | None]
property subscriber_name: Tuple[str | None, str | None]
property member_id: str | None

NM109 on loop 2100C, the subscriber’s identifier with the payer.

property payer_name: str | None
property provider_name: str | None
property service_type_codes: Tuple[str, ...]

The service types asked about or answered, across every benefit loop.

EQ01 on an inquiry and EB03 on a response both repeat, so both come back flattened.

class x12sdk.access.PaidClaim(claim, payer, payee, header_number)[source]

One claim on an 835, with the payer and payee that settled it.

Parameters:
claim: Any
payer: Any
payee: Any
header_number: str
property patient_control_number: str

CLP01, matching CLM01 on the claim that was submitted.

property status: str

CLP02, the claim status code: 1 processed as primary, 4 denied, …

property charge: Decimal

CLP03, the total charge submitted.

property paid: Decimal

CLP04, what the payer paid.

property payer_claim_control_number: str | None

CLP07, the payer’s own identifier for the claim.

property service_lines: List[Any]

The 2110 loops, one per service line the payer reported.

property adjustments: List[Any]

The claim-level CAS segments. Service lines carry their own.

property patient: Any | None

The NM1*QC patient name, which the 835 does not require.

property patient_name: Tuple[str | None, str | None]
property payer_name: str | None
property payee_name: str | None
class x12sdk.access.RemittanceAccess[source]

claims() for the 835 transaction model.

claims()[source]

Yields every claim payment in the transaction, in file order.

An 835 groups claims under LX header numbers; header_number keeps the grouping available without having to nest to reach it.

Return type:

Iterator[PaidClaim]

class x12sdk.access.SubmittedClaim(claim, billing_provider, subscriber, payer, patient, is_dependent, relationship)[source]

One claim on an 837, with the loops that give it meaning.

patient is the loop describing whoever was treated: loop 2010CA when the patient is a dependent, and the subscriber’s own loop 2010BA when they are not. Reading it does not require knowing which, which is the point.

Parameters:
  • claim (Any)

  • billing_provider (Any)

  • subscriber (Any)

  • payer (Any)

  • patient (Any)

  • is_dependent (bool)

  • relationship (str | None)

claim: Any
billing_provider: Any
subscriber: Any
payer: Any
patient: Any
is_dependent: bool
relationship: str | None
property patient_control_number: str

CLM01, the provider’s own identifier for the claim.

property charge: Decimal

CLM02, the total charge submitted.

property service_lines: List[Any]

The 2400 loops, one per service line (SV1, SV2 or SV3 by claim type).

property patient_name: Tuple[str | None, str | None]
property subscriber_name: Tuple[str | None, str | None]
property member_id: str | None

NM109 on loop 2010BA, the subscriber’s identifier with the payer.

property payer_name: str | None
property billing_provider_name: str | None
property billing_provider_npi: str | None

NM109 on loop 2010AA, present when NM108 qualifies it as an NPI.

class x12sdk.access.Subscriber(subscriber, billing_provider, payer, dependents)[source]

One subscriber on an 837, and the dependents filed beneath them.

Parameters:
subscriber: Any
billing_provider: Any
payer: Any
dependents: Tuple[Any, ...]
property name: Tuple[str | None, str | None]
property member_id: str | None
class x12sdk.access.TrackedClaim(status, patient, subscriber, payer, requester, provider, is_dependent)[source]

One claim being asked about on a 276 or reported on a 277.

patient is loop 2100E when the patient is a dependent and the subscriber’s own loop 2100D when they are not.

Parameters:
status: Any
patient: Any
subscriber: Any
payer: Any
requester: Any
provider: Any
is_dependent: bool
property trace_number: str | None

TRN02, which ties an inquiry to the response answering it.

property patient_name: Tuple[str | None, str | None]
property member_id: str | None
property payer_name: str | None
property provider_name: str | None
property statuses: Tuple[Any, ...]

The STC segments. Empty on a 276, which asks rather than answers.

property charge: Decimal | None

What was billed.

The inquiry states it in AMT*T3 and the response in STC04, so the caller does not have to know which transaction it is holding.

property paid: Decimal | None

STC05, present only on a response.

Generating

class x12sdk.generate.AdjustmentSpec(group, reason, amount, quantity=None)[source]

One CAS adjustment: why an amount was not paid.

Parameters:
group: str
reason: str
amount: Decimal
quantity: Decimal | None = None
class x12sdk.generate.BenefitSpec(service_type='30', status='1', coverage_level=None, plan_description=None)[source]

One line of coverage: a question on a 270, an answer on a 271.

The same description serves both, so an inquiry and the response to it can be generated as a matched pair from one specification.

Parameters:
  • service_type (str)

  • status (str)

  • coverage_level (str | None)

  • plan_description (str | None)

service_type: str = '30'
status: str = '1'
coverage_level: str | None = None
plan_description: str | None = None
class x12sdk.generate.ClaimPair(claim, remittance)[source]

A claim submission and the remittance that answers it, as two complete interchanges. Unpacks as claim, remittance = generate_claim_pair(...).

Parameters:
  • claim (str)

  • remittance (str)

claim: str

Alias for field number 0

remittance: str

Alias for field number 1

class x12sdk.generate.ClaimSpec(charge, adjustments=<factory>, lines=<factory>, status='1', patient_control_number=None)[source]

One claim on a remittance.

Give the charge and the adjustments; the payment is derived. Claim-level adjustments and service-line adjustments both count toward the balance, which is what the 835 requires.

Parameters:
charge: Decimal
adjustments: Sequence[AdjustmentSpec]
lines: Sequence[ServiceLineSpec]
status: str = '1'
patient_control_number: str | None = None
property adjustment_total: Decimal

Every adjustment on the claim, at claim level and on its lines.

property paid: Decimal

Derived, never supplied: charge minus every adjustment.

class x12sdk.generate.ClaimStatusSpec(patients, payer_name=None, requester_name=None, provider_name=None)[source]

A whole 276 or 277: one payer, one requester, one provider, its patients.

Parameters:
patients: Sequence[StatusPatientSpec]
payer_name: str | None = None
requester_name: str | None = None
provider_name: str | None = None
class x12sdk.generate.CoverageSpec(insurance_line='HLT', maintenance_type='021', coverage_level=None, plan_description=None)[source]

One HD coverage line on an enrollment: what the member is enrolled in.

Parameters:
  • insurance_line (str)

  • maintenance_type (str)

  • coverage_level (str | None)

  • plan_description (str | None)

insurance_line: str = 'HLT'
maintenance_type: str = '021'
coverage_level: str | None = None
plan_description: str | None = None
class x12sdk.generate.DisabilitySpec(type='2', begins=None, ends=None, diagnosis=None)[source]

One disability period on a member (loop 2200: a DSB with its dates).

A member can carry several, and they repeat as separate loops; code that keeps only the last one is a bug this generator exists to expose.

Parameters:
  • type (str)

  • begins (str | None)

  • ends (str | None)

  • diagnosis (str | None)

type: str = '2'
begins: str | None = None
ends: str | None = None
diagnosis: str | None = None
class x12sdk.generate.EligibilitySpec(members, payer_name=None, provider_name=None)[source]

A whole 270 or 271: one payer, one provider, a set of members.

Parameters:
members: Sequence[MemberSpec]
payer_name: str | None = None
provider_name: str | None = None
class x12sdk.generate.EmployerSpec(name, identifier=None)[source]

One employer of a member (loop 2100D). Up to three per member.

Parameters:
  • name (str)

  • identifier (str | None)

name: str
identifier: str | None = None
class x12sdk.generate.EnrolleeSpec(coverages=<factory>, dependent=False, relationship='19', member_id=None, benefit_status='A', maintenance_type='021', employers=<factory>, disabilities=<factory>)[source]

One member on an 834.

The 834 has no HL hierarchy. A dependent is a separate member record marked by INS01 rather than a loop nested under the subscriber, so dependent changes the record rather than where it sits.

Parameters:
coverages: Sequence[CoverageSpec]
dependent: bool = False
relationship: str = '19'
member_id: str | None = None
benefit_status: str = 'A'
maintenance_type: str = '021'
employers: Sequence[EmployerSpec]
disabilities: Sequence[DisabilitySpec]
class x12sdk.generate.EnrollmentSpec(enrollees, sponsor_name=None, payer_name=None)[source]

A whole 834: one sponsor, one payer, a roster of members.

Parameters:
enrollees: Sequence[EnrolleeSpec]
sponsor_name: str | None = None
payer_name: str | None = None
class x12sdk.generate.MemberSpec(benefits=<factory>, dependent=False, relationship='19', member_id=None)[source]

One person an eligibility transaction is about.

As on an 837, the person is either the subscriber or a dependent of one, and the two sit at different depths of the hierarchy. Unlike an 837 the payload is coverage rather than claims, so this is a separate type from PatientSpec.

Parameters:
benefits: Sequence[BenefitSpec]
dependent: bool = False
relationship: str = '19'
member_id: str | None = None
class x12sdk.generate.PatientSpec(claims, dependent=False, relationship='19')[source]

One patient on a claim submission, with the claims filed for them.

In an 837 a patient is either the subscriber themselves or a dependent of one, and the two sit at different depths in the hierarchy. Saying which here is what puts the claim on the right branch.

Parameters:
claims: Sequence[ClaimSpec]
dependent: bool = False
relationship: str = '19'
class x12sdk.generate.ProviderAdjustmentSpec(reason, amount, identifier=None)[source]

One provider-level adjustment: money moved at the payee level, outside any claim, carried in the PLB segment. A positive amount is taken out of the payment (an overpayment recovery, a withholding); a negative amount is added to it (interest owed to the provider).

Parameters:
reason: str
amount: Decimal
identifier: str | None = None
class x12sdk.generate.RemittanceSpec(claims, payer_name=None, payee_name=None, provider_adjustments=<factory>)[source]

A whole 835: one payer paying one payee for a set of claims.

The check amount in BPR02 is derived: every claim’s payment, less the provider-level adjustments. A remittance whose adjustments exceed what the claims pay would need a negative check, which the 835 does not allow, so it cannot be written down.

Parameters:
claims: Sequence[ClaimSpec]
payer_name: str | None = None
payee_name: str | None = None
provider_adjustments: Sequence[ProviderAdjustmentSpec]
property claims_paid: Decimal

The sum of CLP04 over every claim, before provider-level adjustments.

property provider_adjustment_total: Decimal
property total_paid: Decimal

BPR02: what the check is for. Derived, never supplied.

class x12sdk.generate.ServiceLineSpec(charge, procedure=None, adjustments=<factory>, units=1, tooth=None, surfaces=<factory>)[source]

One service line on a claim.

tooth and surfaces describe a dental line (the 837D’s TOO segment) and are refused on a professional or institutional claim, which has nowhere to put them. An 835 paying a dental claim does not repeat them.

Parameters:
charge: Decimal
procedure: str | None = None
adjustments: Sequence[AdjustmentSpec]
units: int = 1
tooth: str | None = None
surfaces: Sequence[str]
property adjustment_total: Decimal
property paid: Decimal

What the payer allowed on this line.

class x12sdk.generate.StatusPatientSpec(claims, dependent=False, relationship='19', member_id=None)[source]

A patient on a 276 or 277, and the claims being tracked for them.

Parameters:
claims: Sequence[TrackedClaimSpec]
dependent: bool = False
relationship: str = '19'
member_id: str | None = None
class x12sdk.generate.SubmissionSpec(patients, billing_provider_name=None, payer_name=None, submitter_name=None)[source]

A whole 837: one billing provider filing claims with one payer.

Parameters:
patients: Sequence[PatientSpec]
billing_provider_name: str | None = None
payer_name: str | None = None
submitter_name: str | None = None
property total_charge: Decimal
refuse_teeth(claim_type)[source]

Raises if any line names a tooth, for the claim types that cannot carry one, rather than dropping it from the output without a word.

Parameters:

claim_type (str)

Return type:

None

class x12sdk.generate.TrackedClaimSpec(charge, patient_control_number=None, payer_claim_control_number=None, paid=None, status_category='F1', status_code='1')[source]

One claim whose status is asked about on a 276 or reported on a 277.

paid and the status codes are only rendered on the response; an inquiry carries the identifying detail and nothing else, so the same specification builds a 276 and the 277 answering it.

Parameters:
  • charge (Decimal)

  • patient_control_number (str | None)

  • payer_claim_control_number (str | None)

  • paid (Decimal | None)

  • status_category (str)

  • status_code (str)

charge: Decimal
patient_control_number: str | None = None
payer_claim_control_number: str | None = None
paid: Decimal | None = None
status_category: str = 'F1'
status_code: str = '1'
class x12sdk.generate.ValueFactory(seed)[source]

Produces plausible, obviously synthetic values from a seeded RNG.

Parameters:

seed (int)

npi()[source]

A syntactically valid 10 digit NPI, check digit included.

Return type:

str

tax_id()[source]
Return type:

str

member_id()[source]
Return type:

str

control_number(width=9)[source]
Parameters:

width (int)

Return type:

str

claim_number(index)[source]
Parameters:

index (int)

Return type:

str

payer_claim_number()[source]
Return type:

str

person_name()[source]

Returns (last, first).

Return type:

tuple

plan_name()[source]
Return type:

str

provider_name()[source]
Return type:

str

dental_provider_name()[source]
Return type:

str

employer_name()[source]
Return type:

str

address()[source]
Return type:

str

city()[source]
Return type:

str

state()[source]
Return type:

str

postal_code()[source]
Return type:

str

phone_number()[source]

Ten digits in the 555 exchange, which is reserved for fiction.

Return type:

str

procedure()[source]
Return type:

str

dental_procedure()[source]

Returns (code, tooth, surfaces) for a dental service line.

tooth is None for a procedure not done to one tooth (an exam, a cleaning), and surfaces is empty unless the procedure is a filling, whose code says how many surfaces it covers.

Return type:

tuple

dental_fee(code)[source]

A fee in the usual range for a code from dental_procedure().

Parameters:

code (str)

Return type:

Decimal

diagnosis()[source]

An ICD-10-CM code with the decimal point removed, as X12 carries it.

Return type:

str

birth_date(youngest=1, oldest=90)[source]

A date of birth, relative to the same fixed epoch as service dates.

Parameters:
Return type:

date

amount(low=50, high=5000)[source]

A money amount with two decimal places.

Parameters:
Return type:

Decimal

service_date(within_days=365)[source]

A date in the recent past, relative to a fixed epoch for reproducibility.

Parameters:

within_days (int)

Return type:

date

split(total, parts)[source]

Splits an amount into parts that sum back to it exactly.

Used so service line charges add up to the claim charge, which the 837 models enforce.

Parameters:
Return type:

List[Decimal]

x12sdk.generate.adjudicate(claim, values, *, denial_rate=0.15)[source]

Decides an invented outcome for a submitted claim.

A share denial_rate of claims is denied outright (CLP02 4, every line adjusted to nothing). The rest are processed as primary: most with a contractual write-off on each line (CO 45, the usual gap between charge and fee schedule), some also leaving a deductible or coinsurance to the patient (PR), and some paid in full. Outcomes are made of adjustments, so the payment is derived and the 835 balances by construction.

Parameters:
Return type:

ClaimSpec

x12sdk.generate.build_270(spec, *, seed=0, control_number='0001')[source]

Builds a validated 270 eligibility inquiry from a specification.

Parameters:
  • spec (EligibilitySpec) – Who is asking, of whom, and about which members.

  • seed (int) – Seeds the values the specification leaves unstated.

  • control_number (str) – ST02/SE02. At least 4 characters.

Return type:

EligibilityInquiry

Every benefit in the specification is rendered. EQ repeats within loop 2110, so an inquiry can ask about several service types at once.

x12sdk.generate.build_271(spec, *, seed=0, control_number='0001')[source]

Builds a validated 271 eligibility response from a specification.

The 271 carries a list of EB segments per member, so every benefit in the specification appears. This is the asymmetry that makes the 270 raise.

Parameters:
Return type:

EligibilityBenefit

x12sdk.generate.build_276(spec, *, seed=0, control_number='0001')[source]

Builds a validated 276 claim status inquiry from a specification.

Parameters:
Return type:

HealthCareClaimsStatusRequest

x12sdk.generate.build_277(spec, *, seed=0, control_number='0001')[source]

Builds a validated 277 claim status response from a specification.

Takes the same specification as build_276(), so an inquiry and the response to it can be built as a matched pair.

Parameters:
Return type:

HealthCareClaimsStatusResponse

x12sdk.generate.build_834(spec, *, seed=0, control_number='0001')[source]

Builds a validated 834 enrollment transaction from a specification.

Parameters:
  • spec (EnrollmentSpec) – The sponsor, the payer, and the roster of members.

  • seed (int) – Seeds the values the specification leaves unstated.

  • control_number (str) – ST02/SE02. At least 4 characters.

Return type:

BenefitEnrollmentAndMaintenance

x12sdk.generate.build_835(spec, *, seed=0, control_number='0001', procedure_qualifier='HC', patients=None, payee_npi=None)[source]

Builds a validated 835 transaction model from a specification.

The last three parameters let the remittance answer a particular claim submission, which is how generate_claim_pair() keeps the two in step.

Parameters:
  • spec (RemittanceSpec) – What the remittance should contain.

  • seed (int) – Seeds the values that the specification leaves unstated.

  • control_number (str) – ST02/SE02. At least 4 characters, per the standard.

  • procedure_qualifier (str) – SVC01-1. HC for HCPCS/CPT, AD for dental (CDT) codes.

  • patients (Sequence[Tuple[str, str, str]] | None) – (last, first, member id) for each claim, in order, for the NM1*QC patient name. Invented when not given.

  • payee_npi (str | None) – The payee’s NPI. Invented when not given.

Returns:

A validated HealthCareClaimPayment.

Return type:

HealthCareClaimPayment

x12sdk.generate.build_837d(spec, *, seed=0, control_number='0001')[source]

Builds a validated 837D transaction model from a specification.

Parameters:
  • spec (SubmissionSpec) – What the submission should contain. A line’s tooth and surfaces become its TOO segment.

  • seed (int) – Seeds the values that the specification leaves unstated.

  • control_number (str) – ST02/SE02. At least 4 characters, per the standard.

Returns:

A validated HealthCareClaimDental.

Return type:

HealthCareClaimDental

x12sdk.generate.build_837i(spec, *, seed=0, control_number='0001')[source]

Builds a validated 837I transaction model from a specification.

Parameters:
  • spec (SubmissionSpec) – What the submission should contain.

  • seed (int) – Seeds the values that the specification leaves unstated.

  • control_number (str) – ST02/SE02. At least 4 characters, per the standard.

Return type:

HealthCareClaimInstitutional

x12sdk.generate.build_837p(spec, *, seed=0, control_number='0001')[source]

Builds a validated 837P transaction model from a specification.

Parameters:
  • spec (SubmissionSpec) – What the submission should contain.

  • seed (int) – Seeds the values that the specification leaves unstated.

  • control_number (str) – ST02/SE02. At least 4 characters, per the standard.

Returns:

A validated HealthCareClaimProfessional.

Return type:

HealthCareClaimProfessional

x12sdk.generate.build_claim_pair(claims, *, claim_type='837p', seed=0, dependent_rate=0.3, billing_provider_name=None, payer_name=None, control_number='0001')[source]

Builds a claim submission model and the remittance model that answers it.

Parameters:
  • claims (Sequence[ClaimSpec]) – The claims, each with its outcome: adjustments and status are what the payer decided, everything else is what was submitted.

  • claim_type (str)

  • seed (int)

  • dependent_rate (float)

  • billing_provider_name (str | None)

  • payer_name (str | None)

  • control_number (str)

Returns:

(submission, remittance) models, both validated.

Return type:

Tuple

x12sdk.generate.claim_pair_specs(count, values, *, claim_type='837p', denial_rate=0.15)[source]

Invents count claims of a type, each with an invented outcome.

Parameters:
Return type:

List[ClaimSpec]

x12sdk.generate.claim_specs_to_patients(claims, values, *, dependent_rate=0.3)[source]

Puts one claim on each patient, splitting them across both branches.

Parameters:
Return type:

List[PatientSpec]

x12sdk.generate.denial(group, reason, amount)[source]

Shorthand for a payer-side adjustment.

>>> denial("CO", "45", "30.00").amount
Decimal('30.00')
Parameters:
Return type:

AdjustmentSpec

x12sdk.generate.generate_270(*, seed=0, members=5, dependent_rate=0.3, payer_name=None, provider_name=None, sender_id='SYNTHETICPROV', receiver_id='SYNTHETICPAYER', control_number='0001')[source]

Generates a complete 270 eligibility inquiry.

Parameters:
  • seed (int) – Reproduces the same file when unchanged.

  • members (int | Sequence[MemberSpec] | EligibilitySpec) – A number of members to invent, specifications to follow, or a whole EligibilitySpec.

  • dependent_rate (float) – The share of members who are a dependent of the subscriber rather than the subscriber themselves, so generated files exercise both branches. Ignored when an EligibilitySpec is given.

  • payer_name (str | None) – Defaults to a synthetic plan name.

  • provider_name (str | None) – Defaults to a synthetic provider name.

  • sender_id (str) – ISA06 / GS02.

  • receiver_id (str) – ISA08 / GS03.

  • control_number (str) – ST02 / SE02, at least 4 characters.

Returns:

The interchange, ISA through IEA.

Return type:

str

x12sdk.generate.generate_271(*, seed=0, members=5, dependent_rate=0.3, payer_name=None, provider_name=None, sender_id='SYNTHETICPAYER', receiver_id='SYNTHETICPROV', control_number='0001')[source]

Generates a complete 271 eligibility response.

Takes the same specification as generate_270(), so an inquiry and the response to it can be generated as a matched pair from one spec.

Returns:

The interchange, ISA through IEA.

Parameters:
Return type:

str

x12sdk.generate.generate_276(*, seed=0, patients=5, dependent_rate=0.3, payer_name=None, requester_name=None, provider_name=None, sender_id='SYNTHETICPROV', receiver_id='SYNTHETICPAYER', control_number='0001')[source]

Generates a complete 276 claim status inquiry.

Parameters:
  • seed (int) – Reproduces the same file when unchanged.

  • patients (int | Sequence[StatusPatientSpec] | ClaimStatusSpec) – A number of patients to invent, specifications to follow, or a whole ClaimStatusSpec.

  • dependent_rate (float) – The share of patients who are a dependent of the subscriber rather than the subscriber themselves, so generated files exercise both branches. Ignored when a ClaimStatusSpec is given.

  • payer_name (str | None) – Defaults to a synthetic plan name.

  • requester_name (str | None) – The information receiver asking. Defaults to a synthetic name.

  • provider_name (str | None) – The service provider the claims belong to.

  • sender_id (str) – ISA06 / GS02.

  • receiver_id (str) – ISA08 / GS03.

  • control_number (str) – ST02 / SE02, at least 4 characters.

Returns:

The interchange, ISA through IEA.

Return type:

str

x12sdk.generate.generate_277(*, seed=0, patients=5, dependent_rate=0.3, payer_name=None, requester_name=None, provider_name=None, sender_id='SYNTHETICPAYER', receiver_id='SYNTHETICPROV', control_number='0001')[source]

Generates a complete 277 claim status response.

Takes the same specification as generate_276() and stays in step with it on the same seed, so an inquiry and the response to it describe the same people and the same claims.

Returns:

The interchange, ISA through IEA.

Parameters:
Return type:

str

x12sdk.generate.generate_834(*, seed=0, enrollees=5, dependent_rate=0.3, sponsor_name=None, payer_name=None, sender_id='SYNTHSPONSOR', receiver_id='SYNTHETICPAYER', control_number='0001')[source]

Generates a complete 834 benefit enrollment and maintenance transaction.

The 834 has no HL hierarchy: a dependent is a separate member record told apart by INS01 and INS02, not a loop nested under the subscriber. Both kinds of record appear by default so code reading an 834 can be tested on each.

Parameters:
  • seed (int) – Reproduces the same file when unchanged.

  • enrollees (int | Sequence[EnrolleeSpec] | EnrollmentSpec) – A number of members to invent, specifications to follow, or a whole EnrollmentSpec.

  • dependent_rate (float) – The share of records marked as a dependent. Ignored when an EnrollmentSpec is given.

  • sponsor_name (str | None) – The plan sponsor. Defaults to a synthetic name.

  • payer_name (str | None) – Defaults to a synthetic plan name.

  • sender_id (str) – ISA06 / GS02.

  • receiver_id (str) – ISA08 / GS03.

  • control_number (str) – ST02 / SE02, at least 4 characters.

Returns:

The interchange, ISA through IEA.

Return type:

str

x12sdk.generate.generate_835(*, seed=0, claims=5, provider_adjustments=None, payer_name=None, payee_name=None, sender_id='SYNTHETICPAYER', receiver_id='SYNTHETICPROV', control_number='0001')[source]

Generates a complete 835 remittance advice.

Parameters:
  • seed (int) – Reproduces the same file when unchanged.

  • claims (int | Sequence[ClaimSpec]) – A number of claims to invent, or specifications to follow.

  • provider_adjustments (int | Sequence[ProviderAdjustmentSpec] | None) – Provider-level (PLB) adjustments: a number to invent, specifications to follow, or None for the default, which is one invented adjustment when the claims are invented and none when they are specified, so a described scenario contains only what it describes. At most six fit on a remittance.

  • payer_name (str | None) – Defaults to a synthetic plan name.

  • payee_name (str | None) – Defaults to a synthetic provider name.

  • sender_id (str) – ISA06 / GS02.

  • receiver_id (str) – ISA08 / GS03.

  • control_number (str) – ST02 / SE02, at least 4 characters.

Returns:

The interchange, ISA through IEA.

Return type:

str

x12sdk.generate.generate_837d(*, seed=0, claims=5, dependent_rate=0.3, billing_provider_name=None, payer_name=None, submitter_name=None, sender_id='SYNTHETICPROV', receiver_id='SYNTHETICPAYER', control_number='0001')[source]

Generates a complete 837D dental claim submission.

Takes the same specification as generate_837p(). A ServiceLineSpec’s procedure is a CDT code, billed under the AD qualifier, and its tooth and surfaces become the line’s TOO segment. Invented lines mix procedures done to a tooth (with surfaces for a filling) and procedures that are not (an exam, a cleaning), and both patient branches appear by default.

Returns:

The interchange, ISA through IEA.

Parameters:
Return type:

str

x12sdk.generate.generate_837i(*, seed=0, claims=5, dependent_rate=0.3, billing_provider_name=None, payer_name=None, submitter_name=None, sender_id='SYNTHETICPROV', receiver_id='SYNTHETICPAYER', control_number='0001')[source]

Generates a complete 837I institutional claim submission.

Takes the same specification as generate_837p(); a ServiceLineSpec’s procedure becomes the SV2 procedure composite, billed under a revenue code. The subscriber/dependent branch is the same, and both appear by default.

Returns:

The interchange, ISA through IEA.

Parameters:
Return type:

str

x12sdk.generate.generate_837p(*, seed=0, claims=5, dependent_rate=0.3, billing_provider_name=None, payer_name=None, submitter_name=None, sender_id='SYNTHETICPROV', receiver_id='SYNTHETICPAYER', control_number='0001')[source]

Generates a complete 837P professional claim submission.

Parameters:
  • seed (int) – Reproduces the same file when unchanged.

  • claims (int | Sequence[ClaimSpec] | SubmissionSpec) – A number of claims to invent, specifications to follow, or a whole SubmissionSpec when you want to place each claim on a particular patient.

  • dependent_rate (float) – The share of patients who are a dependent of the subscriber rather than the subscriber themselves, so generated files exercise both branches of the hierarchy. Ignored when a SubmissionSpec is given, which says where each claim goes.

  • billing_provider_name (str | None) – Defaults to a synthetic provider name.

  • payer_name (str | None) – Defaults to a synthetic plan name.

  • submitter_name (str | None) – Defaults to the billing provider.

  • sender_id (str) – ISA06 / GS02.

  • receiver_id (str) – ISA08 / GS03.

  • control_number (str) – ST02 / SE02, at least 4 characters.

Returns:

The interchange, ISA through IEA.

Return type:

str

x12sdk.generate.generate_claim_pair(*, seed=0, claims=5, claim_type='837p', denial_rate=0.15, dependent_rate=0.3, billing_provider_name=None, payer_name=None, provider_id='SYNTHETICPROV', payer_id='SYNTHETICPAYER', control_number='0001')[source]

Generates a claim submission and the remittance that answers it.

Every claim on the 837 is paid, reduced or denied by exactly one claim payment on the 835, linked by CLM01 = CLP01, with the same charge, the same procedure on each line, and the same patient, payer and payee.

Parameters:
  • seed (int) – Reproduces the same pair when unchanged.

  • claims (int | Sequence[ClaimSpec]) – A number of claims to invent, outcomes included, or ClaimSpec``s to follow: a spec's lines and charges are what was submitted, its adjustments and ``status what the payer decided.

  • claim_type (str) – "837p", "837i" or "837d".

  • denial_rate (float) – The share of invented claims denied outright. The rest are paid, most less a contractual write-off, some also leaving a share to the patient. Ignored when the claims are specified.

  • dependent_rate (float) – The share of patients who are a dependent of the subscriber, as for generate_837p().

  • billing_provider_name (str | None) – The provider billing, and so the payee.

  • payer_name (str | None) – The payer billed, and so the payer paying.

  • provider_id (str) – The provider’s interchange id: the 837’s sender and the 835’s receiver.

  • payer_id (str) – The payer’s interchange id, the other way round.

  • control_number (str) – ST02 / SE02 on both, at least 4 characters.

Returns:

ClaimPair(claim, remittance), two complete interchanges.

Return type:

ClaimPair

x12sdk.generate.patient_responsibility(reason, amount)[source]

Shorthand for a PR adjustment: deductible, coinsurance or copay.

Parameters:

reason (str)

Return type:

AdjustmentSpec

x12sdk.generate.provider_adjustment(reason, amount, identifier=None)[source]

Shorthand for a PLB provider-level adjustment.

>>> provider_adjustment("WO", "25.00", "PCN000001").amount
Decimal('25.00')
Parameters:
  • reason (str)

  • identifier (str | None)

Return type:

ProviderAdjustmentSpec

x12sdk.generate.random_claims(count, values, *, denial_rate=0.4)[source]

Builds plausible claims with a mix of paid, adjusted and denied outcomes.

Used when a caller asks for a number of claims rather than describing each one. denial_rate is the share of claims carrying a payer-side adjustment; the rest are paid in full or carry only patient cost share.

Parameters:
Return type:

List[ClaimSpec]

x12sdk.generate.random_dental_lines(values, count)[source]

Invents count dental lines, each with its procedure, and the tooth and surfaces that procedure implies, already decided.

Parameters:
Return type:

List[ServiceLineSpec]

x12sdk.generate.random_dental_patients(count, values, *, dependent_rate=0.3)[source]

Builds plausible dental patients carrying one claim each.

A visit is one to four lines, so files mix lines with a tooth, lines with a tooth and surfaces, and lines with neither. dependent_rate is the share of patients who are a dependent rather than the subscriber.

Parameters:
Return type:

List[PatientSpec]

x12sdk.generate.random_enrollees(count, values, *, dependent_rate=0.3)[source]

Builds a roster mixing subscribers and dependents.

dependent_rate is the share of records marked as a dependent, so both kinds of INS record appear by default. Every subscriber carries an employer, a quarter of them a second one, and a fifth of all members a disability period, so the repeating 2100D and 2200 loops, where a reader that keeps only the last record goes wrong, are exercised by default.

Parameters:
Return type:

List[EnrolleeSpec]

x12sdk.generate.random_members(count, values, *, dependent_rate=0.3)[source]

Builds members asking about whole-plan coverage.

dependent_rate is the share who are a dependent of the subscriber rather than the subscriber themselves, so both branches appear by default.

Parameters:
Return type:

List[MemberSpec]

x12sdk.generate.random_patients(count, values, *, dependent_rate=0.3)[source]

Builds plausible patients carrying one claim each.

dependent_rate is the share of patients who are a dependent of the subscriber rather than the subscriber themselves. Both branches appear by default, because code that walks an 837 tends to handle only one of them.

Parameters:
Return type:

List[PatientSpec]

x12sdk.generate.random_provider_adjustments(count, values, claims)[source]

Invents provider-level adjustments small enough to leave the check positive.

Two kinds appear: an overpayment recovery (WO) naming the claim it recovers, taken out of the payment, and interest owed to the provider (L6), added to it as a negative amount. Each is at most a few percent of what the claims pay, so BPR02 stays non-negative however many are asked for (up to the six a PLB holds).

Parameters:
Return type:

List[ProviderAdjustmentSpec]

x12sdk.generate.random_status_patients(count, values, *, dependent_rate=0.3)[source]

Builds patients each tracking one claim, across both branches.

dependent_rate is the share who are a dependent of the subscriber rather than the subscriber themselves.

Parameters:
Return type:

List[StatusPatientSpec]

Denial analytics

class x12sdk.denials.Adjustment(payer_name, payer_id, patient_control_number, payer_claim_control_number, claim_status_code, claim_charge_amount, claim_payment_amount, patient_responsibility_amount, level, group_code, reason_code, amount, quantity, category, procedure=None, revenue_code=None, line_charge_amount=None, line_payment_amount=None, remark_codes=<factory>)[source]

One CAS reason code, with the claim and line it came from.

Amounts are the values as adjudicated: amount is the adjustment, not the charge. A positive amount reduces what the payer pays.

Parameters:
  • payer_name (str | None)

  • payer_id (str | None)

  • patient_control_number (str | None)

  • payer_claim_control_number (str | None)

  • claim_status_code (str | None)

  • claim_charge_amount (Decimal | None)

  • claim_payment_amount (Decimal | None)

  • patient_responsibility_amount (Decimal | None)

  • level (str)

  • group_code (str | None)

  • reason_code (str | None)

  • amount (Decimal)

  • quantity (Decimal | None)

  • category (str)

  • procedure (str | None)

  • revenue_code (str | None)

  • line_charge_amount (Decimal | None)

  • line_payment_amount (Decimal | None)

  • remark_codes (Tuple[str, ...])

payer_name: str | None
payer_id: str | None
patient_control_number: str | None
payer_claim_control_number: str | None
claim_status_code: str | None
claim_charge_amount: Decimal | None
claim_payment_amount: Decimal | None
patient_responsibility_amount: Decimal | None
level: str
group_code: str | None
reason_code: str | None
amount: Decimal
quantity: Decimal | None
category: str
procedure: str | None = None
revenue_code: str | None = None
line_charge_amount: Decimal | None = None
line_payment_amount: Decimal | None = None
remark_codes: Tuple[str, ...]
is_denial(denial_groups=frozenset({'CO', 'OA', 'PI'}))[source]

True when the adjustment group is payer-side rather than patient cost share.

Parameters:

denial_groups (frozenset)

Return type:

bool

class x12sdk.denials.DenialSummaryRow(payer_name, group_code, reason_code, category, adjustment_count, claim_count, total_amount)[source]

One payer/group/reason combination, with its volume and value.

Parameters:
  • payer_name (str | None)

  • group_code (str | None)

  • reason_code (str | None)

  • category (str)

  • adjustment_count (int)

  • claim_count (int)

  • total_amount (Decimal)

payer_name: str | None
group_code: str | None
reason_code: str | None
category: str
adjustment_count: int
claim_count: int
total_amount: Decimal
x12sdk.denials.categorize(reason_code)[source]

Returns the analysis category for a CARC, or other when unmapped.

>>> categorize("45")
'contractual'
>>> categorize("A2")
'other'
Parameters:

reason_code (str | None)

Return type:

str

x12sdk.denials.category_map()[source]

Returns a copy of the CARC to category mapping.

Return type:

Mapping[str, str]

x12sdk.denials.denial_summary(adjustments, *, denial_groups=frozenset({'CO', 'OA', 'PI'}), include_patient_responsibility=False)[source]

Aggregates adjustments by payer, adjustment group and reason code.

By default only payer-side groups are counted (CO, OA, PI); patient cost share (PR) and corrections (CR) are excluded, because a deductible is not a denial. Set include_patient_responsibility to keep every group.

claim_count counts distinct claims, so a reason appearing on three lines of one claim counts once. adjustment_count counts every occurrence.

Returns:

Rows sorted by total_amount descending.

Parameters:
Return type:

List[DenialSummaryRow]

x12sdk.denials.describe(rows, descriptions)[source]

Attaches descriptions from a code list you loaded.

x12sdk ships no CARC/RARC text; see x12sdk.denials.load_code_descriptions().

Parameters:
Returns:

One dict per row with a description key added.

Return type:

List[dict]

x12sdk.denials.iter_adjustments(transaction)[source]

Flattens every CAS adjustment in an 835 into Adjustment records.

Parameters:

transaction – A HealthCareClaimPayment model, as returned by x12sdk.io.X12ModelReader.

Returns:

One record per populated CAS reason code, claim level first then each service line, in transaction order.

Return type:

Iterator[Adjustment]

Claims are reached through x12sdk.access.RemittanceAccess.claims() rather than by walking loops here.

>>> from x12sdk.io import X12ModelReader
>>> from x12sdk.denials import iter_adjustments
>>> with X12ModelReader(remittance) as reader:
...     for txn in reader.models():
...         rows = list(iter_adjustments(txn))
x12sdk.denials.load_code_descriptions(source, *, code_field='code', text_field='text')[source]

Loads CARC/RARC descriptions from a file you supply.

x12sdk ships no code-list text. Obtain the official list from <https://x12.org/codes> (or a CMS publication of it) under the licence that applies to you, then load it here.

Accepts either a JSON object of {code: text} or a CSV with a code column and a text column, whose names default to code and text.

Parameters:
  • source (str | Path) – Path to a .json or .csv file.

  • code_field (str) – CSV column holding the code.

  • text_field (str) – CSV column holding the description.

Returns:

Mapping of code to description.

Return type:

Dict[str, str]

x12sdk.denials.to_dataframe(adjustments)[source]

Returns the adjustments as a pandas DataFrame.

Requires the optional pandas dependency: pip install 'x12sdk[pandas]'. Amounts stay as Decimal so totals are exact; cast them yourself if you need float maths.

Parameters:

adjustments (Iterable[Adjustment])