FHIR Billing SDK API reference

Generated from the TypeScript declarations published in @cognovis/fhir-billing-sdk 0.51.0, the version the npm dist-tag latest named at render time. FHIR Billing SDK · All SDKs.

Entry points

@cognovis/fhir-billing-sdk

Re-exports BillingCatalogEditionManifestV1, BillingCatalogSource, BillingReasonCode, BILLING_FACT_SOURCE_ORIGINS, BILLING_NATIVE_FACT_NAMES, AdmissionState, BillingCase, BillingFactSourceDeclaration, BillingFactSourceOrigin, BillingFactUnavailableCause, BillingLine, BillingNativeFactName, BillingRuleProvenance, BillingRuleSet, BillingRuleSource, BillingRuleSourceKind, Coding from @cognovis/fhir-billing-types.

Re-exports BILLING_CONFORMANCE_FORMAT, compareConformanceRecords, evaluateConformanceCases, BillingConformanceBlockingPair, BillingConformanceDecision, BillingConformanceDifference, BillingConformanceFinding, BillingConformanceRecord, BillingConformanceRuleSetIdentity, BillingConformanceSide, BillingReasonResolution, BillingResolutionCode, EvaluateConformanceCasesInput from @cognovis/fhir-billing-engine.

assertWriterSnapshot function

function assertWriterSnapshot(current: WriterSnapshot, bound: BoundWriter): 'ok' | 'conflict';

bindWriterPreconditions function

function bindWriterPreconditions(preconditions: readonly WriterPrecondition[], snapshot?: {
    identityDigest?: string;
    searches?: readonly SearchReceipt[];
    mutationDigest?: string;
}): BoundWriter;

catalogEditionIdentity function

function catalogEditionIdentity(input: {
    authority: string;
    catalogScope: string;
    publisherIdentity: string;
    sourcePublicationDigest: string;
    memberSetDigest: string;
}): string;

catalogMemberSetDigest function

function catalogMemberSetDigest(canonicalVersions: readonly string[]): string;

catalogSourceSetDigest function

function catalogSourceSetDigest(sources: readonly BillingCatalogSource[]): string;

evaluateBillingAccount function

Checks an existing Account and every ChargeItem the `account=Account/{id}` search returns, without a prospective charge. The Coverage and Contract are selected for each line's service date, or for `asOf` when the Account has no ChargeItems. The result carries resource-version evidence and search receipts but no writer preconditions.

function evaluateBillingAccount(given: EvaluateBillingAccountInput): Promise<BillingAccountResult>;

evaluateChargeRetirement function

Checks the Account after retiring one stored ChargeItem and directed companion loss in the stored target's original patient windows. The target contributes no post-removal facts or counts; its original context still selects dependency sources. A's supplied original authority and store-derived neighbor authority are covered, not unknown neighbor host selections. With complete directed evidence, an allow or rule block binds the exact own PUT, its target version and the combined resource/search/catalog evidence. A known block survives a later directed failure with its typed cause and an unavailable writer. Selection blocks and unavailable results never authorize a write. The existing host pre/post/conflict/compensation contract applies; no cross-Account atomic commit is supplied.

function evaluateChargeRetirement(given: EvaluateChargeRetirementInput): Promise<ChargeRetirementResult>;

evaluateCandidateCharges function

Checks each candidate ChargeItem against one Account as `evaluateProspectiveCharge` checks it alone: the Account's stored ChargeItems plus that candidate, never another candidate. The reads are shared across the candidates: each distinct FHIR read, search and page, and each distinct entitlement request, is sent once for the call, so the Schein, its editions and rule sets, the Contract's rule sets, the history and the facts are read once, and a further candidate adds only the reads its own codes and service dates need. A failure of a read that only one candidate needs is that candidate's `unavailable`; a failure of a shared read makes every candidate that needs it `unavailable` with the same reason. Only classified failures stay local to a candidate, as they become `unavailable` in `evaluateProspectiveCharge`: a `SnapshotFailure`, a `BillingInputError` or a canonical FHIR client failure. Any other error (for example a profile mapper throwing a plain `TypeError`) rejects the whole call, as it rejects the single call. Candidates are evaluated in order, through the reads of the first that needed them.

function evaluateCandidateCharges(input: EvaluateCandidateChargesInput): Promise<CandidateChargesResult>;

evaluateHypotheticalAccount function

Checks one hypothetical line set of an Account: its stored ChargeItems without the `withdrawnChargeItems`, plus every candidate, all evaluated together as one Schein. The result is what `evaluateBillingAccount` returns for that line set, with the same reasons, evidence and search receipts; every stored ChargeItem, a withdrawn one included, stays read evidence. It carries no writer preconditions: a hypothetical set never authorizes a write. With one candidate and nothing withdrawn it answers as `evaluateProspectiveCharge` without its writer; with neither, as `evaluateBillingAccount`.

function evaluateHypotheticalAccount(given: EvaluateHypotheticalAccountInput): Promise<BillingAccountResult>;

evaluateProspectiveCharge function

Checks one prospective ChargeItem on an Account together with the Account's stored ChargeItems. An `allow` or a rule `block` carries writer preconditions bound to every evaluated resource version, the search receipts and the prospective ChargeItem digest. Selection blocks and unavailable results carry a writer that never authorizes a write.

function evaluateProspectiveCharge(given: EvaluateProspectiveChargeInput): Promise<ProspectiveChargeResult>;

verifyCatalogMemberPrecondition function

Checks a catalog-member precondition (one with `canonical` and `digest` and no HTTP header) against the member as the writer re-read it immediately before persisting. Returns `ok` only when the re-read resource is the bound `Type/id`, still has the bound canonical `url|version`, and its content digest (canonical JSON without `text` and volatile `meta` fields) is unchanged. Any other precondition, an unreadable resource, or a difference returns `conflict`: the writer must not persist and must re-evaluate. The check is not store-enforced: the writer calls it again after its commit and, on `conflict`, marks the persisted result stale, re-evaluates and compensates it (README, "Writer contract for digest preconditions").

function verifyCatalogMemberPrecondition(precondition: WriterPrecondition, current: unknown): 'ok' | 'conflict';

verifyCatalogMemberVersion function

The pre-commit fast path for a catalog-member precondition: checks it against a meta-only read of the member (its `id`, `meta`, `url` and `version`, for example `GET /Library/<id>?_elements=id,meta,url,version`; a full read works too). With `phase` `pre-commit` it returns `ok` only when the precondition binds the member by canonical, digest and `lastUpdated`, and the read is the bound `Type/id`, still has the bound canonical `url|version`, states no `meta.versionId`, and states the same `meta.lastUpdated`: the store reports the content `digest` was taken from. Everything else returns `reread`: the writer reads the member in full and decides with verifyCatalogMemberPrecondition. With `phase` `post-commit` it always returns `reread`: the post-commit verification is binding as a full re-read and digest check with verifyCatalogMemberPrecondition, never this fast path. The fast path trusts the store's `meta.lastUpdated`, and a write that bypasses the FHIR API and keeps it is seen only by the digest check, so the post-commit digest check is what detects such a write and leads to the stale marking and compensation.

function verifyCatalogMemberVersion(precondition: WriterPrecondition, current: unknown, phase: CatalogMemberCheckPhase): 'ok' | 'reread';

BillingAccountResult type

Result of `evaluateBillingAccount`: a discriminated union on `decision`, without writer preconditions.

type BillingAccountResult = BillingAllowResult | BillingBlockResult | BillingUnavailableResult;

BillingAllowResult interface

interface BillingAllowResult extends BillingResultEvidence {
    readonly decision: 'allow';
    readonly reasons: readonly BillingDecisionReason<BillingAllowReasonCode>[];
    readonly selection: BillingSelectionRecord;
    readonly case: EngineCase;
    readonly ruleSet: EngineRuleSet;
    readonly admission: EngineAdmission;
    /** One verdict per requested overlay rule set, in request order; present only when the host requested overlays. */
    readonly overlays?: readonly BillingOverlayVerdict[];
}

BillingBlockResult type

type BillingBlockResult = BillingRuleBlockResult | BillingSelectionBlockResult;

BillingCatalogEditionSelection interface

interface BillingCatalogEditionSelection {
    readonly canonical: string;
    readonly version: string;
    readonly memberSetDigest: string;
}

BillingContractBoundEditionSelection interface

A line priced from a contract-bound catalog edition (ported from Billing Core 0.41.0, cognovis/fhir-billing-core#127; cognovis/chp#2048): `catalogEdition` is the edition's `canonical|version`, `contract` the edition's binding to the Applicable Contract as its `depends-on` link and manifest state it (`url` or `url|version`).

interface BillingContractBoundEditionSelection {
    readonly lineId: string;
    readonly catalogEdition: string;
    readonly contract: string;
}

BillingPriceAlternativeSelection type

How the guarded price alternatives of a line's catalog definition priced it (README, "Guarded price alternatives"; ADR-004). `definition` is the definition's `canonical|version`. `alternative` names the one matching alternative; `base` is the publisher base when none matched; `unknown` leaves the unit price unknown because a guard fact is unknown (`fact-unknown`, naming the first such `fact`) or because no alternative matched and the definition states no base (`no-alternative`). A line with an explicit price is listed too: it keeps its amount only when the outcome is `alternative` or `base` with a price that is not `unvalued`.

type BillingPriceAlternativeSelection = {
    readonly lineId: string;
    readonly definition: string;
    readonly priced: 'alternative';
    readonly alternative: string;
} | {
    readonly lineId: string;
    readonly definition: string;
    readonly priced: 'base';
} | {
    readonly lineId: string;
    readonly definition: string;
    readonly priced: 'unknown';
    readonly cause: 'fact-unknown';
    readonly fact: string;
} | {
    readonly lineId: string;
    readonly definition: string;
    readonly priced: 'unknown';
    readonly cause: 'no-alternative';
};

BillingLinePriceEditionSelection interface

One line whose unit price came from another catalog edition or definition than the one its rules were evaluated with: its service date falls outside the effective period of the edition selected at `asOf` (cognovis/chp#3387), or outside the effective period of that edition's definition of its coding (cognovis/chp#2048), so the edition and definition in force on `serviceDate` priced it. `catalogEdition` names that edition, `definition` the definition's `canonical|version`.

interface BillingLinePriceEditionSelection {
    readonly lineId: string;
    readonly serviceDate: string;
    readonly catalogEdition: BillingCatalogEditionSelection;
    readonly definition: string;
}

BillingContractRuleSetSelection interface

One contract rule-set Library read for the selected Contract: a native rule-set Library bound to one of the Contract's canonical identities. `contract` is the binding as the Library's `depends-on` link and the payload's `appliesTo` state it (`url` or `url|version`). `payloadDigest` is the digest the SDK computed; it is absent when the rule set was not decoded.

interface BillingContractRuleSetSelection {
    readonly canonical: string;
    readonly version: string;
    readonly payloadDigest?: string;
    readonly contract: string;
    readonly status: BillingContractRuleSetStatus;
    /**
     * Sorted ids of the rules of this rule set the engine skipped because their class is unsupported and
     * `mustUnderstand` is `false` (README, "Skipped rules"); present only on an evaluated rule set that has any.
     */
    readonly ignoredRuleIds?: readonly string[];
}

BillingContractRuleSetStatus type

What became of one contract rule-set Library bound to the selected Contract: `evaluated` against the Schein's lines, `unavailable` (it, or the rule set it is a version of, could not be used, or the evaluation stopped before it), or `ignored` (a version that is not active and in force beside the version in force that was evaluated).

type BillingContractRuleSetStatus = 'evaluated' | 'unavailable' | 'ignored';

BillingDecision type

type BillingDecision = 'allow' | 'block' | 'unavailable';

BillingDecisionReason interface

interface BillingDecisionReason<Code extends BillingResultReasonCode = BillingResultReasonCode> {
    readonly code: Code;
    readonly lineId?: string;
    readonly ruleId?: string;
    readonly sourceReferences?: readonly string[];
    readonly details?: Readonly<Record<string, string | number | boolean>>;
    /** The engine reason's resolution, carried unchanged. */
    readonly resolution?: BillingReasonResolution;
    /**
     * The effect that routed an engine reason: `reject` on a reason that blocks, `needs-review` on an
     * indeterminate reason, a rule configured with effect `needs-review`, or a withheld admission reason.
     * Present on every reason the engine produced for a rule `block` or an engine-decided `unavailable`;
     * absent on `ELIGIBLE`, `CATALOG_PARTIAL`, selection reasons and evaluation failures.
     */
    readonly effect?: BillingRuleEffect;
    /** The producing rule's provenance sources, carried unchanged; present only when the rule has provenance. */
    readonly sources?: readonly BillingRuleSource[];
    /** The producing rule's evidence level, carried unchanged; present only when the rule has provenance. */
    readonly evidenceLevel?: Coding;
    /**
     * Why an evaluation failure made the result, or a contract rule set's contribution, `unavailable`: a
     * key from `BILLING_UNAVAILABLE_MESSAGE_KEYS` and typed identifier parameters, never free text
     * from a resource or an error message. Present on every evaluation-failure reason (snapshot,
     * selection and prospective-charge failures, and contract rule-set failures); absent on engine reasons,
     * which name their rule by `ruleId`.
     */
    readonly explanation?: BillingUnavailableExplanation;
}

BillingEntitlementDecision interface

@deprecated Since 0.25.0 unused; see BillingEntitlementRequest.

interface BillingEntitlementDecision {
    readonly tenant: string;
    readonly artifactKind: BillingEntitlementRequest['artifactKind'];
    readonly canonical: string;
    readonly version: string;
    readonly digest: string;
    readonly sources: readonly BillingCatalogSource[];
    readonly decision: 'entitled' | 'not-entitled' | 'unknown';
    readonly authority: string;
    readonly evidenceReference: string;
}

BillingEntitlementPolicy interface

@deprecated Since 0.25.0 an operation refuses `policy` with `BillingInputError`; pass `tenant` and the `admission` profile descriptor instead (README, "Admission records").

interface BillingEntitlementPolicy {
    readonly tenant: string;
    resolveEntitlement(request: BillingEntitlementRequest): Promise<BillingEntitlementDecision>;
}

BillingEntitlementRequest interface

@deprecated Since 0.25.0 the SDK asks no entitlement policy and never builds a request: native carriers are admitted by the admission records in FHIR (README, "Admission records"). Kept so an import does not break.

interface BillingEntitlementRequest {
    readonly tenant: string;
    /**
     * The kind of the artifact to entitle. `configured-rule` is asked for each configured-rule Library an
     * edition without a rule-set member is evaluated with (README, "Editions with per-code configured
     * rules"); `digest` is then its configured-rule digest.
     */
    readonly artifactKind: 'catalog-edition' | 'rule-set' | 'configured-rule';
    readonly canonical: string;
    readonly version: string;
    readonly digest: string;
    readonly sources: readonly BillingCatalogSource[];
    /**
     * `Library.publisher` of a rule-set Library that names one; absent for a catalog edition and for a
     * rule-set Library without publisher. The publisher is carrier metadata outside the payload digest,
     * so only the policy attests it: a policy may bind admission to it, and need not echo it.
     */
    readonly publisher?: string;
}

BillingInstallationPolicyLocator interface

The `DocumentReference` holding the installation's EBM choice: its FHIR `id` and the `meta.source` its writer stamps.

interface BillingInstallationPolicyLocator {
    readonly id: string;
    readonly source: string;
}

BillingOverlayRequest interface

One overlay rule set the host requests: its canonical `url` or `url|version`, and its role.

interface BillingOverlayRequest {
    readonly ruleSet: string;
    readonly role?: BillingOverlayRole;
}

BillingOverlayRole type

How an overlay rule set takes part in the decision: `advisory` reports its verdict and never changes `decision`; `gate` makes `decision` `block` when it blocks, and `unavailable` when it cannot decide unless a fee schedule or contract rule set already blocks.

type BillingOverlayRole = 'advisory' | 'gate';

BillingOverlaySelection interface

One requested overlay rule set in the selection record: the request (`ruleSet`, `role`), the Library read (`canonical`, `version`; `version` is absent when none was read and the request named none) and the payload digest the SDK computed (absent when the Library was not decoded).

interface BillingOverlaySelection {
    readonly ruleSet: string;
    readonly role: BillingOverlayRole;
    readonly canonical: string;
    readonly version?: string;
    readonly payloadDigest?: string;
    readonly status: BillingOverlayStatus;
    /**
     * Sorted ids of the rules of this rule set the engine skipped because their class is unsupported and
     * `mustUnderstand` is `false` (README, "Skipped rules"); present only on an evaluated rule set that has any.
     */
    readonly ignoredRuleIds?: readonly string[];
}

BillingOverlayStatus type

What became of one requested overlay rule set: `evaluated` on the lines of the editions it applies to, or `unavailable` (it could not be read, bound, decoded or entitled, failed while it was evaluated, or the evaluation stopped before it).

type BillingOverlayStatus = 'evaluated' | 'unavailable';

BillingOverlayVerdict interface

The verdict of one requested overlay rule set, in request order. `ruleSet` is the request as given; `canonical` and `version` name the Library read (`version` is absent when none was read and the request named none), `digest` is the payload digest the SDK computed (absent when the Library was not decoded) and `publisher` the Library's publisher, carrier metadata its admission record attests. `reasons` are the overlay's own: its engine reasons for `block` and engine-decided `unavailable` (with `ruleId`, `sources` and `evidenceLevel`), `ELIGIBLE` for `allow`, or the typed failure that made it `unavailable`, each `unavailable` reason with its `explanation`.

interface BillingOverlayVerdict {
    readonly ruleSet: string;
    readonly role: BillingOverlayRole;
    readonly decision: BillingDecision;
    readonly reasons: readonly BillingDecisionReason<BillingRuleBlockReasonCode>[];
    readonly canonical: string;
    readonly version?: string;
    readonly digest?: string;
    readonly publisher?: string;
}

BillingPartialSelectionRecord interface

The parts of the selection record resolved before an `unavailable` result. When a failure stops the evaluation before the engine runs, `catalogEdition` and `ruleSet` are set only when one catalog edition is used, and `catalogEditions` and `ruleSets` list every edition and rule set resolved before the failure. An `unavailable` decided by the engine carries the complete record, as in BillingSelectionRecord.

interface BillingPartialSelectionRecord {
    readonly account?: BillingResourceVersion;
    readonly serviceDates?: readonly string[];
    readonly coverage?: BillingResourceVersion;
    readonly contract?: BillingContractSelection;
    readonly catalogEdition?: BillingCatalogEditionSelection;
    readonly ruleSet?: BillingRuleSetSelection;
    readonly catalogEditions?: readonly BillingCatalogEditionSelection[];
    /** Present on an engine-decided `unavailable` when a contract-bound edition priced a line, as in {@link BillingSelectionRecord}. */
    readonly contractBoundEditions?: readonly BillingContractBoundEditionSelection[];
    /** Present on an engine-decided `unavailable` when an alternatives definition priced a line, as in {@link BillingSelectionRecord}. */
    readonly priceAlternatives?: readonly BillingPriceAlternativeSelection[];
    /** Present on an engine-decided `unavailable` when a line was priced from its own date's edition, as in {@link BillingSelectionRecord}. */
    readonly linePriceEditions?: readonly BillingLinePriceEditionSelection[];
    readonly ruleSets?: readonly BillingRuleSetSelection[];
    readonly contractRuleSets?: readonly BillingContractRuleSetSelection[];
    /** Every requested overlay rule set resolved before the failure, in request order. */
    readonly overlays?: readonly BillingOverlaySelection[];
    readonly rejectedCoverages: readonly BillingRejectedCandidate[];
    readonly rejectedContracts: readonly BillingRejectedCandidate[];
}

BillingResourceEvidence type

Evidence of one evaluated resource. `evidence.versionId !== undefined` narrows to ResourceVersionEvidence, `evidence.digest !== undefined` to CanonicalDigestEvidence.

type BillingResourceEvidence = ResourceVersionEvidence | CanonicalDigestEvidence;

BillingRuleBlockResult interface

interface BillingRuleBlockResult extends BillingResultEvidence {
    readonly decision: 'block';
    readonly blockedBy: 'rule';
    readonly reasons: readonly BillingDecisionReason<BillingRuleBlockReasonCode>[];
    readonly selection: BillingSelectionRecord;
    readonly case: EngineCase;
    readonly ruleSet: EngineRuleSet;
    readonly admission: EngineAdmission;
    readonly overlays?: readonly BillingOverlayVerdict[];
}

BillingRuleSetSelection interface

interface BillingRuleSetSelection {
    readonly canonical: string;
    readonly version: string;
    readonly payloadDigest: string;
    /**
     * Present only when the edition's rules came from its configured-rule members (README, "Editions with
     * per-code configured rules"): every configured-rule Library used, by `canonical`, `version` and its
     * configured-rule digest as `payloadDigest`, ordered by `canonical|version`. The entry itself then names
     * the edition's canonical with the fragment `#configured-rules`, its version, and the payload digest of
     * the rule set merged from those Libraries.
     */
    readonly configuredRules?: readonly BillingRuleSetSelection[];
    /**
     * Sorted ids of the rules of this rule set the engine skipped because their class is unsupported and
     * `mustUnderstand` is `false` (README, "Skipped rules"); present only on an evaluated rule set that has any.
     */
    readonly ignoredRuleIds?: readonly string[];
}

BillingSelectionBlockRecord interface

The selection record of a selection `block`, up to the blocking step. It names no Contract, catalog edition or rule set.

interface BillingSelectionBlockRecord {
    readonly account: BillingResourceVersion;
    readonly serviceDates: readonly string[];
    readonly blockedAt: 'coverage' | 'contract';
    /** The Coverage every service date selected, when the Contract step blocked. */
    readonly coverage?: BillingResourceVersion;
    readonly rejectedCoverages: readonly BillingRejectedCandidate[];
    readonly rejectedContracts: readonly BillingRejectedCandidate[];
}

BillingSelectionBlockResult interface

interface BillingSelectionBlockResult extends BillingResultEvidence {
    readonly decision: 'block';
    readonly blockedBy: 'selection';
    readonly reasons: readonly BillingDecisionReason<BillingSelectionBlockCode>[];
    readonly selection: BillingSelectionBlockRecord;
    readonly case?: never;
    readonly ruleSet?: never;
    readonly admission?: never;
    readonly overlays?: never;
}

BillingSelectionRecord interface

The complete selection record of an `allow` or a rule `block`. `catalogEditions` and `ruleSets` list every catalog edition used and its rule set, index by index, in the order the Account's lines first bill them. With one edition, `catalogEdition` and `ruleSet` are that edition and rule set. With several (see `EvaluateBillingAccountInput.catalog`), they name the decisive edition: the prospective charge's edition (or a hypothetical line set's single candidate's), or otherwise the first edition whose own decision is the result's decision.

interface BillingSelectionRecord {
    readonly account: BillingResourceVersion;
    readonly serviceDates: readonly string[];
    readonly coverage: BillingResourceVersion;
    readonly contract: BillingContractSelection;
    readonly catalogEdition: BillingCatalogEditionSelection;
    readonly ruleSet: BillingRuleSetSelection;
    readonly catalogEditions: readonly BillingCatalogEditionSelection[];
    /**
     * Every line a contract-bound catalog edition evaluates and prices, in billing order, with that edition
     * and its Contract binding; present only when one does.
     */
    readonly contractBoundEditions?: readonly BillingContractBoundEditionSelection[];
    /** The price-alternative outcome of every line an alternatives definition priced; present only when one did. */
    readonly priceAlternatives?: readonly BillingPriceAlternativeSelection[];
    /**
     * Every line priced from the edition in force on its own service date instead of the edition its rules
     * were evaluated with at `asOf`, in line order; present only when there is one.
     */
    readonly linePriceEditions?: readonly BillingLinePriceEditionSelection[];
    readonly ruleSets: readonly BillingRuleSetSelection[];
    /**
     * Every contract rule-set Library bound to the selected Contract that was read, in the order the
     * Contract identities and the searches returned them; present only when the Contract has one.
     */
    readonly contractRuleSets?: readonly BillingContractRuleSetSelection[];
    /**
     * The contract rule set that decides the result when no catalog edition's rule set reaches the
     * result's decision (for example a contract rule set blocks a code every edition allows): the first
     * contract rule set whose own decision is the result's. `catalogEdition` and `ruleSet` then still name
     * the first edition. Absent when an edition's rule set reaches the result's decision.
     */
    readonly decisiveContractRuleSet?: BillingContractRuleSetSelection;
    /** Every requested overlay rule set, in request order; present only when the host requested overlays. */
    readonly overlays?: readonly BillingOverlaySelection[];
    /**
     * The gate overlay that decides the result when neither an edition's rule set nor a contract rule set
     * reaches the result's decision: the first gate overlay whose own verdict is the result's.
     */
    readonly decisiveOverlay?: BillingOverlaySelection;
    readonly rejectedCoverages: readonly BillingRejectedCandidate[];
    readonly rejectedContracts: readonly BillingRejectedCandidate[];
}

BillingSnapshot interface

interface BillingSnapshot {
    readonly asOf: string;
    readonly resources: readonly Record<string, unknown>[];
    readonly evidence: readonly BillingResourceEvidence[];
    readonly artifacts?: DeclarativeArtifactLocators;
}

BillingSnapshotProfiles interface

interface BillingSnapshotProfiles {
    readonly account: BillingProfileDescriptor;
    readonly chargeItem: BillingProfileDescriptor;
    readonly coverage: BillingProfileDescriptor;
    readonly contract: BillingProfileDescriptor;
    readonly observation: BillingProfileDescriptor;
    readonly catalogEdition: BillingProfileDescriptor;
    readonly ruleSet: BillingProfileDescriptor;
    readonly catalogDefinition: BillingProfileDescriptor;
    /**
     * The descriptors of the resources native and declared facts come from (README, "Facts the SDK
     * reads"). Each is optional: the SDK reads such a resource only when a rule names a fact from it,
     * and without its descriptor that fact is `source-unavailable`, so the rule returns `unavailable`.
     */
    readonly patient?: BillingProfileDescriptor;
    readonly encounter?: BillingProfileDescriptor;
    readonly condition?: BillingProfileDescriptor;
    readonly practitioner?: BillingProfileDescriptor;
    readonly practitionerRole?: BillingProfileDescriptor;
    /**
     * The descriptor of the site memberships (`OrganizationAffiliation`) the Behandlungsfall window
     * reads (README, "Counting windows"). Without it every line's practice is unknown, so a rule of that
     * window returns `unavailable` with `COUNTING_SCOPE_UNAVAILABLE`.
     */
    readonly organizationAffiliation?: BillingProfileDescriptor;
    /**
     * The descriptor of the admission records (`Provenance`, README, "Admission records"). A native
     * carrier is admitted only through an admission record read through it, so without it every native
     * carrier fails closed with `SNAPSHOT_UNAUTHORIZED`.
     */
    readonly admission?: BillingProfileDescriptor;
    /**
     * The descriptor of the installation's EBM choice (`DocumentReference`, README, "Installation EBM
     * choice"), the policy the call's `installationPolicy` names. A native EBM catalog edition is evaluated
     * only when that choice admits it for the tenant, so without the descriptor every native EBM edition
     * fails closed with `SNAPSHOT_UNAUTHORIZED` (`installation-policy-unavailable`). Other editions never
     * read it.
     */
    readonly installationPolicy?: BillingProfileDescriptor;
}

BillingUnavailableResult interface

interface BillingUnavailableResult extends BillingResultEvidence {
    readonly decision: 'unavailable';
    readonly reasons: readonly BillingDecisionReason<BillingUnavailableReasonCode>[];
    readonly selection: BillingPartialSelectionRecord;
    readonly case?: EngineCase;
    readonly ruleSet?: EngineRuleSet;
    readonly admission?: EngineAdmission;
    /**
     * One verdict per requested overlay rule set when the evaluation reached the rule sets (an
     * engine-decided `unavailable`); absent when a failure stopped it before, where
     * `selection.overlays` and the evidence still name every overlay read.
     */
    readonly overlays?: readonly BillingOverlayVerdict[];
}

CatalogMemberCheckPhase type

When a writer checks its catalog-member preconditions: immediately before it persists (`pre-commit`) or after its commit (`post-commit`, README, "Writer contract for digest preconditions", step 4).

type CatalogMemberCheckPhase = 'pre-commit' | 'post-commit';

BoundWriter interface

interface BoundWriter {
    readonly preconditions: readonly WriterPrecondition[];
    readonly token: string;
    readonly identityDigest: string;
    readonly searches: readonly SearchReceipt[];
    readonly mutationDigest: string;
}

CandidateChargesResult interface

Result of `evaluateCandidateCharges`. `results` holds, index by index, exactly what `evaluateProspectiveCharge` returns for the Account and that one candidate, writer preconditions with the candidate's own mutation precondition included. `evidence` and `searches` are the union of every candidate's `snapshot.evidence` and `searches`, each item once, in the order first met.

interface CandidateChargesResult {
    readonly results: readonly ProspectiveChargeResult[];
    readonly evidence: readonly BillingResourceEvidence[];
    readonly searches: readonly SearchReceipt[];
}

ChargeRetirementResult type

The resulting Account decision, with writer preconditions for the exact retirement PUT.

type ChargeRetirementResult = BillingAccountResult & {
    readonly writer: BoundWriter;
};

CanonicalDigestEvidence interface

Evidence of a catalog member the store serves without `meta.versionId`, as Aidbox does for canonical resources held in its package registry. Catalog members are catalog-edition, rule-set and configured-rule Libraries and the edition's ChargeItemDefinitions. The member is bound to its canonical `url|version` and to `digest`, the `sha256:<hex>` of the canonical JSON of the resource without `text` and without the volatile store fields of `meta` (`versionId`, `lastUpdated`, `source`, `extension`); `meta.profile` (sorted) and every other `meta` field stay covered. A member that does carry `meta.versionId` keeps ResourceVersionEvidence.

interface CanonicalDigestEvidence {
    readonly resourceType: string;
    readonly id: string;
    /** The member's canonical `url|version`. */
    readonly canonical: string;
    /** `sha256:<hex>` over the canonical JSON of the resource without `text` and volatile `meta` fields. */
    readonly digest: string;
    /**
     * The store's `meta.lastUpdated` of the content `digest` was taken from, when the store stated one: the
     * version a writer compares with a meta-only read ({@link verifyCatalogMemberVersion}).
     */
    readonly lastUpdated?: string;
    readonly sourceReference: string;
    readonly versionId?: never;
}

DeclarativeArtifactLocators interface

interface DeclarativeArtifactLocators {
    readonly profiles?: readonly string[];
}

EvaluateBillingAccountInput interface

Inputs shared by both operations. The host may select the catalog edition and the rule set; when it does not, the SDK derives them from the billed codings and the selected edition's members.

interface EvaluateBillingAccountInput {
    client: BillingFhirClient;
    profiles: BillingSnapshotProfiles;
    /** Admission date for catalog editions and rule sets, and the service date of an Account without ChargeItems. */
    asOf: string;
    account: Record<string, unknown> | string;
    /**
     * Rule-set Library id, `Library/{id}`, canonical url, or `url|version`; it must be a member of the
     * selected catalog edition. When omitted, the edition's single member Library with artifact-kind
     * `rule-set` is used: none yields `SNAPSHOT_MISSING`, more than one `SNAPSHOT_AMBIGUOUS`. When the
     * lines need several catalog editions, an explicit `ruleSet` yields `SNAPSHOT_AMBIGUOUS`, because
     * one selector cannot name each edition's rule set.
     */
    ruleSet?: string;
    /**
     * Library edition id, `Library/{id}`, canonical url, or `url|version`. A ChargeItemDefinition id or url does not select an edition.
     * An explicit `catalog` always selects exactly one edition. When omitted and several editions are in
     * force, the SDK keeps the editions whose members contain a ChargeItemDefinition for every billed
     * coding of the Account and the prospective charge: exactly one is selected, more than one yields
     * `SNAPSHOT_AMBIGUOUS`. When none covers every coding, each line is evaluated in the single in-force
     * edition that contains its coding (none yields `SNAPSHOT_MISSING`, several `SNAPSHOT_AMBIGUOUS`),
     * with that edition's own rule set and admission. The decisions combine: any `block` is `block`,
     * else any `unavailable` is `unavailable`, else `allow`.
     */
    catalog?: string;
    artifacts?: DeclarativeArtifactLocators;
    /**
     * The tenant whose admission records admit native carriers (README, "Admission records"): a native
     * catalog edition, rule set or configured rule is evaluated only when an admission record of this
     * tenant in FHIR binds it. A non-empty string; without it every native carrier fails closed with
     * `SNAPSHOT_UNAUTHORIZED`. Legacy carriers (admission extensions) are read only without it.
     */
    tenant?: string;
    /**
     * The installation's EBM choice (README, "Installation EBM choice"): the id of the `DocumentReference`
     * holding it, read through `profiles.installationPolicy`, and the `meta.source` its writer stamps. A
     * policy with another source is foreign and refuses every native EBM edition. Without it every native
     * EBM edition fails closed with `SNAPSHOT_UNAUTHORIZED` (`installation-policy-unavailable`).
     */
    installationPolicy?: BillingInstallationPolicyLocator;
    /**
     * @deprecated Removed in 0.25.0: the SDK asks no entitlement policy. Any value other than `undefined`
     * is refused with `BillingInputError`; pass `tenant` instead.
     */
    policy?: never;
    /** @deprecated Removed in 0.25.0 with `policy`. Any value other than `undefined` is refused with `BillingInputError`. */
    entitlementConcurrency?: never;
    /**
     * An opt-in, host-held cache of verified catalog artifacts ({@link createBillingArtifactCache}, README,
     * "Artifact cache"). It holds only admitted, digest-verified catalog content (never Account-side
     * data); a hit returns exactly that content with the evidence and receipts recorded when it was
     * verified. Without it every call reads and verifies everything.
     */
    artifactCache?: BillingArtifactCache;
    /**
     * The FHIR base URL of the server `client` reads, for example `https://fhir.example/fhir`. It lets
     * the SDK assign a history line's absolute `{base}/Account/{id}` reference to an Account of this
     * server. Without it, every absolute Account reference is one the SDK cannot assign.
     */
    fhirBaseUrl?: string;
    /**
     * Which `OrganizationAffiliation` codes state that a site belongs to a practice, for the
     * `quarter`/`patient-per-practice-and-insurer` window (README, "Counting windows"). The country
     * profile defines them; Core names none. Without it every line's practice is unknown, so a rule
     * of that window returns `unavailable` with `COUNTING_SCOPE_UNAVAILABLE`.
     */
    practiceMembership?: BillingPracticeMembership;
    /**
     * Which `Practitioner.identifier` systems carry a physician's number, for the
     * `quarter`/`patient-per-physician-number-and-insurer` window (Arztfall, README, "Counting windows").
     * The country profile defines them; Core names none. Without it every line's physician number is
     * unknown, so a rule of that window returns `unavailable` with `COUNTING_SCOPE_UNAVAILABLE`.
     */
    physicianNumber?: BillingPhysicianNumber;
    /**
     * Which `PractitionerRole.specialty` code system names a physician's group, for the
     * `quarter`/`patient-per-practice-physician-group-and-insurer` window (Arztgruppenfall, README,
     * "Counting windows"). The country profile defines it; Core names none. Without it every line's
     * physician group is unknown, so a rule of that window returns `unavailable` with `COUNTING_SCOPE_UNAVAILABLE`.
     */
    physicianGroup?: BillingPhysicianGroup;
    /**
     * Overlay rule sets the host requests beside the fee schedule's rule sets (README, "Overlay rule
     * sets"): native rule-set Libraries a third party maintains, each bound to the catalog edition(s) it
     * applies to. Each is read by its canonical (`url` or `url|version`), checked against the editions
     * selected for the Schein's lines, admitted by an admission record of `tenant`, and evaluated on the lines of the
     * editions it applies to. Its verdict is reported in the result's `overlays`; `role` (default
     * `advisory`) decides whether it can change the result's decision.
     */
    overlays?: readonly BillingOverlayRequest[];
    /**
     * The host's source of `patient.age` and `patient.gender` (README, "Facts the SDK reads"). With it the
     * SDK reads no Patient: a host whose client may not read Patient, such as a background service client,
     * supplies birth date and gender from a source it may read. A declared fact source `from: 'patient'`
     * is then `source-unavailable`, and the supplied facts are neither evidence nor a writer precondition.
     * Without it the SDK reads the Patient through `profiles.patient` as before.
     */
    patientFacts?: BillingPatientFactsReader;
}

EvaluateCandidateChargesInput interface

interface EvaluateCandidateChargesInput extends EvaluateBillingAccountInput {
    /**
     * The ChargeItems to check, each on its own: every candidate is evaluated as the only addition to the
     * Account's stored ChargeItems, never together with another candidate. Each must meet the
     * requirements of `EvaluateProspectiveChargeInput.prospectiveCharge`; one that does not is that
     * candidate's `unavailable`.
     */
    candidates: readonly Record<string, unknown>[];
}

EvaluateChargeRetirementInput interface

interface EvaluateChargeRetirementInput extends EvaluateBillingAccountInput {
    /**
     * The exact ChargeItem PUT that retires a stored line: its id and status `entered-in-error`, with
     * all other resource content unchanged. `meta.profile`, `meta.versionId` and `meta.lastUpdated`
     * may differ. When target validation is reached, a supplied versionId must match the stored target,
     * and the target must belong only to this Account and its Patient. Earlier selection blocks and
     * unavailable outcomes keep their precedence. Metadata stays covered by the exact mutation digest.
     */
    retiredCharge: Record<string, unknown>;
}

EvaluateHypotheticalAccountInput interface

interface EvaluateHypotheticalAccountInput extends EvaluateBillingAccountInput {
    /**
     * The ChargeItems the host proposes to add, all evaluated together with the Account's remaining stored
     * ChargeItems. Each must meet the requirements of `EvaluateProspectiveChargeInput.prospectiveCharge`
     * and carry an `id` no other candidate carries; a candidate with the id of a stored ChargeItem takes
     * that line's place. A candidate that fails a requirement makes the result `unavailable`.
     */
    candidates: readonly Record<string, unknown>[];
    /**
     * Ids of stored ChargeItems of the Account to treat as absent. An id that is not a stored ChargeItem
     * of the Account makes the result `unavailable`.
     */
    withdrawnChargeItems?: readonly string[];
}

EvaluateProspectiveChargeInput interface

interface EvaluateProspectiveChargeInput extends EvaluateBillingAccountInput {
    /**
     * The ChargeItem the host intends to write. It must reference the evaluated Account in
     * `ChargeItem.account`, carry a safe-integer quantity of at least 1, and a service date.
     */
    prospectiveCharge: Record<string, unknown>;
}

ProspectiveChargeResult type

Result of `evaluateProspectiveCharge`: the same union, each variant with writer preconditions.

type ProspectiveChargeResult = BillingAccountResult & {
    readonly writer: BoundWriter;
};

ResourceVersionEvidence interface

Evidence of a resource the store versions: its `meta.versionId`. Every runtime resource carries it.

interface ResourceVersionEvidence {
    readonly resourceType: string;
    readonly id: string;
    readonly versionId: string;
    readonly sourceReference: string;
    readonly canonical?: never;
    readonly digest?: never;
    readonly lastUpdated?: never;
}

SearchReceipt interface

interface SearchReceipt {
    readonly resourceType: string;
    readonly query: Readonly<Record<string, string | string[]>>;
    readonly identities: readonly string[];
    readonly count: number;
}

WriterPrecondition interface

One condition a writer must hold before it persists. A precondition with `ifMatch` or `ifNoneMatch` is sent as that HTTP header. A precondition with `canonical` and `digest` but neither header binds a catalog member without `meta.versionId`: the writer re-reads the member and checks it with verifyCatalogMemberPrecondition; a conflict means the evaluation is stale.

interface WriterPrecondition {
    readonly path: string;
    readonly ifMatch?: string;
    readonly ifNoneMatch?: string;
    readonly versionId?: string;
    /** The canonical `url|version` of a catalog member bound by digest. */
    readonly canonical?: string;
    readonly digest?: string;
    /**
     * The store's `meta.lastUpdated` of the catalog member bound by digest, when the store stated one. A
     * meta-only read that reports it unchanged proves the member unchanged ({@link verifyCatalogMemberVersion}).
     */
    readonly lastUpdated?: string;
}

WriterSnapshot interface

interface WriterSnapshot {
    readonly identities: readonly string[];
    readonly searches: readonly SearchReceipt[];
    readonly mutationDigest: string;
}

BillingFhirClient type

type BillingFhirClient = Pick<FhirClient, 'forProfile'>;

BillingProfileDescriptor type

type BillingProfileDescriptor = ProfileDescriptor<FhirResource, unknown>;

BillingPatientFacts interface

The Patient facts a host supplies instead of a Patient read (cognovis/chp#2029): `birthDate` as FHIR states it (`YYYY`, `YYYY-MM` or `YYYY-MM-DD`) and `gender` as the `Patient.gender` code. An absent member is a fact the host has no value for.

interface BillingPatientFacts {
    readonly birthDate?: string;
    readonly gender?: string;
}

BillingPatientFactsReader type

Supplies the facts of one Patient, named by its literal reference `Patient/<id>`, from a source the host is allowed to read, such as a stored query. `undefined` means the host has no such Patient. The SDK then reads no Patient: `patient.age` and `patient.gender` come from the supplied facts, a declared fact source `from: 'patient'` is `source-unavailable`, and the supplied facts are neither evidence nor a writer precondition. A rejection fails the evaluation like a failed read.

type BillingPatientFactsReader = (patient: string) => Promise<BillingPatientFacts | undefined>;

BillingPhysicianGroup interface

The code system of a physician's group for the Arztgruppenfall (BMV-Ä §21 para. 1c), read from `PractitionerRole.specialty` of the physician's roles at the line's site; Core names none.

interface BillingPhysicianGroup {
    readonly system: string;
}

BillingPhysicianNumber interface

The identifier systems of a physician's number for the Arztfall (BMV-Ä §21 para. 1b), as the country profile defines them; Core names none. Every value in these systems names the same number, so two different values leave the number unknown.

interface BillingPhysicianNumber {
    readonly systems: readonly string[];
}

BillingPracticeMembership interface

The `OrganizationAffiliation` codes, in one code system the country profile defines, that state a site's membership in a practice. `codes` name a practice membership: the affiliation's `organization` is the site's practice for its period. `otherCodes` name relationships of the same system that are no practice membership and are ignored. Any other code of the system is unknown.

interface BillingPracticeMembership {
    readonly system: string;
    readonly codes: readonly string[];
    readonly otherCodes?: readonly string[];
}

warmBillingArtifactCache function

Fills an artifact cache before the first booking (README, "Artifact cache"), through the code an evaluation runs cold, so a later evaluation's decision, reasons, receipts and evidence equal a cold evaluation's. It discovers the native catalog editions in force on `asOf` as an evaluation does; for each, it reads the tenant's admission record (an edition without one is skipped and nothing of it is cached), the admitted configured-rule shards and the full edition; then, for every definition the edition declares configured rules for (those of `priorityCodings` first), it runs the definition's configured-rule search, the members-digest check and the resolution and decoding of each member, and caches what an evaluation caches once every member is admitted with its digest. A definition that fails is counted by its failure code and the warm-up goes on; it yields to the event loop between definitions, stops at `signal`, and stops (without evicting what it entered) where the cache's `maxEntries` or `maxRules` would be exceeded. Input that is not usable throws `BillingInputError`.

function warmBillingArtifactCache(input: WarmBillingArtifactCacheInput): Promise<BillingArtifactCacheWarmup>;

BillingArtifactCacheWarmup interface

What a warm-up did.

interface BillingArtifactCacheWarmup {
    readonly editions: readonly BillingArtifactCacheWarmupEdition[];
    readonly definitionsTotal: number;
    /** Definitions whose configured rules the cache now holds (also those it held already). */
    readonly definitionsWarmed: number;
    /** Configured rules this warm-up entered into the cache. */
    readonly rulesCached: number;
    /** Definitions (and editions) that could not be warmed, by failure code. */
    readonly failures: Readonly<Record<string, number>>;
    readonly elapsedMs: number;
    /** The cache bound that stopped the warm-up, when one did. */
    readonly stoppedAt?: 'maxConfiguredRules' | 'maxEntries' | 'maxRules';
    /** With `onlyPriorityCodings`, the priority codings no warmed edition has a catalog definition for. */
    readonly priorityCodingsWithoutDefinition: number;
    readonly aborted: boolean;
}

BillingArtifactCacheWarmupEdition interface

One native edition a warm-up found in force.

interface BillingArtifactCacheWarmupEdition {
    readonly canonical: string;
    readonly version: string;
    /** `warmed`: admitted and its definitions warmed; `not-admitted`: no admission record of the tenant (nothing cached); `failed`: it could not be read or checked. */
    readonly status: 'warmed' | 'not-admitted' | 'failed';
    /** The failure code when `status` is not `warmed`. */
    readonly reason?: string;
    /** The definitions with configured rules the edition declares. */
    readonly definitions: number;
    /**
     * For a `not-admitted` edition in force beside an admitted one: its full content was read and checked
     * and is cached as the selection candidate an evaluation reads it as (to decide which edition holds the
     * billed codes), never its shards or rules.
     */
    readonly selectionCandidate?: boolean;
}

WarmBillingArtifactCacheInput interface

What warmBillingArtifactCache reads and fills.

interface WarmBillingArtifactCacheInput {
    readonly client: BillingFhirClient;
    readonly profiles: BillingSnapshotProfiles;
    /** The tenant whose admission records admit the editions warmed; an edition it has none for is skipped. */
    readonly tenant: string;
    /** The date the editions must be in force on, `YYYY-MM-DD`, as an evaluation's `asOf`. */
    readonly asOf: string;
    /** The store the cache serves, as an evaluation passes it. */
    readonly fhirBaseUrl: string;
    readonly artifactCache: BillingArtifactCache;
    /** Billed codings whose catalog definitions are warmed first, in this order. */
    readonly priorityCodings?: readonly {
        readonly system: string;
        readonly code: string;
    }[];
    /** Warm only the definitions of `priorityCodings` (and the editions' shards and full content). */
    readonly onlyPriorityCodings?: boolean;
    /** Definitions warmed at once, an integer from 1 to 16; default 4. */
    readonly concurrency?: number;
    /** Stops the warm-up between definitions; the summary then says `aborted`. */
    readonly signal?: AbortSignal;
    /** Called after each definition with what is done so far; an error it throws is ignored. */
    readonly onProgress?: (progress: {
        readonly definitionsDone: number;
        readonly definitionsTotal: number;
        readonly rulesCached: number;
    }) => void;
}

createBillingArtifactCache function

Creates an empty artifact cache for the store `store` names. A `store` that is not a non-empty string, or `maxEntries` or `maxRules` that is not a positive safe integer, throws `BillingInputError`.

function createBillingArtifactCache(options: BillingArtifactCacheOptions): BillingArtifactCache;

BillingArtifactCache interface

A host-held cache of verified catalog artifacts for `evaluateBillingAccount`, `evaluateProspectiveCharge` and `evaluateCandidateCharges` (input `artifactCache`). Entries are content-addressed (README, "Artifact cache"), bounded, and hold no Account-side data. Share one per process; `clear()` empties it, and `forget()` invalidates changed searches and Library copies while retaining other memory entries.

interface BillingArtifactCache {
    /** The FHIR base URL of the store the cache serves, as normalized (no trailing slash). */
    readonly store: string;
    /** The number of entries it holds. */
    readonly size: number;
    /** Drops every entry, so the next evaluation reads and verifies everything again. */
    clear(): void;
    /**
     * Drops definitions matching a changed search's resource type and query, their merged rule sets,
     * and full resource copies of changed Library references. See README, "Artifact cache", for reference
     * forms. Older evaluations cannot refill this cache generation.
     */
    forget(receipts: readonly BillingArtifactCacheReceipt[]): void;
}

BillingArtifactCacheOptions interface

interface BillingArtifactCacheOptions {
    /**
     * The FHIR base URL of the one store the cache serves, for example `https://fhir.example/fhir`
     * (trailing slashes are ignored). Required: everything the cache holds was read from this store, so a
     * call that passes the cache must name the same store as its `fhirBaseUrl`, else it is refused with
     * `BillingInputError`. Keep one cache per store.
     */
    readonly store: string;
    /**
     * The most configured rules the cache keeps, the entries that take most of its memory (README, "Memory
     * and bounds"); when one more is entered, the least recently used goes. A definition one of whose rules
     * went is read again as without a cache, so results do not change. A warm-up stops here instead.
     * A positive safe integer, default 10,000.
     */
    readonly maxConfiguredRules?: number;
    /**
     * The most other entries the cache keeps (one per definition, shard, shard union, merged rule set and
     * catalog edition); the least recently used go first. A positive safe integer, default 250,000.
     */
    readonly maxEntries?: number;
    /**
     * The most rules and catalog members those other entries hold together (a shard and a merged rule set
     * count their rules, a catalog edition its members, every other entry one); the least recently used
     * entries go first. A positive safe integer, default 400,000.
     */
    readonly maxRules?: number;
    /**
     * How long, in milliseconds, the native catalog editions a discovery search found are reused while the
     * store's admission records are unchanged (README, "Artifact cache"); an older result is searched again.
     * It bounds how long a write to an edition that changes no admission record goes unnoticed. A positive
     * safe integer, default 300,000 (5 minutes).
     */
    readonly editionDiscoveryMaxAgeMs?: number;
}

BillingArtifactCacheReceipt type

A changed search (matched by resource type and query) or catalog member reference.

type BillingArtifactCacheReceipt = CachedSearch | string;

bundleAdmissionRecords function

function bundleAdmissionRecords(bundles: readonly unknown[], options: BundleAdmissionOptions): Record<string, unknown>[];

createBundleFhirClient function

A canonical, read-only FHIR client (`createFhirClient` of `@cognovis/fhir-sdk/client`) over the resources of the given FHIR Bundles (`collection`, `transaction`, `batch` or `searchset`; each entry's `resource`). It serves reads by `Type/id` and exactly the searches the Billing SDK issues: Account by `patient` (retirement neighbor discovery), ChargeItem by `account` and by `patient`, `occurrence` and `status` (the counting-window history), Library by `url`, `version`, `identifier` and `depends-on` (a canonical, or `canonical|version`, against `depends-on` related artifacts: the contract rule-set search), ChargeItemDefinition by `url`, `version`, `identifier` and `code`, PractitionerRole by `practitioner`, `organization` and `identifier` (the role search of a Practitioner performer, cognovis/fhir-billing-core#134, by workforce source key since cognovis/chp#2741), Practitioner by `identifier` (the holder of a workforce source key), `identifier` also as a comma OR list of tokens, and `_profile`, `_total=accurate`, a positive `_count` and `_elements` (only the listed elements, with `resourceType`, `id` and `meta`) on every type, each answered in one page with an exact total (`_count` is a page-size request, never a filter). Any other search parameter, a value list (comma) on another parameter than `status` and `identifier`, or an escaped value fails the search with HTTP 400, never ignoring a filter. Every write (create, update, patch, delete, batch, transaction) fails and changes nothing. It never opens a network connection. It never answers less than a FHIR server holding the same resources: what it cannot represent fails the load with `BillingInputError`. The references the SDK follows are resolved to `Type/id` (see readBundles), and an unresolvable `ChargeItem.account`, `ChargeItem.supportingInformation`, `Account.coverage.coverage` or `Coverage.contract` fails the load. A transaction or batch entry must be `PUT Type/id` of its resource or `POST Type`; a searchset must be complete (no `next` link, no stated total above its matches), and its `outcome` entries are skipped. A resource that occurs in several entries must be identical in each, and `entry` must be an array. A runtime resource without `meta.versionId` is served with versionId `bundle-<16 hex digits>` (see storedForm); a stated versionId is kept. Catalog members (Library, ChargeItemDefinition) are served as supplied.

function createBundleFhirClient(bundles: readonly unknown[]): FhirClient;

BundleAdmissionOptions interface

interface BundleAdmissionOptions {
    /** The tenant the records admit for. */
    readonly tenant: string;
}

BundleEntitlementPolicyOptions interface

@deprecated Since 0.25.0 a type only: the bundle entitlement policy it configured is removed, an operation refuses `policy`; serve bundleAdmissionRecords with the bundles and pass `tenant`.

interface BundleEntitlementPolicyOptions {
    /** The tenant the policy answers for; a request for another tenant is not entitled. */
    readonly tenant: string;
}

BILLING_BUNDLE_CONFORMANCE_MODE const

`mode` of a record evaluated from FHIR Bundles through the SDK projection.

const BILLING_BUNDLE_CONFORMANCE_MODE: "standalone-fhir";

BILLING_BUNDLE_DEFAULT_TENANT const

The tenant the bundle admission records admit for when the caller names none.

const BILLING_BUNDLE_DEFAULT_TENANT = "standalone";

bundleConformanceRecord function

Maps one SDK result onto a record; `CATALOG_PARTIAL` is an advisory and `ELIGIBLE` no finding.

function bundleConformanceRecord(caseId: string, result: BillingAccountResult): BillingBundleConformanceRecord;

evaluateBundleConformance function

Evaluates every Account of the bundles with `evaluateBillingAccount` over createBundleFhirClient serving the bundles and their bundleAdmissionRecords, without a FHIR server, and returns one BillingBundleConformanceRecord per Account, sorted by Account id. The SDK selects the catalog edition and rule set from the billed codings, as it does against a server. Malformed bundles or bundles without an Account throw `BillingInputError`.

function evaluateBundleConformance(input: EvaluateBundleConformanceInput): Promise<readonly BillingBundleConformanceRecord[]>;

BillingBundleConformanceFinding interface

One reason of a bundle record. Selection blocks carry effect `reject`, evaluation failures `needs-review`.

interface BillingBundleConformanceFinding {
    readonly code: BillingResultReasonCode;
    readonly ruleId?: string;
    readonly lineId?: string;
    readonly effect: BillingRuleEffect;
    readonly details?: Readonly<Record<string, string | number | boolean>>;
    readonly resolution?: BillingReasonResolution;
    /** The producing rule's provenance sources and evidence level, unchanged; comparison ignores them. */
    readonly sources?: readonly BillingRuleSource[];
    readonly evidenceLevel?: Coding;
    /** The typed explanation of an evaluation failure, unchanged; comparison ignores it. */
    readonly explanation?: BillingUnavailableExplanation;
}

BillingBundleConformanceRecord interface

One Account of the bundles evaluated in memory by `evaluateBillingAccount`, in the `fhir-billing-conformance/1` format. `caseId` is the Account id and `lineId` a ChargeItem id. `ruleSet` names the decisive rule set (payload `id`, `digest`, `canonical`, `version`) when the evaluation resolved one, the gate overlay of `selection.decisiveOverlay` when only it decides; `ruleSets` lists every rule set when the lines used more than one catalog edition. `selection` is the result's selection record, unchanged. `overlays` lists the verdict of every requested overlay rule set when the evaluation reached the rule sets.

interface BillingBundleConformanceRecord {
    readonly format: typeof BILLING_CONFORMANCE_FORMAT;
    readonly mode: typeof BILLING_BUNDLE_CONFORMANCE_MODE;
    readonly caseId: string;
    readonly decision: BillingDecision;
    readonly ruleSet?: BillingConformanceRuleSetIdentity;
    readonly ruleSets?: readonly BillingBundleRuleSetIdentity[];
    readonly engineVersion: typeof BILLING_ENGINE_VERSION;
    readonly advisories?: readonly BillingDecisionReason[];
    readonly findings: readonly BillingBundleConformanceFinding[];
    readonly overlays?: readonly BillingBundleOverlayVerdict[];
    readonly selection: BillingAccountResult['selection'];
}

BillingBundleOverlayVerdict interface

The verdict of one requested overlay rule set in a bundle record: the SDK verdict with its reasons as findings (`ELIGIBLE` is no finding). Record comparison ignores overlays; a gate overlay that changes the decision is in the record's own `decision` and `findings`.

interface BillingBundleOverlayVerdict {
    readonly ruleSet: string;
    readonly role: BillingOverlayRole;
    readonly decision: BillingDecision;
    readonly canonical: string;
    readonly version?: string;
    readonly digest?: string;
    readonly publisher?: string;
    readonly findings: readonly BillingBundleConformanceFinding[];
}

BillingBundleRuleSetIdentity interface

A rule set the evaluation used, by canonical, version and payload digest, with its publisher when it names one.

interface BillingBundleRuleSetIdentity {
    readonly canonical: string;
    readonly version: string;
    readonly digest: string;
    readonly publisher?: string;
}

EvaluateBundleConformanceInput interface

interface EvaluateBundleConformanceInput {
    /** FHIR Bundles holding the artifacts (catalog edition, its members, rule set) and the cases. */
    readonly bundles: readonly unknown[];
    /** Admission date for catalog editions and rule sets, `YYYY-MM-DD`. */
    readonly asOf: string;
    /** Tenant of the admission records the supplied artifacts are admitted with; defaults to `standalone`. */
    readonly tenant?: string;
    /**
     * Overlay rule sets to evaluate on every Account, as `EvaluateBillingAccountInput.overlays`; an overlay
     * of the bundles is admitted like any other rule set.
     */
    readonly overlays?: readonly BillingOverlayRequest[];
}

BILLING_UNAVAILABLE_MESSAGE_KEYS const

Typed explanations of `unavailable` reasons (cognovis/fhir-billing-core#68). A key names one failure cause from a closed set; the parameters name the failing input by identifiers only. An explanation never carries free text from a resource or the text of an error message: the SDK fills parameters from identifier fields it parsed and drops a value that does not have the grammar of its kind.

const BILLING_UNAVAILABLE_MESSAGE_KEYS: readonly ["as-of-invalid", "account-id-missing", "resource-missing", "resource-unreadable", "resource-identity-missing", "resource-version-conflict", "resource-read-mismatch", "json-value-invalid", "fhir-unauthorized", "fhir-profile-validation-failed", "fhir-request-failed", "pagination-incomplete", "pagination-limit", "prospective-charge-invalid", "prospective-quantity-invalid", "prospective-account-mismatch", "retirement-charge-invalid", "retirement-target-mismatch", "retirement-mutation-changed", "candidate-id-missing", "candidate-id-duplicate", "withdrawn-charge-item-unknown", "coding-missing", "chargeitem-quantity-invalid", "chargeitem-factor-invalid", "money-invalid", "currency-missing", "currency-conflict", "observation-coding-missing", "observation-value-unreadable", "observation-fact-conflict", "service-date-missing", "period-invalid", "reference-invalid", "account-coverage-invalid", "account-coverage-priority-conflict", "coverage-contract-invalid", "coverage-not-linked", "coverage-indeterminate", "coverage-subject-mismatch", "coverage-ambiguous", "contract-not-linked", "contract-indeterminate", "contract-ambiguous", "contract-identity-missing", "selection-diverges", "catalog-edition-not-in-force", "catalog-editions-overlap", "billed-coding-not-in-edition", "billed-coding-in-several-editions", "definition-code-search-unsupported", "catalog-edition-invalid", "catalog-membership-invalid", "catalog-source-evidence-invalid", "catalog-member-missing", "catalog-member-ambiguous", "catalog-member-not-active", "catalog-member-mismatch", "catalog-member-identity-missing", "catalog-membership-missing", "catalog-membership-ambiguous", "catalog-definition-missing", "catalog-definition-applicability-unsupported", "catalog-definition-price-invalid", "catalog-definition-price-ambiguous", "catalog-price-scope-invalid", "catalog-price-context-unknown", "catalog-price-context-unsupported", "catalog-price-alternative-ambiguous", "artifact-identity-missing", "artifact-not-active", "artifact-out-of-period", "modifier-extension-unsupported", "implicit-rules-unsupported", "profile-not-declared", "digest-missing", "digest-mismatch", "digest-duplicate", "edition-digest-outdated", "admission-state-invalid", "rule-set-not-in-edition", "rule-set-ambiguous", "rule-set-invalid", "rule-set-incompatible", "explicit-rule-set-ambiguous", "cross-edition-rule-unsupported", "contract-rule-set-in-edition", "contract-version-missing", "contract-rule-set-not-in-force", "contract-rule-set-ambiguous", "contract-rule-set-not-bound", "configured-rule-invalid", "configured-rule-conflict", "configured-rule-members-mismatch", "fact-source-conflict", "overlay-request-invalid", "overlay-missing", "overlay-not-in-force", "overlay-ambiguous", "overlay-not-bound", "overlay-edition-not-selected", "overlay-in-edition", "entitlement-evidence-missing", "entitlement-policy-invalid", "entitlement-policy-not-applicable", "entitlement-unverified", "entitlement-decision-invalid", "admission-missing", "admission-ambiguous", "admission-record-invalid", "admitted-configured-rules-mismatch", "configured-rule-not-admitted", "installation-policy-unavailable", "installation-policy-invalid", "installation-policy-excludes-edition", "rule-rejected", "admission-incomplete", "edition-unavailable", "edition-unentitled", "edition-expired", "edition-incompatible", "unsupported-rule", "required-fact-unavailable", "rule-exception-unavailable", "counting-scope-unavailable", "actual-multiplier-unavailable", "unit-price-unavailable", "agreement-override-unavailable", "quantity-cap-exceeded", "value-cap-applicable", "mutually-exclusive-code-present", "companion-code-required", "multiplier-out-of-bounds", "multiplier-threshold-exceeded", "multiplier-justification-required", "accompanying-information-required", "patient-attribute-mismatch", "contract-participation-required", "setting-not-permitted", "setting-indeterminate", "prior-authorization-required", "prior-authorization-indeterminate", "procedure-finding-not-satisfied", "procedure-finding-indeterminate", "diagnosis-not-satisfied", "diagnosis-indeterminate", "provider-not-eligible", "provider-eligibility-indeterminate", "quota-degression-applicable", "quota-degression-indeterminate", "quota-parameter-unavailable", "patient-attribute-indeterminate", "patient-attribute-unit-unavailable", "accompanying-information-indeterminate", "minimum-evidence-not-met", "minimum-evidence-indeterminate", "contract-code-not-permitted", "unclassified"];

BillingUnavailableExplanation interface

interface BillingUnavailableExplanation {
    readonly key: BillingUnavailableMessageKey;
    readonly params?: BillingUnavailableMessageParams;
}

BillingUnavailableMessageKey type

type BillingUnavailableMessageKey = (typeof BILLING_UNAVAILABLE_MESSAGE_KEYS)[number];

BillingUnavailableMessageParams interface

The typed parameters of an explanation. They are identifiers passed through from the failing input, never free text: `resourceType` and `id` follow the FHIR grammars, `canonical` is an absolute URI with an optional `|version`, `system` an absolute URI and `code` a FHIR code.

interface BillingUnavailableMessageParams {
    readonly resourceType?: string;
    readonly id?: string;
    readonly canonical?: string;
    readonly system?: string;
    readonly code?: string;
}

BILLING_PROSPECTIVE_CHARGE_CODES const

Prospective ChargeItem shape failures. Every code yields `unavailable`.

const BILLING_PROSPECTIVE_CHARGE_CODES: readonly ["PROSPECTIVE_QUANTITY_INVALID", "PROSPECTIVE_ACCOUNT_MISMATCH"];

BILLING_SELECTION_BLOCK_CODES const

Coverage and Contract selection outcomes that definitively exclude the service date. Every code yields `block`.

const BILLING_SELECTION_BLOCK_CODES: readonly ["COVERAGE_NOT_IN_FORCE", "CONTRACT_NOT_APPLICABLE"];

BILLING_SELECTION_UNAVAILABLE_CODES const

Indeterminate Coverage and Contract selection: unavailable contributions unless a known rule block takes precedence.

const BILLING_SELECTION_UNAVAILABLE_CODES: readonly ["SERVICE_DATE_MISSING", "COVERAGE_UNLINKED", "COVERAGE_INDETERMINATE", "COVERAGE_SUBJECT_MISMATCH", "COVERAGE_AMBIGUOUS", "CONTRACT_UNLINKED", "CONTRACT_INDETERMINATE", "CONTRACT_AMBIGUOUS", "CONTRACT_IDENTITY_MISSING", "SELECTION_DIVERGES"];

BILLING_SNAPSHOT_FAILURE_CODES const

Reasons for an unusable authority read set: unavailable contributions unless a known rule block takes precedence.

const BILLING_SNAPSHOT_FAILURE_CODES: readonly ["SNAPSHOT_MISSING", "SNAPSHOT_MALFORMED", "SNAPSHOT_AMBIGUOUS", "SNAPSHOT_STALE", "SNAPSHOT_INCOMPATIBLE", "SNAPSHOT_UNAUTHORIZED", "SNAPSHOT_PAGINATION_INCOMPLETE", "SNAPSHOT_PAGINATION_LIMIT", "DIGEST_MISMATCH", "PRICE_APPLICABILITY_UNAVAILABLE"];

BillingAllowReasonCode type

Reasons an `allow` result carries: `ELIGIBLE`, and the `CATALOG_PARTIAL` advisory when the admitted catalog edition is partial, and the `ACCOUNT_OWNER_PRACTICE_DIFFERS` review hint. An advisory never changes the decision.

type BillingAllowReasonCode = Extract<BillingReasonCode, 'ELIGIBLE' | 'CATALOG_PARTIAL' | 'ACCOUNT_OWNER_PRACTICE_DIFFERS'>;

BillingBlockReasonCode type

Every reason a `block` result may carry.

type BillingBlockReasonCode = BillingRuleBlockReasonCode | BillingSelectionBlockCode;

BillingEvaluationFailureCode type

Codes a classified snapshot, selection or prospective-input failure may carry.

type BillingEvaluationFailureCode = BillingSnapshotFailureCode | BillingSelectionUnavailableCode | BillingProspectiveChargeCode;

BillingProspectiveChargeCode type

type BillingProspectiveChargeCode = (typeof BILLING_PROSPECTIVE_CHARGE_CODES)[number];

BillingResultReasonCode type

Every reason code a Billing SDK result may carry.

type BillingResultReasonCode = BillingAllowReasonCode | BillingBlockReasonCode | BillingUnavailableReasonCode;

BillingRuleBlockReasonCode type

Reasons of a `block` decided by the configured rules, including advisories such as `CATALOG_PARTIAL`, and, beside the blocking reasons, an evaluation failure of a rule source or directed retirement read that could not be used. A known rule block takes precedence over that unavailable contribution.

type BillingRuleBlockReasonCode = BillingReasonCode | BillingEvaluationFailureCode;

BillingSelectionBlockCode type

type BillingSelectionBlockCode = (typeof BILLING_SELECTION_BLOCK_CODES)[number];

BillingSelectionUnavailableCode type

type BillingSelectionUnavailableCode = (typeof BILLING_SELECTION_UNAVAILABLE_CODES)[number];

BillingSnapshotFailureCode type

type BillingSnapshotFailureCode = (typeof BILLING_SNAPSHOT_FAILURE_CODES)[number];

BillingUnavailableReasonCode type

Every reason an `unavailable` result may carry: withheld engine reasons and evaluation failures.

type BillingUnavailableReasonCode = BillingReasonCode | BillingEvaluationFailureCode;

BillingCandidateDisposition type

Why a linked Coverage or Contract candidate was not selected for a service date. `status-excluded`: Coverage `cancelled`, or Contract `terminated`, `revoked`, `cancelled` or `rejected`. `outside-period`: Coverage `period` or Contract `applies` excludes the service date. `indeterminate`: any other or a missing status, or a period bound with a time that only partly covers the service date; it never grants selection. `lower-priority`: an in-force Coverage with a higher `Account.coverage.priority` value than the selected one. `entered-in-error`: ignored for selection, recorded as evidence.

type BillingCandidateDisposition = 'status-excluded' | 'outside-period' | 'indeterminate' | 'lower-priority' | 'entered-in-error';

BillingContractSelection interface

The selected Contract and its canonical identity. At least one of `url` and `instantiatesUri` is present.

interface BillingContractSelection extends BillingResourceVersion {
    readonly url?: string;
    readonly instantiatesUri?: string;
}

BillingRejectedCandidate interface

interface BillingRejectedCandidate extends BillingResourceVersion {
    readonly serviceDate: string;
    readonly disposition: BillingCandidateDisposition;
    readonly status?: string;
}

BillingResourceVersion interface

A FHIR resource identified by its relative reference and the version that was read.

interface BillingResourceVersion {
    readonly reference: string;
    readonly versionId: string;
}

selectBillingPerformer function

PPRF names the billing role; otherwise only one distinct literal actor is usable.

function selectBillingPerformer(chargeItem: unknown): BillingPerformerSelection;

BillingPerformerSelection type

type BillingPerformerSelection = {
    readonly reference: string;
    readonly reason?: never;
} | {
    readonly reference?: never;
    readonly reason: 'missing-billing-performer' | 'ambiguous-billing-performer' | 'invalid-billing-performer';
};