openapi: 3.1.0
info:
  title: MindBill Partner API
  version: 2.0.0
  description: |
    One bill is the immutable snapshot and payer packet submitted in a single request.
    There is no editable public bill draft. A confirmed submission returns `submitted`;
    a retained attempt with uncertain transmission returns `submission_unconfirmed`
    and `reconciliationRequired: true` on its read endpoint. Retain the returned bill ID.
    MindBill owns later status, EORs, payments, denials, reviews,
    and follow-up reviews.

    Scheduled no-response follow-ups emit `bill.follow_up_opened` and
    `bill.follow_up_resolved` for the owning partner, organization and environment.
    Payloads contain `billId`, `followUpId`, `kind: no_response` and nullable ISO
    `dueAt`. Operational thresholds are 45 days for treatment and 60 days for
    medical-legal bills, from acceptance or submission when acceptance is absent.
    These are not statutory payment deadlines. Response/payment evidence, dismissal
    or closure resolves the task; follow-up events do not change claim acceptance
    or automatically resend a bill.

    API keys belong only on your server. Browser integrations use a short-lived,
    origin-bound organization session with explicit user permissions. A session may
    optionally be restricted to one existing bill. Sandbox accepts synthetic data only.
    Business endpoints use the same URL and response contract with either credential.
    Browser sessions require their exact allowed Origin header. Legacy /browser/ URLs
    remain compatibility aliases. Events, session issuance, and organization provisioning
    require a server API key. Collection endpoints reject bill-scoped browser sessions.
    Browser access to all RFA operations requires an organization session, the treatmentBilling capability,
    and the documented RFA permission; bill-scoped browser sessions cannot access RFAs.
    The API key identifies one developer workspace. Billing requests use its stable
    default billing storage automatically; no organization ID is required in the normal
    integration. Sandbox and live remain separate. Existing explicitly selected organization
    routes and restricted keys remain supported for legacy integrations.
    Each bill contains its own provider, location and payer-document snapshots. Host customer
    isolation uses resource.customerExternalId on a browser session, derived by the partner
    backend from the authenticated user. MindBill enforces that scope on creation, resource
    reads/actions, documents and bill collections/reports. subject is audit attribution only.
    Customer sessions cannot manage shared organization settings, use shared saved provider
    profiles, or access RFA workflows. Omitted resource grants workspace-wide access and is
    appropriate only for trusted workspace administrators. resource.billId restricts access
    to one existing bill; specifying both fields requires both restrictions to match.
    The same workspace key can be used across applications. X-MindBill-Org-Id is an optional
    legacy routing override, validated against that key's workspace and environment.
servers:
  - url: https://app.mindbill.org/partner/v2
security:
  - bearerAuth: []
  - browserSessionAuth: []
tags:
  - name: Bills
  - name: Dental drafts
  - name: Documents
  - name: Lifecycle
  - name: Treatment Authorization
  - name: Events
  - name: Browser sessions
  - name: Notifications
paths:
  /fee-quotes/ca/claim:
    post:
      tags:
        - Bills
      operationId: quoteCaClaimFees
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        requiredCapability: treatmentBilling
      summary: Calculate California fees for multiple dated procedures
      description: Calculates statutory estimates for one patient and one provider/group, grouped by actual service
        date. Accepts up to 100 uniquely identified procedures with modifiers and explicit context. Applies
        verified adopted public claim edits and supported payment adjustments. Missing, held or unsupported
        historical sources require review; current rates are never substituted. Amounts are cents. A null
        estimatedPayableCents is not zero and must not be replaced with submitted charges. Does not establish
        authorization, medical necessity or entitlement to payment. No bill is created or changed. The browser
        compatibility alias is /browser/fee-quotes/ca/claim.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                lines:
                  type: array
                  items:
                    type: object
                    properties:
                      drug:
                        type: object
                        properties:
                          ndcNumber:
                            type: string
                            pattern: ^\d{11}$
                          metricQuantity:
                            type: string
                            pattern: ^(?:0|[1-9]\d{0,4})(?:\.\d{1,3})?$
                          unitOfMeasure:
                            type: string
                            enum:
                              - UN
                              - ML
                              - GR
                          administered:
                            type: object
                            properties:
                              drugName:
                                type: string
                                minLength: 1
                                maxLength: 80
                                pattern: ^[A-Za-z0-9 .(),/%+-]+$
                              administeredAmount:
                                type: string
                                pattern: ^(?:0|[1-9]\d{0,5})(?:\.\d{1,6})?$
                              doseUnit:
                                type: string
                                enum:
                                  - mg
                                  - mcg
                                  - g
                                  - mL
                                  - units
                              hcpcsCode:
                                type: string
                                pattern: ^[A-Z0-9]{5}$
                              amountPerHcpcsUnit:
                                type: string
                                pattern: ^(?:0|[1-9]\d{0,5})(?:\.\d{1,6})?$
                              amountPerNdcUnit:
                                type: string
                                pattern: ^(?:0|[1-9]\d{0,5})(?:\.\d{1,6})?$
                              hcpcsUnitSource:
                                type: string
                                format: uri
                                maxLength: 500
                              productLabelSource:
                                type: string
                                format: uri
                                maxLength: 500
                              unitDefinitionsVerified:
                                type: boolean
                                const: true
                            required:
                              - drugName
                              - administeredAmount
                              - doseUnit
                              - hcpcsCode
                              - amountPerHcpcsUnit
                              - amountPerNdcUnit
                              - hcpcsUnitSource
                              - productLabelSource
                              - unitDefinitionsVerified
                            additionalProperties: false
                        required:
                          - ndcNumber
                          - metricQuantity
                          - unitOfMeasure
                        additionalProperties: false
                      pharmacyContext:
                        type: object
                        properties:
                          dispenser:
                            type: string
                            enum:
                              - physician
                              - pharmacy
                          productKind:
                            type: string
                            enum:
                              - simple
                              - repackaged
                              - compound
                              - physician_administered
                          usualCustomaryCents:
                            type: integer
                            minimum: 0
                            maximum: 100000000
                          pharmacyNpi:
                            type: string
                            pattern: ^\d{10}$
                          noSubstitution:
                            type: boolean
                          noSubstitutionRequirementsSatisfied:
                            type: boolean
                          physicianDispensingRequirementsSatisfied:
                            type: boolean
                          physicianPaidForDrug:
                            type: boolean
                          documentedPaidCostCents:
                            type: integer
                            minimum: 0
                            maximum: 100000000
                          acquisitionDocumentationIncluded:
                            type: boolean
                          codingRequirementsSatisfied:
                            type: boolean
                        required:
                          - dispenser
                          - productKind
                          - usualCustomaryCents
                          - noSubstitution
                          - codingRequirementsSatisfied
                        additionalProperties: false
                      padbContext:
                        type: object
                        properties:
                          providerKind:
                            type: string
                            const: physician
                          placeOfService:
                            type: string
                            const: "11"
                          productKind:
                            type: string
                            const: injectable
                          bundledOrPackaged:
                            type: boolean
                            const: false
                          codingRequirementsSatisfied:
                            type: boolean
                            const: true
                          completeSameDayServices:
                            type: boolean
                            const: true
                          sameDayServices:
                            type: array
                            items:
                              type: object
                              properties:
                                code:
                                  type: string
                                  pattern: ^[A-Z0-9]{5}$
                                units:
                                  type: integer
                                  exclusiveMinimum: 0
                                  maximum: 10000
                              required:
                                - code
                                - units
                              additionalProperties: false
                            minItems: 1
                            maxItems: 50
                        required:
                          - providerKind
                          - placeOfService
                          - productKind
                          - bundledOrPackaged
                          - codingRequirementsSatisfied
                          - completeSameDayServices
                          - sameDayServices
                        additionalProperties: false
                      anesthesiaContext:
                        type: object
                        properties:
                          providerKind:
                            type: string
                            const: physician
                          personallyPerformedAlone:
                            type: boolean
                          actualMinutes:
                            type: integer
                            minimum: 1
                            maximum: 1440
                          placeOfService:
                            type: string
                            pattern: ^\d{2}$
                          completeSameDayServices:
                            type: boolean
                            const: true
                          otherSameDayServices:
                            type: boolean
                            const: false
                          codingRequirementsSatisfied:
                            type: boolean
                            const: true
                          medicalDirection:
                            type: object
                            properties:
                              physicianRef: &a1
                                type: string
                                minLength: 1
                                maxLength: 128
                              groupPhysicianRefs:
                                type: array
                                items: *a1
                                minItems: 0
                                maxItems: 100
                              billedCaseRef: *a1
                              rosterScope:
                                const: all_overlapping_cases_all_payers
                              rosterRecordRef: *a1
                              cases:
                                type: array
                                items:
                                  type: object
                                  properties:
                                    caseRef: *a1
                                    anesthetistRole:
                                      enum:
                                        - crna
                                        - anesthesiologist_assistant
                                        - intern
                                        - resident
                                        - student_nurse_anesthetist
                                    qualificationRecordRef: *a1
                                    procedure:
                                      enum:
                                        - cataract
                                        - iridectomy
                                        - other
                                    interval: &a6
                                      type: object
                                      properties:
                                        startMinute: &a2
                                          type: integer
                                          minimum: 0
                                          maximum: 2880
                                        endMinute: *a2
                                      required:
                                        - startMinute
                                        - endMinute
                                      additionalProperties: false
                                      description: Minutes from midnight on the service date (0–2880). End must be after start. Overnight billed cases require review.
                                    activities:
                                      type: object
                                      properties:
                                        preAnestheticEvaluation: &a3
                                          type: object
                                          properties:
                                            physicianRef: *a1
                                            recordRef: *a1
                                            minute: *a2
                                          required:
                                            - physicianRef
                                            - recordRef
                                            - minute
                                          additionalProperties: false
                                        prescribedPlan: *a3
                                        demandingProcedures:
                                          type: array
                                          items: &a4
                                            type: object
                                            properties:
                                              physicianRef: *a1
                                              recordRef: *a1
                                              startMinute: *a2
                                              endMinute: *a2
                                            required:
                                              - physicianRef
                                              - recordRef
                                              - startMinute
                                              - endMinute
                                            additionalProperties: false
                                          minItems: 1
                                          maxItems: 100
                                        induction: &a5
                                          oneOf:
                                            - *a4
                                            - type: object
                                              properties:
                                                applicability:
                                                  const: not_indicated
                                                recordRef: *a1
                                              required:
                                                - applicability
                                                - recordRef
                                              additionalProperties: false
                                        emergence: *a5
                                        qualifiedAnesthetistProcedures: *a3
                                        frequentMonitoring:
                                          type: object
                                          properties:
                                            recordRef: *a1
                                            observations:
                                              type: array
                                              items: *a3
                                              minItems: 1
                                              maxItems: 1440
                                          required:
                                            - recordRef
                                            - observations
                                          additionalProperties: false
                                        indicatedPostAnesthesiaCare: *a3
                                      required:
                                        - preAnestheticEvaluation
                                        - prescribedPlan
                                        - demandingProcedures
                                        - induction
                                        - emergence
                                        - qualifiedAnesthetistProcedures
                                        - frequentMonitoring
                                        - indicatedPostAnesthesiaCare
                                      additionalProperties: false
                                  required:
                                    - caseRef
                                    - anesthetistRole
                                    - qualificationRecordRef
                                    - procedure
                                    - interval
                                    - activities
                                  additionalProperties: false
                                minItems: 1
                                maxItems: 100
                              physicalPresenceAndImmediateAvailability:
                                type: array
                                items: *a4
                                minItems: 1
                                maxItems: 100
                              otherPatientServices:
                                type: array
                                items:
                                  type: object
                                  properties:
                                    kind:
                                      enum:
                                        - emergency
                                        - labor_analgesia
                                        - obstetric_monitoring
                                        - receiving_patient
                                        - recovery_care
                                        - other
                                    interval: *a6
                                    recordRef: *a1
                                  required:
                                    - kind
                                    - interval
                                    - recordRef
                                  additionalProperties: false
                                minItems: 0
                                maxItems: 100
                            required:
                              - physicianRef
                              - groupPhysicianRefs
                              - billedCaseRef
                              - rosterScope
                              - rosterRecordRef
                              - cases
                              - physicalPresenceAndImmediateAvailability
                              - otherPatientServices
                            additionalProperties: false
                            description: QK direction requires the complete overlapping case roster across all payers and the actual seven-activity, participation and availability records. Use opaque references, never patient names. The server validates concurrency, timing and applicable exclusions; schema acceptance does not establish payment eligibility.
                          monitoredCare:
                            type: object
                            properties:
                              medicallyNecessary:
                                const: true
                              intraoperativePhysiologicalMonitoring:
                                const: true
                              preparedForGeneralAnesthesiaOrAdverseReaction:
                                const: true
                              perioperativeAnesthesiaCare:
                                const: true
                              underlyingProcedureProvider:
                                enum:
                                  - different_provider
                                  - same_provider
                              underlyingProcedure:
                                enum:
                                  - nerve_block_or_injection
                                  - other
                            required:
                              - medicallyNecessary
                              - intraoperativePhysiologicalMonitoring
                              - preparedForGeneralAnesthesiaOrAdverseReaction
                              - perioperativeAnesthesiaCare
                              - underlyingProcedureProvider
                              - underlyingProcedure
                            additionalProperties: false
                            description: Documented monitored anesthesia care (MAC), requiring QS in addition to AA or QK. Same-provider underlying procedures require review; QS alone does not establish these clinical facts.
                        required:
                          - providerKind
                          - personallyPerformedAlone
                          - actualMinutes
                          - placeOfService
                          - completeSameDayServices
                          - otherSameDayServices
                          - codingRequirementsSatisfied
                        additionalProperties: false
                        oneOf:
                          - properties:
                              personallyPerformedAlone:
                                const: true
                            not:
                              required:
                                - medicalDirection
                          - properties:
                              personallyPerformedAlone:
                                const: false
                            required:
                              - medicalDirection
                        description: One physician anesthesia service with quantity 1. AA is personally performed; QK is documented medical direction. MAC adds QS. Minutes are elapsed anesthesia minutes, not billing time units. Additional same-day patient services, teaching cases, overnight cases, cataract/iridectomy direction and other unsupported circumstances require review.
                      ambulanceContext:
                        type: object
                        properties:
                          pickupZip:
                            type: string
                            pattern: ^\d{5}$
                          transportCode:
                            type: string
                            enum:
                              - A0426
                              - A0427
                              - A0428
                              - A0429
                              - A0433
                              - A0434
                          coveredLoadedMiles:
                            type: number
                            minimum: 0
                            maximum: 100000
                          patientCount:
                            type: integer
                            minimum: 1
                            maximum: 100
                          sameOrigin:
                            type: boolean
                          sameDestination:
                            type: boolean
                          completedTransport:
                            type: boolean
                          esrdDialysisTransport:
                            type: boolean
                          originDestinationModifier:
                            type: string
                            pattern: ^[DEGHIJNPRS][DEGHIJNPRSX]$
                        required:
                          - pickupZip
                          - transportCode
                          - coveredLoadedMiles
                          - patientCount
                          - sameOrigin
                          - sameDestination
                          - completedTransport
                          - esrdDialysisTransport
                          - originDestinationModifier
                        additionalProperties: false
                      ndcNumber:
                        type: string
                        pattern: ^\d{11}$
                      code:
                        type: string
                        pattern: ^[A-Z0-9]{5}$
                      dateOfService:
                        type: string
                        format: date
                      chargeCents:
                        type: integer
                        exclusiveMinimum: 0
                        maximum: 100000000
                      units:
                        type: number
                        exclusiveMinimum: 0
                        maximum: 10000
                      modifiers:
                        type: array
                        items:
                          type: string
                          pattern: ^[A-Z0-9]{2}$
                        maxItems: 4
                        uniqueItems: true
                      pages:
                        type: integer
                        exclusiveMinimum: 0
                        maximum: 10000
                      reportKind:
                        type: string
                        enum:
                          - progress
                          - permanent_stationary_pr3
                          - permanent_stationary_pr4
                      reportQualification:
                        anyOf:
                          - type: object
                            properties:
                              kind:
                                type: string
                                const: psychiatric_report
                              requestedBy:
                                type: string
                                enum:
                                  - wcab
                                  - administrative_director
                              medicalLegalEvaluation:
                                type: boolean
                              reportPayableUnderMedicalLegalSchedule:
                                type: boolean
                            required:
                              - kind
                              - requestedBy
                              - medicalLegalEvaluation
                              - reportPayableUnderMedicalLegalSchedule
                            additionalProperties: false
                          - type: object
                            properties:
                              kind:
                                type: string
                                const: consultation_report
                              requestedBy:
                                type: string
                                enum:
                                  - wcab
                                  - administrative_director
                                  - qme
                                  - ame
                              medicalLegalEvaluation:
                                type: boolean
                              reportPayableUnderMedicalLegalSchedule:
                                type: boolean
                            required:
                              - kind
                              - requestedBy
                              - medicalLegalEvaluation
                              - reportPayableUnderMedicalLegalSchedule
                            additionalProperties: false
                          - type: object
                            properties:
                              kind:
                                type: string
                                const: chart_notes
                              requestedBy:
                                type: string
                                const: claims_administrator
                              writtenRequest:
                                type: boolean
                            required:
                              - kind
                              - requestedBy
                              - writtenRequest
                            additionalProperties: false
                          - type: object
                            properties:
                              kind:
                                type: string
                                const: duplicate_report
                              requestedBy:
                                type: string
                                const: claims_administrator
                              writtenRequest:
                                type: boolean
                              relatedToBilling:
                                type: boolean
                              initialRequiredCopy:
                                type: boolean
                            required:
                              - kind
                              - requestedBy
                              - writtenRequest
                              - relatedToBilling
                              - initialRequiredCopy
                            additionalProperties: false
                      hasFeeAgreement:
                        type: boolean
                      serviceZip:
                        type: string
                        pattern: ^\d{5}(?:-?\d{4})?$
                      serviceCounty:
                        type: string
                        minLength: 1
                        maxLength: 40
                      dmeposContext:
                        $ref: '#/components/schemas/CaDmeposContext'
                      therapyContext:
                        type: object
                        properties:
                          providerKind:
                            type: string
                            enum:
                              - physical_therapist
                              - other
                          personallyPerformed:
                            type: boolean
                          placeOfService:
                            type: string
                            pattern: ^\d{2}$
                          hospitalPatient:
                            type: boolean
                          incidentToPhysicianService:
                            type: boolean
                          assistantInvolved:
                            type: boolean
                          priorInitialEvaluationInEpisode:
                            type: boolean
                            description: Whether an initial PT evaluation was already furnished in this episode of care.
                              Initial evaluations 97161-97163 require false; unknown must stay omitted.
                          directOneOnOneMinutes:
                            type: integer
                            minimum: 0
                            maximum: 1440
                          totalVisitMinutes:
                            type: integer
                            minimum: 0
                            maximum: 1440
                          visitsOnDate:
                            type: integer
                            minimum: 0
                            maximum: 100
                          completeSameDayServices:
                            type: boolean
                          otherSameDayServices:
                            type: boolean
                          globalPeriodApplies:
                            type: boolean
                          hpsaBonusEligible:
                            type: boolean
                        additionalProperties: false
                      historicalTelephoneContext:
                        $ref: '#/components/schemas/CaHistoricalTelephoneContext'
                      catalogContext:
                        type: object
                        properties:
                          codingRequirementsSatisfied:
                            type: boolean
                          statusIAlternative:
                            type: string
                            enum:
                              - none
                              - cpt
                              - drug
                          completeSurgicalPackage:
                            type: boolean
                          surgicalContext:
                            type: object
                            properties:
                              bilateralProcedurePerformed:
                                type: boolean
                              assistantAtSurgery:
                                type: object
                                properties:
                                  activelyAssisted:
                                    type: boolean
                                  coOrTeamSurgeonAppropriate:
                                    type: boolean
                                  medicalNecessityEstablished:
                                    type: boolean
                                  qualifiedResidentUnavailable:
                                    type: boolean
                                required:
                                  - activelyAssisted
                                  - coOrTeamSurgeonAppropriate
                                additionalProperties: false
                            additionalProperties: false
                        required:
                          - codingRequirementsSatisfied
                        additionalProperties: false
                      professionalComponentContext:
                        type: object
                        properties:
                          interpretationLocation:
                            type: string
                            enum:
                              - same_as_patient_service
                              - different_from_patient_service
                          supervisionLevel:
                            type: string
                            enum: [general, direct, personal]
                            description: Actual diagnostic supervision furnished, where required by the adopted indicator.
                          imagingSessionReference:
                            type: string
                            pattern: ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$
                            description: Opaque encounter-local reference to the actual imaging session; use no patient identifiers. Distinct eligible modifier-26 imaging services are ranked within this session. For supported global MRI, supply the same actual session in both component contexts; professional and technical amounts rank independently.
                          completeSameDayImagingServices:
                            type: boolean
                            description: Actual confirmation that this encounter includes all relevant imaging services for the patient and provider group on this date, including services otherwise billed elsewhere. Required true for imaging encounter allocation; never inferred from a date or session reference.
                        required:
                          - interpretationLocation
                        additionalProperties: false
                      technicalComponentContext:
                        type: object
                        description: Actual facts for bounded office MRI encounters. Supports distinct 70551, 72141 and 72148, one unit, physician provider, actual service ZIP and POS 11 under the audited California July 2026 RVU edition. Use modifier TC for a technical-only encounter, or no modifiers for a global-only encounter with professionalComponentContext specifying the same physical interpretation location, matching actual session and complete imaging services. Global rates require authenticated and reconciled global, professional and technical source rows and a nonbinding technical OPPS ceiling. Mixed component encounters and other contexts require review. Session labels and dates never imply completeness, performance or supervision.
                        properties:
                          performedByBillingProviderGroup:
                            type: boolean
                            description: Whether the billing provider or group actually furnished the technical service. Purchased or outsourced services require review.
                          patientHospitalStatus:
                            type: string
                            enum: [not_hospital_patient, hospital_inpatient_or_outpatient]
                          supervisionLevel:
                            type: string
                            enum: [general, direct, personal]
                            description: Actual supervision furnished; never inferred from the procedure or provider type.
                          imagingSessionReference:
                            type: string
                            pattern: ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$
                            description: Opaque reference for the actual imaging session, without patient identifiers. Technical components rank independently within this session.
                          completeSameDayImagingServices:
                            type: boolean
                            description: Actual confirmation that all relevant imaging services for this patient and provider group on this date are included, including services billed elsewhere. Must be true; mixed or incomplete encounters require review.
                        required:
                          - performedByBillingProviderGroup
                          - patientHospitalStatus
                          - supervisionLevel
                          - imagingSessionReference
                          - completeSameDayImagingServices
                        additionalProperties: false
                      prolongedServiceContext:
                        type: object
                        properties:
                          totalMinutes:
                            type: integer
                            minimum: 0
                            maximum: 1440
                          relatedEvaluationDate:
                            type: string
                            pattern: ^\d{4}-\d{2}-\d{2}$
                          ongoingPatientManagement:
                            type: boolean
                          personallyPerformed:
                            type: boolean
                          timeCountedInOtherServices:
                            type: boolean
                          completeSameDayServices:
                            type: boolean
                          sameDayServices:
                            type: array
                            items:
                              type: object
                              properties:
                                code:
                                  type: string
                                  pattern: ^9935[89]$
                                units:
                                  type: integer
                                  minimum: 1
                                  maximum: 100
                              required:
                                - code
                                - units
                              additionalProperties: false
                            minItems: 1
                            maxItems: 2
                        required:
                          - totalMinutes
                          - relatedEvaluationDate
                          - ongoingPatientManagement
                          - personallyPerformed
                          - timeCountedInOtherServices
                          - completeSameDayServices
                          - sameDayServices
                        additionalProperties: false
                      physicianContext:
                        type: object
                        properties:
                          telehealthModality:
                            type: string
                            enum:
                              - audio_video
                              - audio_only
                          providerKind:
                            type: string
                            enum:
                              - physician
                              - physician_assistant
                              - nurse_practitioner
                              - clinical_nurse_specialist
                              - clinical_social_worker
                              - other
                          incidentToPhysicianService:
                            type: boolean
                          placeOfService:
                            type: string
                            pattern: ^\d{2}$
                          standaloneService:
                            type: boolean
                          globalPeriodApplies:
                            type: boolean
                          hpsaBonusEligible:
                            type: boolean
                        required:
                          - providerKind
                          - placeOfService
                          - standaloneService
                          - globalPeriodApplies
                          - hpsaBonusEligible
                        additionalProperties: false
                      id:
                        type: string
                        minLength: 1
                        maxLength: 100
                    required:
                      - code
                      - dateOfService
                      - id
                    additionalProperties: false
                  minItems: 1
                  maxItems: 100
                  description: All lines for one patient and one provider/group. IDs must be unique; different service dates are
                    evaluated independently.
                completeDateOfServiceContext:
                  type: boolean
                  description: True only when all same-day services for this patient and provider/group are included, including
                    services billed elsewhere. Incomplete context requires review.
                ordinaryMultipleSurgeryContext:
                  type: boolean
                  description: Explicitly attest to unrelated separately payable ordinary operations by the same surgeon/group;
                    excludes endoscopy, interventional radiology and returns for complications.
              required:
                - lines
                - completeDateOfServiceContext
              additionalProperties: false
            example:
              completeDateOfServiceContext: true
              lines:
                - id: line-1
                  code: "99214"
                  dateOfService: 2024-02-15
                  units: 1
                  modifiers: []
                  serviceCounty: Los Angeles
                  physicianContext:
                    providerKind: physician
                    placeOfService: "11"
                    standaloneService: true
                    globalPeriodApplies: false
                    hpsaBonusEligible: false
      responses:
        "200":
          description: Claim assessment with per-line evidence, dated claim edits and nullable complete totals.
          content:
            application/json:
              schema:
                type: object
                required:
                  - data
                properties:
                  data:
                    type: object
                    required:
                      - status
                      - lines
                      - totals
                      - claimEdits
                      - limitations
                    properties:
                      status:
                        type: string
                        enum:
                          - priced
                          - requires_review
                          - not_separately_payable
                      lines:
                        type: array
                        items:
                          type: object
                          required:
                            - id
                            - input
                            - quote
                            - assessment
                            - findings
                          properties:
                            id:
                              type: string
                            input:
                              $ref: "#/paths/~1fee-quotes~1ca~1claim/post/requestBody/content/application~1json/schema/properties/lines/ite\
                                ms"
                            quote:
                              type: object
                              description: Unadjusted line calculation and provenance. This is evidence, not the final claim allowance.
                              properties:
                                status:
                                  type: string
                                  enum:
                                    - priced
                                    - requires_review
                                    - not_separately_payable
                                amountCents:
                                  type: integer
                                  minimum: 0
                                scheduleMaximumCents:
                                  type: integer
                                  minimum: 0
                                reason:
                                  type: string
                                provenance:
                                  type: array
                                  items:
                                    type: object
                            assessment:
                              type: string
                              enum:
                                - priced
                                - requires_review
                                - not_separately_payable
                            findings:
                              type: array
                              items:
                                type: object
                                required:
                                  - code
                                  - lineIds
                                  - message
                                properties:
                                  code:
                                    type: string
                                  lineIds:
                                    type: array
                                    items:
                                      type: string
                                  message:
                                    type: string
                                  citationUrl:
                                    type: string
                                    format: uri
                                  edit:
                                    type: object
                                    description: Underlying public PTP/MUE finding when applicable.
                            paymentAdjustment:
                              type: object
                              required:
                                - rule
                                - rank
                                - percent
                                - unadjustedScheduleMaximumCents
                                - scheduleMaximumCents
                                - amountCents
                                - citationUrl
                              properties:
                                rule:
                                  type: string
                                  const: ca_multiple_surgery
                                rank:
                                  type: integer
                                  minimum: 1
                                percent:
                                  type: integer
                                  enum:
                                    - 100
                                    - 50
                                unadjustedScheduleMaximumCents:
                                  type: integer
                                  minimum: 0
                                scheduleMaximumCents:
                                  type: integer
                                  minimum: 0
                                amountCents:
                                  type: integer
                                  minimum: 0
                                citationUrl:
                                  type: string
                                  format: uri
                      totals:
                        type: object
                        required:
                          - submittedChargeCents
                          - pricedSubtotalCents
                          - estimatedPayableCents
                          - scheduleMaximumCents
                          - reviewLineCount
                        properties:
                          submittedChargeCents:
                            type:
                              - integer
                              - "null"
                            minimum: 0
                          pricedSubtotalCents:
                            type: integer
                            minimum: 0
                            description: Subtotal of priced lines only; not a complete allowance when any line requires review.
                          estimatedPayableCents:
                            type:
                              - integer
                              - "null"
                            minimum: 0
                            description: Null when the complete claim allowance cannot be established.
                          scheduleMaximumCents:
                            type:
                              - integer
                              - "null"
                            minimum: 0
                          reviewLineCount:
                            type: integer
                            minimum: 0
                      claimEdits:
                        type: array
                        items:
                          type: object
                          required:
                            - dateOfService
                            - lineIds
                            - status
                            - findings
                          properties:
                            dateOfService:
                              type: string
                              format: date
                            lineIds:
                              type: array
                              items:
                                type: string
                            status:
                              type: string
                              enum:
                                - evaluated
                                - requires_review
                                - source_unavailable
                                - not_applicable
                            reason:
                              type: string
                            findings:
                              type: array
                              items:
                                type: object
                            provenance:
                              type: object
                              description: Exact adopted dates, government source links and immutable source hashes.
                            supportedDateRange:
                              type: object
                              properties:
                                from:
                                  type: string
                                  format: date
                                through:
                                  type: string
                                  format: date
                      limitations:
                        type: array
                        items:
                          type: string
        "403":
          description: Missing bills:read permission or treatmentBilling capability.
        "422":
          description: invalid_claim_fee_quote; invalid dates, duplicate line IDs/modifiers or malformed context.
        default:
          $ref: "#/components/responses/Problem"
  /fee-quotes/ca/claim-edits:
    post:
      tags: [Bills]
      operationId: screenCaPractitionerClaimEdits
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        requiredCapability: treatmentBilling
      summary: Screen California practitioner PTP and public MUE edits
      description: |
        Screens submitted practitioner lines against verified California-adopted July–September 2026 editions.
        Groups by patientKey, providerKey and actual date of service. Supply opaque grouping keys, not names.
        PTP modifier indicators remain review findings; a modifier never proves a clinical exception.
        MUE indicator 1 evaluates each line; indicators 2 and 3 aggregate same-code units for each group.
        California excludes zero-value MUEs. Missing public values may be confidential and require review.
        This endpoint never determines or changes a monetary allowance. It does not adjudicate medical necessity,
        confidential limits, manual exceptions or other payment adjustments. Older/later dates or inactive,
        changed, held or unavailable sources return source_unavailable. The browser compatibility alias is
        /browser/fee-quotes/ca/claim-edits. Saved-bill reads also expose claimEdits with incomplete date context,
        because one stored bill cannot establish whether other same-day services exist.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [lines, completeDateOfServiceContext]
              properties:
                completeDateOfServiceContext:
                  type: boolean
                  description: True only when every service for each submitted patient/provider/date group is included, including services on other bills.
                lines:
                  type: array
                  minItems: 1
                  maxItems: 100
                  items:
                    type: object
                    additionalProperties: false
                    required: [id, code, units, dateOfService, patientKey, providerKey]
                    properties:
                      id: {type: string, minLength: 1, maxLength: 100, description: Unique line identifier}
                      code: {type: string, pattern: '^[A-Z0-9]{5}$'}
                      units: {type: integer, minimum: 1, maximum: 1000000}
                      dateOfService: {type: string, format: date}
                      patientKey: {type: string, minLength: 1, maxLength: 100}
                      providerKey: {type: string, minLength: 1, maxLength: 100}
                      modifiers:
                        type: array
                        maxItems: 4
                        items: {type: string, pattern: '^[A-Z0-9]{2}$'}
            example:
              completeDateOfServiceContext: false
              lines:
              - {id: line-1, code: '97110', units: 4, dateOfService: '2026-07-01', patientKey: patient-1, providerKey: provider-1}
      responses:
        '200':
          description: Screening result, including review findings or source unavailability. Never a claim acceptance or payable amount.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: object
                    required: [status, scope, findings]
                    properties:
                      status: {type: string, enum: [evaluated, requires_review, source_unavailable]}
                      scope: {type: string, const: submitted_practitioner_lines}
                      completeDateOfServiceContext: {type: boolean}
                      reason: {type: string}
                      findings:
                        type: array
                        items:
                          type: object
                          required: [type, lineIds, message, citationUrl]
                          properties:
                            type: {type: string, enum: [ptp, mue, public_mue_unavailable, incomplete_date_context]}
                            lineIds: {type: array, items: {type: string}}
                            message: {type: string}
                            citationUrl: {type: string, format: uri}
                            modifierIndicator: {type: integer}
                            adjudicationIndicator: {type: integer}
                            submittedUnits: {type: integer}
                            limit: {type: integer}
                            code: {type: string}
                            column1: {type: string}
                            column2: {type: string}
                            scope: {type: string, enum: [line, patient_provider_date]}
                      limitations: {type: array, items: {type: string}}
                      provenance: {type: object, additionalProperties: true, description: Adopted edition, effective dates, regulation/order URLs, source archive and normalized bundle SHA-256 hashes.}
                      supportedDateRange: {type: object, additionalProperties: {type: string}}
        '422':
          description: invalid_claim_edit_request; malformed dates, lines, units or duplicate line IDs.
        '403':
          description: Missing bills:read permission or treatmentBilling capability.
        default:
          $ref: '#/components/responses/Problem'
  /fee-quotes/ca/copy-service:
    post:
      tags: [Bills]
      operationId: quoteCaCopyServiceFee
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        requiredCapability: treatmentBilling
      summary: Calculate a California Copy Service schedule estimate
      description: >-
        Selects the July 1, 2015 or July 15, 2022 edition by actual service date.
        Dates before the schedule, unresolved exceptions, and stale or unavailable source reviews return explicit review states.
        An unknown allowance is null, never the submitted charge or a presumed zero. Supplied claim history and evidence
        are not independently verified. Contract amounts, submitted charges, tax, and late-payment estimates remain separate.
        The browser-authenticated alias is /browser/fee-quotes/ca/copy-service. Both transports require bills:read
        and the organization's treatmentBilling capability. Organization and environment come from authentication.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/CaCopyServiceQuoteInput'}
            example: {dateOfService: '2026-09-18', service: initial, paperPages: 600, submittedChargeCents: 25000}
      responses:
        '200':
          description: Schedule estimate or explicit review/documentation/liability state with regulatory citations. No bill is created.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data: {$ref: '#/components/schemas/CaCopyServiceQuoteResult'}
        '401':
          description: Missing or invalid authentication.
        '403':
          description: Missing bills:read permission or treatmentBilling capability.
        '422':
          description: Invalid dates, quantities, cents, missing add-on history, service facts, chronology, or unknown request fields (invalid_copy_service_quote).
        default:
          $ref: '#/components/responses/Problem'
  /fee-quotes/ca/inpatient:
    post:
      tags: [Bills]
      operationId: quoteCaInpatientFee
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        requiredCapability: treatmentBilling
      summary: Calculate a California inpatient hospital maximum
      description: >-
        Uses adopted discharge-date hospital factors and DRG weights. Supply the assigned DRG; this endpoint does not
        group diagnoses or procedures. Returns the statutory maximum, not a negotiated contract amount or a coverage
        determination. Missing editions or hospital factors and cases requiring a separate determination return
        unavailable without a monetary allowance. Supply actualInpatientDays to exclude leave days from transfer
        formulas. A known leave without an actual count returns actual_inpatient_days_required without a fee.
        Otherwise calendar dates provide the day count, disclosed in the result.
        New-technology payments are verified for December 1, 2025 through November 30, 2026; missing or
        unsupported technology facts return review without a base-only allowance. DRG 018 requires the product
        purchase context. The December 1, 2025 edition applies a 0.16 weight factor to products supplied through
        an applicable trial, expanded access or at no cost, including operating and capital components. Normally
        purchased products retain full weight, including use during a trial of a different product.
        Explicit deviceReplacementCreditStatus is required. Free replacement devices, credits of at least 50%
        of device cost require deviceReplacementCredit details. For a qualifying DRG whose assignment depended
        on the device implantation, deduct the actual credit from final reimbursement; covered charges must
        already reflect the credit. Unknown circumstances require claim facts. Partial credits below 50% use none.
        For discharges December 1, 2020 through September 30, 2023, hasCovid19Diagnosis is conditionally
        required. Only explicit false permits an unaffected calculation; true or null returns historical_covid_review
        without an amount. Supplied U07.1 diagnosis coding contradicting false also requires review. Current dates
        do not require this field. Historical COVID adjustment calculations are not implemented.
        The browser-authenticated alias is /browser/fee-quotes/ca/inpatient.
      requestBody:
        required: true
        content:
          application/json:
            example: {
              "admissionDate": "2025-02-01",
              "dischargeDate": "2025-02-05",
              "hospitalProviderNumber": "050002",
              "drg": "470",
              "hospitalType": "acute",
              "dischargeType": "ordinary",
              "coveredInpatientChargesCents": 5000000,
              "deviceReplacementCreditStatus": "none",
              "hasNewTechnology": false,
              "hasOrganAcquisition": false
            }
            schema:
              type: object
              additionalProperties: false
              required: [admissionDate, dischargeDate, hospitalProviderNumber, drg, hospitalType, dischargeType, coveredInpatientChargesCents, deviceReplacementCreditStatus, hasNewTechnology, hasOrganAcquisition]
              properties:
                admissionDate: {type: string, format: date}
                dischargeDate:
                  type: string
                  format: date
                  description: Selects the adopted data edition; must be on or after admission.
                hasCovid19Diagnosis:
                  type: boolean
                  nullable: true
                  description: Required only for discharges December 1, 2020 through September 30, 2023. False confirms no COVID-19 diagnosis during this stay. True or null (unknown) returns historical_covid_review without any allowance; missing required declarations return 422. Covers the adopted 20% adjustment through May 11, 2023 and unresolved California applicability of federal COVID treatment add-ons through September 30, 2023.
                actualInpatientDays:
                  type: integer
                  minimum: 1
                  description: Actual inpatient days excluding leave days. Cannot exceed the admission-to-discharge calendar difference, with a one-day bound for a same-day inpatient stay. Used in transfer and transfer-outlier formulas; does not change ordinary DRG amounts.
                hasLeaveOfAbsence:
                  type: boolean
                  description: True when the stay includes a known leave. Without actualInpatientDays, true returns a review result without a fee. Omitted or false permits the calendar day-count default when no actual count is supplied.
                hospitalProviderNumber:
                  type: string
                  pattern: '^[0-9]{6}$'
                  description: Six-digit Medicare provider number, retaining leading zeros.
                drg:
                  type: string
                  pattern: '^[0-9]{3}$'
                  description: Assigned diagnosis-related group, retaining leading zeros.
                immunotherapyContext:
                  type: string
                  enum: [standard_purchase, trial_expanded_access_or_no_cost]
                  description: For DRG 018, identify how the immunotherapy product was obtained. The December 1, 2025 edition uses a 0.16 weight factor for trial_expanded_access_or_no_cost. Standard purchase includes a normally purchased product used during a trial of a different product. Missing context cannot calculate; historical adjusted cases require the historical factor.
                hospitalType:
                  type: string
                  enum: [acute, critical_access, children, cancer, va, long_term, rehabilitation, rehabilitation_unit, psychiatric, psychiatric_unit, out_of_state]
                  description: Formal hospital or unit classification; long stay or cancer diagnosis alone does not establish a long-term or cancer hospital. Exempt hospital categories require a separate reasonable-cost determination.
                dischargeType:
                  type: string
                  enum: [ordinary, receiving_hospital, acute_transfer, post_acute_transfer]
                postAcuteDestination:
                  type: string
                  enum: [rehabilitation_hospital, rehabilitation_unit, long_term_hospital, other_post_acute]
                  description: Required for post_acute_transfer; identifies the receiving provider category.
                coveredInpatientChargesCents:
                  type: integer
                  minimum: 0
                  maximum: 100000000000
                  description: Covered facility charges excluding separately billed professional services, preadmission services more than 24 hours before admission, nonmedical charges and home-use durable medical equipment.
                deviceReplacementCreditStatus:
                  type: string
                  enum: [none, free_or_credited, unknown]
                  description: Required declaration. none means no free replacement device or credit of at least 50% of device cost; partial credits below 50% use none. free_or_credited requires deviceReplacementCredit facts; unknown cannot calculate.
                deviceReplacementCredit:
                  type: object
                  additionalProperties: false
                  required: [deviceDeterminesDrg, creditAmountCents, coveredChargesNetOfCredit]
                  description: Only supply for free_or_credited. The current adopted edition checks the qualifying DRG list and deducts the actual credit once from final reimbursement when implantation determined the DRG. No 120% multiplier applies to the credit.
                  properties:
                    deviceDeterminesDrg:
                      type: boolean
                      description: Whether implantation of the replacement device determined assignment to this DRG.
                    creditAmountCents:
                      type: integer
                      minimum: 1
                      maximum: 100000000000
                      description: Actual value code FD credit, including the documented value of a free replacement. A credit exceeding calculated reimbursement requires corrected claim facts.
                    coveredChargesNetOfCredit:
                      type: boolean
                      description: Confirm covered inpatient charges already reflect the device credit before outlier calculation. False cannot calculate.
                hasNewTechnology:
                  type: boolean
                  description: Explicitly identify whether new-technology add-on payment applies. True without complete technology facts returns review.
                newTechnology:
                  type: object
                  additionalProperties: false
                  required: [technologyIds, diagnosisCodes, procedureCodes, codingComplete]
                  description: Only supply when hasNewTechnology is true. Identify products actually used and complete inpatient ICD-10-CM/PCS coding. Eligibility, operating CCR and payment caps are server-controlled; unsupported products or dates require review.
                  properties:
                    technologyIds:
                      type: array
                      minItems: 1
                      maxItems: 54
                      items: {type: string, minLength: 1, maxLength: 100}
                      description: Product identifiers from the current inpatient calculator catalogue, such as ceribell. Duplicate or overlapping payment categories require correction.
                    diagnosisCodes:
                      type: array
                      maxItems: 100
                      items: {type: string, pattern: '^[A-Za-z][0-9][A-Za-z0-9](?:\.?[A-Za-z0-9]{1,4})?$'}
                    procedureCodes:
                      type: array
                      maxItems: 100
                      items: {type: string, pattern: '^[A-Za-z0-9]{7}$'}
                    codingComplete:
                      type: boolean
                      description: Confirm that all inpatient diagnosis and procedure codes were supplied. False requires review.
                hasOrganAcquisition:
                  type: boolean
                  description: Explicitly identify whether organ acquisition costs apply. True without complete acquisition facts returns a review result.
                organAcquisition:
                  type: object
                  additionalProperties: false
                  required: [organ, approvedTransplantCenter, documentedPaidCostCents, billedProcurementChargesCents]
                  description: Only supply when hasOrganAcquisition is true. Separate documented procurement reimbursement requires an approved transplant center. California outlier cost retains eligible procurement charges; the incorporated federal technology calculation excludes billed procurement charges from its operating cost basis.
                  properties:
                    organ:
                      type: string
                      enum: [heart, kidney, liver, lung, pancreas, intestine, multivisceral]
                    approvedTransplantCenter: {type: boolean}
                    documentedPaidCostCents:
                      type: integer
                      minimum: 0
                      maximum: 100000000000
                      description: Documented amount paid to procure the organ; not billed acquisition charges.
                    billedProcurementChargesCents:
                      type: integer
                      minimum: 0
                      maximum: 100000000000
                      description: Procurement charges included in coveredInpatientChargesCents under revenue codes 081x except 0815 and 0819. Must not exceed the covered charge total. Removed only from the federal technology cost basis; never replaced by documented paid cost.
      responses:
        '200':
          description: A dated statutory maximum with calculation factors and citations, or an explicit unavailable reason without an allowance.
          content:
            application/json:
              example: {
                "data": {
                  "status": "priced",
                  "effectiveFrom": "2024-12-01",
                  "effectiveThrough": "2025-11-30",
                  "dischargeDate": "2025-02-05",
                  "hospitalProviderNumber": "050002",
                  "hospital": {
                    "composite": "16078.21",
                    "costToChargeRatio": "0.244",
                    "name": "St Rose Hospital",
                    "outlierFactor": "68427.78",
                    "soleCommunityAdjusted": false
                  },
                  "drg": "470",
                  "drgFactors": {
                    "geometricMeanLos": "1.7",
                    "payable": true,
                    "weight": "1.8855"
                  },
                  "lengthOfStay": 4,
                  "coveredInpatientChargesCents": 5000000,
                  "ordinaryMaximumCents": 3637856,
                  "perDiemCents": 2139915,
                  "baseMaximumCents": 3637856,
                  "estimatedCostsCents": 1220000,
                  "outlierThresholdCents": 10480634,
                  "outlierAllowanceCents": 0,
                  "totalMaximumCents": 3637856,
                  "sources": [
                    {
                      "sha256": "adc6ab7c7b4af76736a8530d1b83755ee9381426766b6d177ea6cfcb8eb728f0",
                      "sheet": "FY 2025 Section9789.23",
                      "url": "https://www.dir.ca.gov/dwc/FeeSchedules/InpatientHospital_FeeSchedule/2024/9789_23.xlsx"
                    },
                    {
                      "sha256": "fbc661409a2be2093cf019e4d556b1be437f6f10893ce9b59867ba69675002a6",
                      "sheet": "FY 2025 Section9789.24",
                      "url": "https://www.dir.ca.gov/dwc/FeeSchedules/InpatientHospital_FeeSchedule/2024/9789_24.xlsx"
                    },
                    {
                      "sha256": "d8593ecc5092be405887c2576bcdc30215b115cb47c200eca5d57c1f2e5e7f29",
                      "sheet": "Adopted regulations, §§9789.20–9789.25",
                      "url": "https://www.dir.ca.gov/dwc/FeeSchedules/InpatientHospital_FeeSchedule/2024/Text-of-regulations/Text-of-Regulations-clean.docx"
                    }
                  ],
                  "citations": [
                    "https://www.dir.ca.gov/t8/9789_20.html",
                    "https://www.dir.ca.gov/t8/9789_21.html",
                    "https://www.dir.ca.gov/t8/9789_22.html"
                  ],
                  "explanation": [
                    {
                      "description": "Select hospital factors and DRG weights by discharge date.",
                      "citation": "https://www.dir.ca.gov/t8/9789_20.html"
                    },
                    {
                      "description": "16078.21 hospital composite × 1.8855 DRG weight × 120%. The published composite already includes applicable hospital adjustments.",
                      "citation": "https://www.dir.ca.gov/t8/9789_21.html"
                    },
                    {
                      "description": "Covered inpatient charges × 0.244 cost-to-charge ratio. Add 80% of costs above the applicable outlier threshold.",
                      "citation": "https://www.dir.ca.gov/t8/9789_22.html"
                    },
                    {
                      "description": "The global hospital amount includes spinal devices for these discharge dates. Physician services and home-use durable medical equipment use their separate schedules.",
                      "citation": "https://www.dir.ca.gov/t8/9789_22.html"
                    }
                  ]
                }
              }
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: object
                    required: [status, citations]
                    properties:
                      status: {type: string, enum: [priced, unavailable]}
                      code: {type: string, description: Present when unavailable.}
                      reason: {type: string, description: Present when unavailable; explains the missing data or separate determination.}
                      effectiveFrom: {type: string, format: date}
                      effectiveThrough: {type: string, format: date}
                      dischargeDate: {type: string, format: date}
                      hospitalProviderNumber: {type: string}
                      hospital:
                        type: object
                        properties:
                          name: {type: string}
                          composite: {type: string, description: Published hospital composite in dollars.}
                          outlierFactor: {type: string, description: Published outlier factor in dollars.}
                          costToChargeRatio: {type: string}
                          soleCommunityAdjusted: {type: boolean}
                      drg: {type: string}
                      drgFactors:
                        type: object
                        properties:
                          payable: {type: boolean}
                          weight: {type: string}
                          geometricMeanLos: {type: string}
                      lengthOfStay: {type: integer, minimum: 1, description: Inpatient days used in the calculation.}
                      calendarLengthOfStay: {type: integer, minimum: 1, description: Admission-to-discharge calendar difference, with a one-day minimum.}
                      lengthOfStaySource: {type: string, enum: [actual_inpatient_days, calendar_dates], description: Whether the calculation used a supplied actual count or the calendar default.}
                      coveredInpatientChargesCents: {type: integer}
                      immunotherapyAdjustmentFactor:
                        type: string
                        enum: ["1", "0.16"]
                        description: Weight adjustment applied to both operating and capital payment components for DRG 018; one for other DRGs.
                      ordinaryMaximumCents: {type: integer}
                      perDiemCents: {type: integer}
                      baseMaximumCents: {type: integer}
                      estimatedCostsCents: {type: integer}
                      outlierThresholdCents: {type: integer}
                      outlierAllowanceCents: {type: integer}
                      newTechnologyAllowanceCents: {type: integer, description: Sum of eligible new-technology add-on payments; zero when absent.}
                      newTechnology:
                        type: object
                        properties:
                          operatingCostToChargeRatio: {type: string}
                          items:
                            type: array
                            items:
                              type: object
                              properties:
                                id: {type: string}
                                label: {type: string}
                                percentage: {type: integer, enum: [65, 75]}
                                maximumCents: {type: integer}
                                allowanceCents: {type: integer}
                      roundingAdjustmentCents: {type: integer, description: Reconciles individually rounded components with the final maximum rounded once. Includes no additional fee.}
                      deviceCreditDeductionCents: {type: integer, description: Actual qualifying replacement-device credit deducted once from final reimbursement; zero when absent or ineligible.}
                      organAcquisitionAllowanceCents: {type: integer, description: Separate documented paid procurement cost; zero when absent.}
                      totalMaximumCents: {type: integer, description: Present only when priced. Statutory maximum before negotiated contract terms.}
                      explanation:
                        type: array
                        items:
                          type: object
                          required: [description, citation]
                          properties:
                            description: {type: string}
                            citation: {type: string, format: uri}
                      sources:
                        type: array
                        items:
                          type: object
                          required: [url, sha256, sheet]
                          properties:
                            url: {type: string, format: uri}
                            sha256: {type: string}
                            sheet: {type: string}
                      citations: {type: array, items: {type: string, format: uri}}
        '422':
          description: Invalid dates, identifiers, charges, missing explicit circumstances, or unexpected request fields.
        '403':
          description: Missing bills:read permission or treatmentBilling capability.
        default:
          $ref: '#/components/responses/Problem'
  /fee-quotes/pharmacy/compound:
    post:
      tags:
      - Bills
      operationId: quoteCaCompoundPharmacyFee
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        requiredCapability: treatmentBilling
      summary: Calculate a California compounded-prescription maximum
      description: Quotes prescriptions dispensed on or after July 1, 2025 using activated, dated pharmacy sources
        and caller-supplied regulatory findings. Pharmacy and physician rules differ; authorization, essential-copy,
        NDC validity and documentation findings are required context, not inferred eligibility. Missing sources or
        unresolved rules return requires_review without an amount. All monetary fields are integer cents except ingredient
        unitCostInHundredThousandths, which is 1/100000 dollars per metric unit. Container counts are limited by the
        applicable route. This quote does not establish coverage, authorization or payment, and does not create a
        bill. Credentials select sandbox or live; there is no request environment override. Browser sessions require
        the exact allowed Origin. Explicit single-drug sterile transfers are supported for pharmacy injection/infusion
        from September 1, 2026, the earliest reviewed manual edition; earlier transfers require review. This is
        a pricing classification and does not establish federal compounding status.
      requestBody:
        required: true
        content:
          application/json:
            example:
              dateOfService: '2026-09-16'
              dispenser: pharmacy
              pharmacyNpi: '1234567893'
              route: Oral
              dosageForm: '01'
              compoundMetricQuantity: '30'
              containerCount: 1
              ingredients:
              - ndcNumber: '00000000001'
                metricQuantity: '10'
                billedIngredientCents: 1200
                ndcStatus: valid
                productCategory: drug
                noSubstitution: false
              - ndcNumber: '00000000002'
                metricQuantity: '20'
                billedIngredientCents: 1800
                ndcStatus: valid
                productCategory: drug
                noSubstitution: false
              billedCents: 5000
              usualCustomaryCents: 5000
              billedCompoundingFeeCents: 395
              billedSterilityFeeCents: 0
              authorizationStatus: authorized
              essentialCopyStatus: not_essential_copy
              sterilityTesting: not_performed
            schema:
              type: object
              additionalProperties: false
              required:
              - dateOfService
              - dispenser
              - route
              - dosageForm
              - compoundMetricQuantity
              - containerCount
              - ingredients
              - billedCents
              - billedCompoundingFeeCents
              - billedSterilityFeeCents
              - authorizationStatus
              - essentialCopyStatus
              - sterilityTesting
              oneOf:
              - properties:
                  preparationKind: {const: compound}
                  ingredients: {minItems: 2}
                not:
                  required: [sterileTransferRequirementsSatisfied]
              - required: [preparationKind]
                properties:
                  preparationKind: {const: sterile_transfer}
                  dispenser: {const: pharmacy}
                  route: {enum: [Injection, Infusion]}
                  ingredients: {minItems: 1, maxItems: 1}
              properties:
                preparationKind:
                  type: string
                  enum: [compound, sterile_transfer]
                  description: Omission means ordinary compound with at least two actual drug ingredients. Sterile transfer requires exactly one actual drug NDC and separate containerCount; never include the container marker as an ingredient.
                sterileTransferRequirementsSatisfied:
                  type: boolean
                  description: Required true for a transfer quote. Documented pharmacist findings that this is an eligible, lawfully prepared, patient-specific dispensed sterile transfer under the incorporated methodology. Excludes manufacturer-packaged simple products, bedside immediate preparation, and omitted additional ingredients. Does not replace authorization, NDC or essential-copy findings. Only accepted with preparationKind sterile_transfer.
                dateOfService:
                  type: string
                  format: date
                  description: Actual dispensing date. Dates before July 1, 2025 require review.
                dispenser:
                  type: string
                  enum:
                  - pharmacy
                  - physician
                pharmacyNpi:
                  type: string
                  pattern: ^\d{10}$
                  description: Required to price pharmacy dispensing; determines dated dispensing-fee tier.
                route:
                  type: string
                  enum:
                  - Buccal
                  - Dental
                  - Enteral
                  - Infusion
                  - Inhalation
                  - Injection
                  - Intraperitoneal
                  - Irrigation
                  - Mouth/Throat
                  - Mucous Membrane
                  - Nasal
                  - Ophthalmic
                  - Oral
                  - Other/Miscellaneous
                  - Otic
                  - Rectal
                  - Sublingual
                  - Topical
                  - Transdermal
                  - Translingual
                  - Urethral
                  - Vaginal
                dosageForm:
                  type: string
                  enum:
                  - '01'
                  - '02'
                  - '03'
                  - '04'
                  - '05'
                  - '06'
                  - '07'
                  - '10'
                  - '11'
                  - '12'
                  - '13'
                  - '14'
                  - '15'
                  - '16'
                  - '17'
                  - '18'
                compoundMetricQuantity:
                  type: string
                  pattern: ^(?:0|[1-9]\d{0,6})(?:\.\d{1,3})?$
                  description: NCPDP metric decimal quantity greater than zero and at most 9999999; up to three decimal
                    places. No package conversion or rounding is inferred. Total finished-product claim quantity,
                    not the sum of unlike ingredient units.
                containerCount:
                  type: integer
                  minimum: 1
                  maximum: 10000
                ingredients:
                  type: array
                  minItems: 1
                  maxItems: 25
                  description: Each NDC occurs once. Combine its total quantity and charge across containers. NDC
                    validity and product eligibility are explicit regulatory findings, not inferred from price-file
                    presence.
                  items:
                    type: object
                    additionalProperties: false
                    required:
                    - ndcNumber
                    - metricQuantity
                    - billedIngredientCents
                    - ndcStatus
                    - productCategory
                    - noSubstitution
                    properties:
                      ndcNumber:
                        type: string
                        pattern: ^\d{11}$
                        not:
                          const: '99999999997'
                        description: Unique ingredient NDC. Container marker 99999999997 is not allowed.
                      metricQuantity:
                        type: string
                        pattern: ^(?:0|[1-9]\d{0,6})(?:\.\d{1,3})?$
                        description: NCPDP metric decimal quantity greater than zero and at most 9999999; up to three
                          decimal places. No package conversion or rounding is inferred. Total ingredient quantity
                          across all containers.
                      billedIngredientCents: &id002
                        type: integer
                        minimum: 0
                        maximum: 100000000
                      ndcStatus:
                        type: string
                        enum:
                        - valid
                        - invalid
                        - unresolved
                      productCategory:
                        type: string
                        enum:
                        - drug
                        - excluded_product
                        - unresolved
                      noSubstitution: &id001
                        type: boolean
                      noSubstitutionRequirementsSatisfied: *id001
                      documentedPaidCostCents:
                        type: integer
                        minimum: 0
                        maximum: 100000000
                        description: Total ingredient acquisition cost net of discounts and rebates; required for
                          physician dispensing.
                billedCents: *id002
                usualCustomaryCents:
                  type: integer
                  minimum: 0
                  maximum: 100000000
                  description: Required for physician dispensing and pharmacy dispensing on or after July 18, 2025.
                    Pharmacy usual/customary amount must be positive when applicable.
                billedCompoundingFeeCents:
                  type: integer
                  minimum: 0
                  maximum: 100000000
                  description: Total billed compounding fee across the entire prescription.
                billedSterilityFeeCents:
                  type: integer
                  minimum: 0
                  maximum: 100000000
                  description: Total billed sterility fee across the entire prescription.
                authorizationStatus:
                  type: string
                  enum:
                  - authorized
                  - not_authorized
                  - unresolved
                essentialCopyStatus:
                  type: string
                  enum:
                  - not_essential_copy
                  - essential_copy
                  - unresolved
                sterilityTesting:
                  type: string
                  enum:
                  - performed_records_retained
                  - not_performed
                  - unresolved
                physicianDispensingRequirementsSatisfied: *id001
                acquisitionAndAuthorizationDocumentationIncluded: *id001
                physicianSterileCompoundingRequirementsSatisfied: *id001
      responses:
        '200':
          description: 'A matched regulatory maximum with ingredient breakdown, or an explicit review reason. Responses
            use Cache-Control: no-store.'
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required:
                - data
                properties:
                  data:
                    oneOf:
                    - type: object
                      additionalProperties: false
                      required:
                      - status
                      - maximumCents
                      - amountCents
                      - ingredientCostCents
                      - allowedContainerCount
                      - dispensingFeePerContainerCents
                      - dispensingFeeCents
                      - compoundingFeeCents
                      - sterilityFeeCents
                      - scheduleMaximumCents
                      - ingredients
                      - usualCustomaryCapApplied
                      - rateBasis
                      - paymentStatus
                      - eligibilityBasis
                      - provenance
                      properties:
                        status:
                          type: string
                          const: matched
                        maximumCents:
                          type: integer
                          minimum: 0
                          description: Maximum after applicable usual/customary and physician acquisition caps.
                        amountCents:
                          type: integer
                          minimum: 0
                          description: Lesser of maximumCents and billedCents. Does not establish payment entitlement.
                        ingredientCostCents: &id003
                          type: integer
                          minimum: 0
                        allowedContainerCount: *id003
                        dispensingFeePerContainerCents: *id003
                        dispensingFeeCents: *id003
                        compoundingFeeCents: *id003
                        sterilityFeeCents: *id003
                        scheduleMaximumCents:
                          type: integer
                          minimum: 0
                          description: Ingredient plus allowed dispensing, compounding and sterility fees before usual/customary
                            and physician acquisition caps.
                        paidCostTripleCapCents: *id003
                        paidCostPlusTwentyCapCents: *id003
                        ingredients:
                          type: array
                          items:
                            type: object
                            additionalProperties: false
                            required:
                            - ndcNumber
                            - metricQuantity
                            - billedIngredientCents
                            - allowedIngredientCents
                            - ndcStatus
                            - priceBasis
                            properties:
                              ndcNumber:
                                type: string
                              metricQuantity:
                                type: string
                              billedIngredientCents: *id003
                              allowedIngredientCents: *id003
                              ndcStatus:
                                type: string
                                enum:
                                - valid
                                - invalid
                              unitCostInHundredThousandths: *id003
                              effectiveFrom:
                                type: string
                                format: date
                              priceBasis:
                                type: string
                                enum:
                                - lowest_cost
                                - no_substitution
                                - invalid_ndc_not_reimbursable
                        usualCustomaryCapApplied: *id001
                        rateBasis:
                          type: string
                          const: ca_compounded_dispensed_drug
                        paymentStatus:
                          type: string
                          const: not_determined
                        eligibilityBasis:
                          type: string
                          const: caller_supplied_regulatory_findings
                        provenance: &id004
                          type: array
                          items:
                            type: object
                            additionalProperties: false
                            required:
                            - id
                            - url
                            properties:
                              id:
                                type: string
                              url:
                                type: string
                                format: uri
                              sha256:
                                type: string
                              effectiveFrom:
                                type: string
                                format: date
                              effectiveThrough:
                                type: string
                                format: date
                    - type: object
                      additionalProperties: false
                      required:
                      - status
                      - reason
                      - provenance
                      properties:
                        status:
                          type: string
                          const: requires_review
                        reason:
                          type: string
                        provenance: *id004
        '422':
          description: 'Invalid input, unknown fields or duplicate ingredient NDCs: invalid_compound_pharmacy_quote.'
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        default:
          $ref: '#/components/responses/Problem'
  /fee-quotes/pharmacy:
    post:
      tags:
      - Bills
      operationId: quoteCaPharmacyFee
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        requiredCapability: treatmentBilling
      summary: Calculate a California dispensed-drug maximum
      description: Uses reviewed weekly NDC history and dated pharmacy dispensing eligibility. Returns a maximum only; coding,
        authorization, coverage and claim submission are separate. Repackaged products use the actual original labeler NDC.
        An unlisted simple pharmacy-dispensed drug can use documented dated Wholesale Acquisition Cost (WAC).
        Compounds use the separate compound endpoint. Physician-administered drugs and products missing required therapeutic-equivalence evidence
        require review here. Historical quotes from March 8 2019 through June 30 2025 support only direct-listed simple pharmacy-dispensed prescription drugs with historicalContext and billedCents. Historical compounds, repackaged products, physician dispensing, missing or conflicting prices, and exact half-cent rounding ties require review. Historical inputs are quote-only. Source changes or stale review prevent quoting, including WAC quotes.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required:
              - ndcNumber
              - dateOfService
              - dispenser
              - productKind
              - metricQuantity
              - usualCustomaryCents
              - noSubstitution
              properties:
                ndcNumber:
                  type: string
                  pattern: ^[0-9]{11}$
                originalNdcNumber:
                  type: string
                  pattern: ^[0-9]{11}$
                  description: Actual original labeler product used by the repackager; required for repackaged products and distinct from the dispensed NDC.
                dateOfService:
                  type: string
                  format: date
                  description: Actual dispensing date; historical support begins March 8 2019 and requires historicalContext.
                dispenser:
                  type: string
                  enum:
                  - physician
                  - pharmacy
                productKind:
                  type: string
                  enum:
                  - simple
                  - repackaged
                  - compound
                  - physician_administered
                  description: Simple and repackaged dispensing are priced; compounds and physician-administered products use separate rules.
                metricQuantity:
                  type: string
                  pattern: ^(?:0|[1-9][0-9]{0,4})(?:\.[0-9]{1,3})?$
                  description: Total NCPDP metric decimal units, greater than zero and at most 10000; not package count.
                usualCustomaryCents:
                  type: integer
                  minimum: 0
                  maximum: 100000000
                  description: Total usual and customary public charge, including dispensing.
                billedCents:
                  type: integer
                  minimum: 0
                  maximum: 100000000
                pharmacyNpi:
                  type: string
                  pattern: ^[0-9]{10}$
                  description: Required for pharmacy dispensing. Dated active eligibility selects $13.20; otherwise $10.05. Physicians receive at most $10.05.
                noSubstitution:
                  type: boolean
                noSubstitutionRequirementsSatisfied:
                  type: boolean
                  description: Affirms brand DAW and applicable BPC and 9792.27.7 requirements; physicians also satisfy 9792.27.8.
                physicianDispensingRequirementsSatisfied:
                  type: boolean
                  description: Physician dispensing satisfies Business and Professions Code 4170; required true for physician
                    dispensing.
                physicianPaidForDrug:
                  type: boolean
                  description: Physician acquired the drug for payment, not a free sample; required true for physician dispensing.
                documentedPaidCostCents:
                  type: integer
                  minimum: 0
                  maximum: 100000000
                  description: Total net amount actually paid for dispensed nonlegend drug, after discounts and rebates.
                acquisitionDocumentationIncluded:
                  type: boolean
                  description: Invoice, proof of payment and required inventory documentation accompany physician nonlegend
                    bill.
                historicalContext:
                  type: object
                  additionalProperties: false
                  required: [patientInSkilledNursingOrIntermediateCare]
                  description: Quote-only facts for March 8 2019 through June 30 2025. Documented prescription-drug classification and billedCents are required for a matched quote; no classification is inferred from current FDA data or the historical label.
                  properties:
                    patientInSkilledNursingOrIntermediateCare:
                      type: boolean
                      description: Selects the historical $8 dispensing fee when true, otherwise $7.25.
                    prescriptionIndicatesNoSubstitution:
                      type: boolean
                      description: Must be true when noSubstitution is true.
                    classification:
                      type: object
                      additionalProperties: false
                      required: [ndcNumber, effectiveFrom, effectiveThrough, kind, documentationConfirmed]
                      properties:
                        ndcNumber:
                          type: string
                          pattern: ^[0-9]{11}$
                        effectiveFrom:
                          type: string
                          format: date
                        effectiveThrough:
                          type: string
                          format: date
                        kind:
                          type: string
                          enum: [prescription_drug, nonprescription_drug, device, unverified]
                        documentationConfirmed:
                          type: boolean
                          description: Must be true, with a matching NDC and interval covering the dispensing date.
                wholesaleAcquisitionCost:
                  type: object
                  additionalProperties: false
                  description: Optional documented WAC per metric unit under section 9789.40.5(c), only for simple pharmacy-dispensed drugs absent from the dated PFS. Published rates take precedence. Caller evidence is not independently verified; the dispensing fee, usual charge and billed caps still apply. Not available in bill pricing context.
                  required: [ndcNumber, unitPrice, effectiveFrom, effectiveThrough, sourceUrl, documentationConfirmed, notIncludedInOtherPayment]
                  properties:
                    ndcNumber:
                      type: string
                      pattern: ^[0-9]{11}$
                      description: Must equal the actual dispensed NDC.
                    unitPrice:
                      type: string
                      pattern: ^(?:0|[1-9][0-9]{0,5})(?:\.[0-9]{1,5})?$
                      description: Dollars per metric unit, not package price or acquisition cost.
                    effectiveFrom:
                      type: string
                      format: date
                    effectiveThrough:
                      type: string
                      format: date
                      description: Inclusive documented interval must cover the dispensing date.
                    sourceUrl:
                      type: string
                      format: uri
                      maxLength: 2000
                      description: HTTPS evidence reference; do not include patient data or access tokens.
                    documentationConfirmed:
                      type: boolean
                      description: Must be true to use this evidence.
                    notIncludedInOtherPayment:
                      type: boolean
                      description: Drug is not covered by or bundled into a facility or physician fee-schedule payment; must be true.
      responses:
        '200':
          description: A dated maximum or a reason requiring review.
          content:
            application/json:
              schema:
                type: object
                required:
                - data
                properties:
                  data:
                    type: object
                    required:
                    - status
                    - provenance
                    properties:
                      status:
                        type: string
                        enum:
                        - matched
                        - requires_review
                      maximumCents:
                        type: integer
                      amountCents:
                        type: integer
                      ingredientCostCents:
                        type: integer
                      dispensingFeeCents:
                        type: integer
                      ingredientEffectiveFrom:
                        type: string
                        format: date
                      legend:
                        type: [boolean, 'null']
                        description: Null when caller-documented WAC supplies no authoritative legend classification.
                      rateBasis:
                        type: string
                        enum: [ca_simple_dispensed_drug, ca_repackaged_original_ndc, ca_pharmacy_documented_wac, ca_historical_simple_pharmacy]
                      historicalDetails:
                        type: object
                        description: Historical source row references, exact decimal ingredient and schedule amounts, selected price field, and caller-documented classification basis. Present only for matched historical quotes.
                      originalNdcNumber:
                        type: string
                        pattern: ^[0-9]{11}$
                      paymentStatus:
                        type: string
                        const: not_determined
                      reason:
                        type: string
                      provenance:
                        type: array
                        items:
                          type: object
        default:
          $ref: '#/components/responses/Problem'
  /fee-quotes/owcp:
    post:
      tags:
      - Bills
      operationId: quoteOwcpFee
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        requiredCapability: treatmentBilling
      summary: Look up an OWCP physician unit maximum
      description: Uses dated OWCP data and exact server-owned postal locality. The result is an unadjusted single-service maximum,
        not a payable allowance or a determination of coding eligibility. Program-specific rules and unavailable context may
        require review.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required:
              - code
              - dateOfService
              properties:
                code:
                  type: string
                  pattern: ^[A-Za-z0-9]{5}$
                dateOfService:
                  type: string
                  format: date
                postalCode:
                  type: string
                  pattern: ^[0-9]{5}(?:-[0-9]{4})?$
                placeOfService:
                  type: string
                  pattern: ^[0-9]{2}$
                modifiers:
                  type: array
                  maxItems: 4
                  items:
                    type: string
                    pattern: ^[A-Z0-9]{2}$
                program:
                  type: string
                  enum:
                  - FECA
                  - ENERGY
                  - BLACK_LUNG
      responses:
        '200':
          description: Matched unadjusted unit maximum, unmatched code, or a reason requiring review.
          content:
            application/json:
              schema:
                type: object
                required:
                - data
                properties:
                  data:
                    type: object
                    required:
                    - status
                    properties:
                      status:
                        type: string
                        enum:
                        - matched
                        - requires_review
                        - unmatched
                      unitMaximumCents:
                        type: integer
                      rateBasis:
                        type: string
                        const: unadjusted_single_service_maximum
                      paymentStatus:
                        type: string
                        const: not_determined
                      reason:
                        type: string
                      locality:
                        type: string
                      setting:
                        type: string
                        enum:
                        - facility
                        - nonfacility
                      globalDays:
                        type: string
                      provenance:
                        type: object
        default:
          $ref: '#/components/responses/Problem'
  /fee-quotes/owcp/ancillary:
    post:
      tags:
      - Bills
      operationId: quoteOwcpAncillaryFee
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        requiredCapability: treatmentBilling
      summary: Look up an OWCP lab, DME or physician-administered drug maximum
      description: Uses reviewed dated OWCP tables and an exact code and modifier match. Whole HCPCS billing units are extended before rounding to cents, preserving fractional-cent drug rates. Units are not milligrams or milliliters; consult dosagePerBillingUnit for drugs. Returns a published schedule maximum, not a coverage decision or payable allowance. Zero rates, unsupported modifiers, missing editions and source review holds require review. Never accepts caller rates or an environment override. Sandbox or live data selection follows the authenticated credential.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [category, code, dateOfService]
              properties:
                category:
                  type: string
                  enum: [clinical_lab, dmepos, padb]
                code:
                  type: string
                  pattern: ^[A-Za-z0-9]{5}$
                dateOfService:
                  type: string
                  format: date
                modifiers:
                  type: array
                  maxItems: 4
                  items:
                    type: string
                    pattern: ^[A-Z0-9]{2}$
                units:
                  type: integer
                  minimum: 1
                  maximum: 1000000
                  default: 1
                  description: Whole published HCPCS billing units, not drug milligrams or milliliters.
            example:
              category: padb
              code: '90656'
              dateOfService: '2026-09-08'
              units: 2
      responses:
        '200':
          description: Exact published maximum or a reason requiring review; no-store response.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: object
                    required: [status]
                    properties:
                      status:
                        type: string
                        enum: [matched, requires_review, unmatched]
                      reason:
                        type: string
                      category:
                        type: string
                        enum: [clinical_lab, dmepos, padb]
                      code:
                        type: string
                      modifier:
                        type: string
                      unitMaximumDollars:
                        type: string
                        description: Exact source decimal dollars, retaining fractional cents.
                      units:
                        type: integer
                      extendedMaximumCents:
                        type: integer
                        description: Exact unit rate multiplied by whole billing units, rounded half up once to cents.
                      dosagePerBillingUnit:
                        type: [string, 'null']
                      rateBasis:
                        type: string
                        const: published_schedule_maximum
                      paymentStatus:
                        type: string
                        const: not_determined
                      provenance:
                        type: object
        default:
          $ref: '#/components/responses/Problem'
  /sandbox/dental-bills/{id}/simulate:
    post:
      tags:
      - Dental drafts
      operationId: simulateDentalSandboxReceipt
      summary: Simulate dental acceptance, rejection or payment
      description: Sandbox only, treatmentBilling required, exact Origin for browser sessions, organization-wide sessions only.
        No external transmission or production accounting. New York CMS-1500/CDT/SOAP preparations support this simulated lifecycle; historical NY ADA/837D snapshots remain blocked.
        Stable preparation line IDs identify payments; historical preparations without a snapshot require refresh. Receipt IDs
        deduplicate across HTTP keys; changed receipt content conflicts. Payments require accepted/partially_paid status, distinct
        known line IDs and no overpayment. Rejected and paid statuses are terminal. Unknown fields and query parameters reject.
        Mutations require Idempotency-Key. Simulated paid is not payer payment evidence.
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      x-mindbill-access:
        serverScope: bills:submit
        browserPermission: bills:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      parameters:
      - name: id
        in: path
        required: true
        schema:
          type: string
          pattern: ^[A-Za-z0-9_-]{1,255}$
      - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '200':
          description: Current simulated dental bill. Reusing a preparation returns its existing bill.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DentalSandboxBillResponse'
        default:
          $ref: '#/components/responses/Problem'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SimulateDentalSandboxReceipt'
  /organizations/{id}/charge-schedules:
    parameters:
    - name: id
      in: path
      required: true
      schema:
        type: string
    get:
      tags:
      - Platform
      operationId: listChargeSchedules
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      x-mindbill-access:
        serverScope: orgs:read
        browserPermission: organization:manage
      summary: List dated practice charges and contracted rates
      responses:
        '200':
          description: Schedules in the authorized organization and credential environment, including inactive historical versions.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/ChargeSchedule'
        default:
          $ref: '#/components/responses/Problem'
    post:
      tags:
      - Platform
      operationId: createChargeSchedule
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      x-mindbill-access:
        serverScope: orgs:write
        browserPermission: organization:manage
      summary: Create a dated practice charge or payer contract
      description: Definitions are immutable and auditable. Overlapping active entries return 409. Deactivate the prior definition
        before replacing it. Contracted rates require a canonical payer ID. Percentage entries use the official one-unit maximum;
        missing official rates are never converted into a payable estimate.
      parameters:
      - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChargeScheduleInput'
      responses:
        '201':
          description: Created schedule.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/ChargeSchedule'
        default:
          $ref: '#/components/responses/Problem'
  /sandbox/dental-bills:
    post:
      tags:
      - Dental drafts
      operationId: createDentalSandboxBill
      summary: Create a simulated dental bill
      description: Sandbox only, treatmentBilling required, exact Origin for browser sessions, organization-wide sessions only.
        No external transmission or production accounting. New York CMS-1500/CDT/SOAP preparations support this simulated lifecycle; historical NY ADA/837D snapshots remain blocked.
        Stable preparation line IDs identify payments; historical preparations without a snapshot require refresh. Receipt IDs
        deduplicate across HTTP keys; changed receipt content conflicts. Payments require accepted/partially_paid status, distinct
        known line IDs and no overpayment. Rejected and paid statuses are terminal. Unknown fields and query parameters reject.
        Mutations require Idempotency-Key. Simulated paid is not payer payment evidence.
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      x-mindbill-access:
        serverScope: bills:submit
        browserPermission: bills:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      parameters:
      - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '201':
          description: Current simulated dental bill. Reusing a preparation returns its existing bill.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DentalSandboxBillResponse'
        default:
          $ref: '#/components/responses/Problem'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateDentalSandboxBill'
  /dental-preparations/{id}:
    get:
      tags:
      - Dental drafts
      operationId: getDentalPreparationArtifact
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Download owned sandbox dental artifact
      description: Scoped to partner, organization and sandbox environment. Private no-store download. PDF is a watermarked
        ADA SAMPLE; EDI is X224A2 with ISA15=T. No transmission occurs.
      parameters:
      - name: id
        description: Owned dental draft or preparation ID.
        in: path
        required: true
        schema:
          type: string
          pattern: ^[A-Za-z0-9_-]{1,255}$
      - name: format
        description: Retained artifact format to download.
        in: query
        required: true
        schema:
          type: string
          enum:
          - edi
          - pdf
      responses:
        default:
          $ref: '#/components/responses/Problem'
        '200':
          description: Immutable artifact download.
          headers:
            Cache-Control:
              schema:
                type: string
                const: private, no-store
            Content-Disposition:
              schema:
                type: string
          content:
            application/edi-x12:
              schema:
                type: string
                format: binary
            application/pdf:
              schema:
                type: string
                format: binary
        '400':
          description: Problem response; validation, ownership, capability, sandbox restriction or revision conflict.
        '401':
          description: Problem response; validation, ownership, capability, sandbox restriction or revision conflict.
        '403':
          description: Problem response; validation, ownership, capability, sandbox restriction or revision conflict.
        '404':
          description: Problem response; validation, ownership, capability, sandbox restriction or revision conflict.
        '409':
          description: Problem response; validation, ownership, capability, sandbox restriction or revision conflict.
  /sandbox/dental-bills/{id}:
    get:
      tags:
      - Dental drafts
      operationId: getDentalSandboxBill
      summary: Read a simulated dental bill
      description: Sandbox only, treatmentBilling required, exact Origin for browser sessions, organization-wide sessions only.
        No external transmission or production accounting. New York CMS-1500/CDT/SOAP preparations support this simulated lifecycle; historical NY ADA/837D snapshots remain blocked.
        Stable preparation line IDs identify payments; historical preparations without a snapshot require refresh. Receipt IDs
        deduplicate across HTTP keys; changed receipt content conflicts. Payments require accepted/partially_paid status, distinct
        known line IDs and no overpayment. Rejected and paid statuses are terminal. Unknown fields and query parameters reject.
        Mutations require Idempotency-Key. Simulated paid is not payer payment evidence.
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      parameters:
      - name: id
        in: path
        required: true
        schema:
          type: string
          pattern: ^[A-Za-z0-9_-]{1,255}$
      responses:
        '200':
          description: Current simulated dental bill. Reusing a preparation returns its existing bill.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DentalSandboxBillResponse'
        default:
          $ref: '#/components/responses/Problem'
  /organizations/{id}/charge-schedules/{scheduleId}:
    parameters:
    - name: id
      in: path
      required: true
      schema:
        type: string
    - name: scheduleId
      in: path
      required: true
      schema:
        type: string
    delete:
      tags:
      - Platform
      operationId: deactivateChargeSchedule
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      x-mindbill-access:
        serverScope: orgs:write
        browserPermission: organization:manage
      summary: Deactivate a charge schedule while retaining its history
      parameters:
      - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '200':
          description: Deactivated schedule.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/ChargeSchedule'
        default:
          $ref: '#/components/responses/Problem'
  /dental-drafts/{id}/prepare:
    post:
      tags:
      - Dental drafts
      operationId: prepareDentalDraft
      x-mindbill-access:
        serverScope: bills:write
        browserPermission: bills:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Prepare immutable sandbox dental claim artifacts
      description: Sandbox only; never sends a claim or creates an ordinary bill. Requires explicit record-backed attestations
        matching the draft, exact revision and patient/provider/claim identity. Original employee WC claims only; CA/OWCP use X224A2 TEST and NY uses CMS-1500 with SOAP. Up to
        four ICD10 codes without dots and one-based line pointers; unique codes, pointers, teeth and surfaces. Birth <= injury
        <= service <= envelope date. Replacement prior placement must precede service; orthodontic placement must not be future
        and remaining months <= total. Distinct valid billing/rendering NPIs. Printable ASCII text excludes X12 delimiters *~:^
        and surrounding whitespace. Draft codes, diagnoses, anatomy, clinical assertions and charges must match claim; code
        edition must match service year. D5/D6 require prosthesis details; D8 requires orthodontic details. Unsupported claim variants reject. CA/OWCP
        reject attachments and by-report anatomy. Missing statutory/practice rates or authorization review yield requires_review.
        CA/OWCP PDFs retain the official ADA SAMPLE watermark; not a production filing form. Recorded ADA form details, optional for sandbox
        preparation. Omitted consent, certification, license, physical address or treating phone is reported in paperForm.missingFields.
        Consent/certification references identify existing source records; supplying a string does not independently verify
        the record. Consent dates must be between patient birth and envelope date. Direct-payment consent requires benefitsAssignment
        Y; provider certification must name the rendering dentist exactly, follow all service dates and require providerSignatureOnFile
        true. Physical address must not be a PO Box and must equal the billing address in the CA/OWCP EDI profile. Draft and
        claim ADA details must agree. Organizational billing provider license box50 stays blank. New York preparations require content.nyCms1500 with SOAP narrative and diagnosis pointers on every line, and produce
        a watermarked CMS-1500/CDT review packet with an immutable clinical snapshot. EDI artifact URL and hash are null;
        an EDI download request is rejected. Recorded consent and certification dates control signatures; omitted facts remain
        in paperForm.missingFields. NY permits a separate physical service address and clinical notes in the appendix.
        D9999 requires medical necessity. Procedure charges above $1,000, D9999 and schedule PAR flags require authorization
        review except documented emergencies. Live NY delivery through an approved XML partner is not implemented;
        paperForm.liveUseBlocked remains true. Historical NY ADA/837D artifacts reject with ny_dental_cms1500_required. New preparations retain encrypted immutable clinical snapshots for the
        dental sandbox bill lifecycle.
      parameters:
      - name: id
        description: Owned dental draft or preparation ID.
        in: path
        required: true
        schema:
          type: string
          pattern: ^[A-Za-z0-9_-]{1,255}$
      - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DentalPreparationRequest'
      responses:
        default:
          $ref: '#/components/responses/Problem'
        '201':
          description: Sandbox artifacts prepared; not transmitted.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DentalPreparationResponse'
        '400':
          description: Problem response; validation, ownership, capability, sandbox restriction or revision conflict.
        '401':
          description: Problem response; validation, ownership, capability, sandbox restriction or revision conflict.
        '403':
          description: Problem response; validation, ownership, capability, sandbox restriction or revision conflict.
        '404':
          description: Problem response; validation, ownership, capability, sandbox restriction or revision conflict.
        '409':
          description: Problem response; validation, ownership, capability, sandbox restriction or revision conflict.
        '422':
          description: Problem response; validation, ownership, capability, sandbox restriction or revision conflict.
  /dental-drafts:
    get:
      tags: [Dental drafts]
      operationId: listDentalDrafts
      x-mindbill-access: { serverScope: 'bills:read', browserPermission: 'bills:read', browserBillScoped: false, requiredCapability: treatmentBilling }
      summary: List dental drafts
      description: Lists manually entered drafts in the selected partner, organization and environment. Requires treatmentBilling. Browser sessions require bills:read and their exact allowed Origin; bill-scoped sessions are rejected. Keep filters unchanged while using nextCursor as afterId. Draft completeness does not establish coding, pricing or claim readiness.
      parameters:
        - { name: claimId, in: query, schema: { type: string, minLength: 1, maxLength: 255 } }
        - { name: status, in: query, schema: { type: string, enum: [draft, archived] } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 200, default: 50 } }
        - { name: afterId, in: query, schema: { type: string, minLength: 1, maxLength: 255 } }
      responses:
        '200':
          description: Stable ID-ordered page of scoped drafts.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DentalDraftPage' }
        default: { $ref: '#/components/responses/Problem' }
    post:
      tags: [Dental drafts]
      operationId: createDentalDraft
      x-mindbill-access: { serverScope: 'bills:write', browserPermission: 'bills:create', browserBillScoped: false, requiredCapability: treatmentBilling }
      summary: Save a dental draft
      description: Saves manual entries against an existing scoped claim, matching patient and active rendering provider. Incomplete drafts are allowed; unknown charges stay null. This cannot transmit a dental claim or validate CDT licensing, clinical coding, dental anatomy, prices or authorization. Requires treatmentBilling. Browser sessions require bills:create and their exact allowed Origin; bill-scoped sessions are rejected. Duplicate externalId returns a conflict.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateDentalDraft' }
      responses:
        '201':
          description: Created draft with revision and completeness review.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DentalDraftEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /dental-drafts/{id}:
    parameters:
      - $ref: '#/components/parameters/DentalDraftId'
    get:
      tags: [Dental drafts]
      operationId: getDentalDraft
      x-mindbill-access: { serverScope: 'bills:read', browserPermission: 'bills:read', browserBillScoped: false, requiredCapability: treatmentBilling }
      summary: Read a dental draft
      description: Reads a draft or archived record only in its owning partner, organization and environment. Requires treatmentBilling. Browser sessions require bills:read and their exact allowed Origin; bill-scoped sessions are rejected.
      responses:
        '200':
          description: Current draft, revision and unverified completeness report.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DentalDraftEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
    patch:
      tags: [Dental drafts]
      operationId: updateDentalDraft
      x-mindbill-access: { serverScope: 'bills:write', browserPermission: 'bills:act', browserBillScoped: false, requiredCapability: treatmentBilling }
      summary: Replace dental draft content
      description: Replaces the entire content object, including every intended service line. Omitted optional fields reset to their defaults; they are not merged with the prior content. Copy expectedRevision from a fresh read. Stale revisions or archived drafts return 409 without changes; claim and patient anchors cannot change. Requires treatmentBilling. Browser sessions require bills:act and their exact allowed Origin; bill-scoped sessions are rejected. Saving does not verify coding or enable transmission.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/UpdateDentalDraft' }
      responses:
        '200':
          description: Replaced content with the next revision.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DentalDraftEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /dental-drafts/{id}/archive:
    parameters:
      - $ref: '#/components/parameters/DentalDraftId'
    post:
      tags: [Dental drafts]
      operationId: archiveDentalDraft
      x-mindbill-access: { serverScope: 'bills:write', browserPermission: 'bills:act', browserBillScoped: false, requiredCapability: treatmentBilling }
      summary: Archive a dental draft
      description: Retains the content and audit history, increments the revision and prevents further editing. Requires the current expectedRevision; stale or already archived records return 409. Requires treatmentBilling. Browser sessions require bills:act and their exact allowed Origin; bill-scoped sessions are rejected. This operation does not cancel or transmit a claim.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ArchiveDentalDraft' }
      responses:
        '200':
          description: Retained archived draft with the next revision.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DentalDraftEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/transmissions/{transmissionId}/reconcile-fax:
    parameters:
      - $ref: '#/components/parameters/RfaId'
      - $ref: '#/components/parameters/RfaTransmissionId'
    post:
      tags: [Treatment Authorization]
      operationId: reconcileRfaFax
      x-mindbill-access: { serverScope: 'rfas:write', browserPermission: 'rfas:act', browserBillScoped: false, requiredCapability: treatmentBilling }
      summary: Reconcile an uncertain RFA fax attempt
      description: Associates the original live Telnyx attempt with a provider message ID after an authenticated provider lookup verifies its exact immutable dispatch marker, packet hash, sender, recipient and outbound direction. Requires treatmentBilling. Server API keys additionally require the operator role and rfas:write; organization browser sessions require rfas:act and their exact allowed Origin. Bill-scoped sessions are rejected. Copy expectedContentRevision and expectedUpdatedAt from a fresh RFA read; stale or conflicting evidence returns 409 without association. Historical attempts without a persisted marker and Sinch attempts remain manual review. This never sends another fax, creates a replacement attempt, establishes receipt or infers clinical approval. Refresh fax status separately for verified delivery evidence. Sandbox requests are rejected.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/RfaFaxReconciliation' }
      responses:
        '200':
          description: Original attempt associated with the verified provider message. Queued transmission becomes sent; draft or ready RFA becomes submitted without changing later or exception states.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/RfaFaxReconciliationEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /browser/rfas/{rfaId}/transmissions/{transmissionId}/reconcile-fax:
    parameters:
      - $ref: '#/components/parameters/BrowserOrigin'
      - $ref: '#/components/parameters/RfaId'
      - $ref: '#/components/parameters/RfaTransmissionId'
    post:
      tags: [Treatment Authorization]
      operationId: browserReconcileRfaFax
      x-mindbill-access: { browserPermission: 'rfas:act', browserBillScoped: false, requiredCapability: treatmentBilling }
      summary: Reconcile an uncertain RFA fax attempt
      description: Associates the original live Telnyx attempt with a provider message ID after an authenticated provider lookup verifies its exact immutable dispatch marker, packet hash, sender, recipient and outbound direction. Requires treatmentBilling. Server API keys additionally require the operator role and rfas:write; organization browser sessions require rfas:act and their exact allowed Origin. Bill-scoped sessions are rejected. Copy expectedContentRevision and expectedUpdatedAt from a fresh RFA read; stale or conflicting evidence returns 409 without association. Historical attempts without a persisted marker and Sinch attempts remain manual review. This never sends another fax, creates a replacement attempt, establishes receipt or infers clinical approval. Refresh fax status separately for verified delivery evidence. Sandbox requests are rejected.
      security: [{ browserSessionAuth: [] }]
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/RfaFaxReconciliation' }
      responses:
        '200':
          description: Original attempt associated with the verified provider message. Queued transmission becomes sent; draft or ready RFA becomes submitted without changing later or exception states.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/RfaFaxReconciliationEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /notifications/recipients:
    parameters:
      - $ref: '#/components/parameters/NotificationOrganization'
      - name: offset
        in: query
        schema: { type: integer, minimum: 0, maximum: 100000, default: 0 }
    get:
      tags: [Notifications]
      operationId: listNotificationRecipients
      security: [{ bearerAuth: [] }]
      x-mindbill-access: { serverScope: 'orgs:write' }
      summary: List notification recipients and pending confirmations
      description: |
        Server-only, managed-organization and key-environment scoped. Returns up to 100
        recipients per page, including disabled recipients so consent can be revoked while
        delivery is unavailable. Never returns confirmation tokens. Providing an address
        does not itself enroll a recipient. Advance offset by 100 while hasMore is true.
      responses:
        '200':
          description: Recipient settings and confirmation states.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: object
                    required: [available, environment, hasMore, recipients]
                    properties:
                      available: { type: boolean }
                      environment: { enum: [sandbox, live] }
                      hasMore: { type: boolean }
                      recipients:
                        type: array
                        items:
                          type: object
                          required: [externalUserId, email, audience, statusUpdates, agingDays, quietHours, enabled, assignedBillCount, state]
                          properties:
                            externalUserId: { type: string }
                            email: { type: string, format: email }
                            audience: { enum: [practice, assigned_bills] }
                            statusUpdates: { type: boolean }
                            statusEvents: { $ref: '#/components/schemas/NotificationStatusEvents' }
                            agingDays: { type: array, items: { enum: [30, 60, 90] } }
                            quietHours: { type: boolean }
                            enabled: { type: boolean }
                            assignedBillCount: { type: integer, minimum: 0 }
                            state: { enum: [active, unavailable, pending_confirmation, expired, off] }
                            deliveryStatus: { enum: [sandbox_preview, sending, sent, unknown, suppressed] }
                            expiresAt: { type: string, format: date-time }
        default: { $ref: '#/components/responses/Problem' }
  /notifications/recipients/{externalUserId}/invitations:
    parameters:
      - $ref: '#/components/parameters/NotificationExternalUserId'
      - $ref: '#/components/parameters/NotificationOrganization'
    post:
      tags: [Notifications]
      operationId: createNotificationInvitation
      security: [{ bearerAuth: [] }]
      x-mindbill-access: { serverScope: 'orgs:write' }
      summary: Invite an email recipient to confirm notification consent
      description: |
        Server-only, managed-organization and key-environment scoped. The recipient must
        review and explicitly confirm the selected audience and categories before enrollment.
        Invitations expire after 48 hours. New invitations disable prior enrollment and
        suppress pending deliveries. All three notification gates default off; live invitations
        also require live email transport. Returns 503 while unavailable. Sandbox never sends
        email and instead returns a sensitive previewUrl for testing; do not log or publish it.
        requestId is a body UUID used for idempotency: retry the same request unchanged, not
        with a new UUID. Changed content under an existing requestId returns 409. A sending or
        unknown delivery result must not be automatically resent. Limits are 100 invitations
        per partner per hour and five per address per day (429 when exceeded). At least one
        category is required: statusUpdates=true or a nonempty agingDays list. No historical
        events are replayed. Assigned-bill recipients need separate explicit bill assignments.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [requestId, email, audience, statusUpdates, agingDays, quietHours]
              properties:
                requestId: { type: string, format: uuid }
                email: { type: string, format: email, maxLength: 254 }
                audience: { enum: [practice, assigned_bills] }
                statusUpdates: { type: boolean }
                statusEvents: { $ref: '#/components/schemas/NotificationStatusEvents' }
                agingDays: { type: array, maxItems: 3, items: { enum: [30, 60, 90] } }
                quietHours: { type: boolean }
      responses:
        '201':
          description: Invitation created; notifications remain disabled pending confirmation.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: object
                    required: [externalUserId, invitationId, enabled, deliveryStatus]
                    properties:
                      externalUserId: { type: string }
                      invitationId: { type: string, format: uuid }
                      enabled: { const: false }
                      deliveryStatus: { enum: [sandbox_preview, sending, sent, unknown, suppressed] }
                      previewUrl: { type: string, format: uri, description: Sandbox-only secret confirmation capability. }
        '200':
          description: Identical retry; no additional email is sent.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: object
                    required: [externalUserId, invitationId, deliveryStatus, expiresAt, retried]
                    properties:
                      externalUserId: { type: string }
                      invitationId: { type: string, format: uuid }
                      deliveryStatus: { enum: [sandbox_preview, sending, sent, unknown, suppressed] }
                      expiresAt: { type: string, format: date-time }
                      retried: { const: true }
        default: { $ref: '#/components/responses/Problem' }
  /claims-administrators:
    get:
      tags:
        - Directories
      operationId: searchClaimsAdministrators
      summary: Search claims administrators
      description: 'Directory entries and payer-choice keys. The response is top-level, without a data wrapper. Use
        payers[].key as claim.claimsAdministrator.payerId, not a clearinghouse routing identifier. Server scope: payers:read.
        Browser permission: payers:read. Browser requests require the exact allowed Origin. Directory matches are
        candidates; verify the employer, subpayer, claim format and supported transmission route before submitting.'
      security:
        - bearerAuth: []
        - browserSessionAuth: []
      parameters:
        - name: q
          in: query
          required: false
          description: ''
          schema:
            type: string
            maxLength: 200
        - name: claimNumber
          in: query
          required: false
          description: ''
          schema:
            type: string
            maxLength: 200
        - name: sourceClaimsAdministratorName
          in: query
          required: false
          description: ''
          schema:
            type: string
            maxLength: 200
        - name: employerName
          in: query
          required: false
          description: ''
          schema:
            type: string
            maxLength: 200
        - name: limit
          in: query
          required: false
          description: Default 50, clamped to 1–100.
          schema:
            type: integer
            minimum: 1
            maximum: 100
        - name: offset
          in: query
          required: false
          description: Zero-based, default 0.
          schema:
            type: integer
            minimum: 0
      responses:
        '200':
          description: Ranked directory results, suggestions, recommendedId when matched, total and optional nextOffset.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DirectorySearch'
          headers:
            Cache-Control:
              schema:
                type: string
                const: no-store
        default:
          $ref: '#/components/responses/Problem'
        '400':
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: payers:read
        browserPermission: payers:read
  /medical-provider-networks:
    get:
      tags: [ Directories ]
      operationId: searchMedicalProviderNetworks
      summary: Search approved medical provider networks
      description: |
        Search the imported California DWC medical provider network (MPN) directory.
        Only Approved networks are returned for new selections. This is a saved
        directory snapshot, not live verification of a network's current status.
        Use data[].id as the optional claim.medicalProviderNetworkId when entering a bill.
        Without limit, all matching approved networks are returned. total counts matches
        before limiting. Server scope and browser permission are payers:read.
        Browser requests require the exact allowed Origin.
      security:
        - bearerAuth: []
        - browserSessionAuth: []
      x-mindbill-access:
        serverScope: payers:read
        browserPermission: payers:read
      parameters:
        - name: q
          in: query
          required: false
          description: Case-insensitive search across ID, network name, applicant name and applicant type. All whitespace-separated terms must match. Omit or leave blank for all approved networks.
          schema: { type: string }
        - name: limit
          in: query
          required: false
          description: Maximum results to return. Omit to return all matches; invalid values return 422.
          schema: { type: integer, minimum: 1, maximum: 300 }
      responses:
        '200':
          description: Approved networks and matching count before limiting.
          content:
            application/json:
              schema:
                type: object
                required: [ data, total ]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/MedicalProviderNetwork' }
                  total: { type: integer, minimum: 0 }
        '422':
          description: limit must be an integer between 1 and 300.
          content:
            application/json:
              schema:
                type: object
                required: [ error, message ]
                properties:
                  error: { type: string, const: invalid_limit }
                  message: { type: string }
        default: { $ref: '#/components/responses/Problem' }
  /claims:
    post:
      tags: [ Treatment Authorization ]
      operationId: provisionClaim
      x-mindbill-access:
        serverScope: bills:write
        browserPermission: bills:create
        browserBillScoped: false
      summary: Create or reuse a patient and claim before billing
      description: |
        Requires bills:write. Supply stable externalId values for both snapshots; native
        IDs are not accepted here. Exact mapped snapshots are reused without changes.
        A changed patient or claim snapshot returns 409 and requires reconciliation.
        The transaction creates no bill, sends nothing and grants no authorization.
        Use the returned IDs to create an RFA or perform EAMS preflight before billing.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [ patient, claim ]
              properties:
                patient:
                  allOf:
                    - $ref: '#/components/schemas/PatientInput'
                    - type: object
                      required: [ externalId ]
                      properties: { id: false, externalId: { type: string, minLength: 1, maxLength: 255 } }
                claim:
                  allOf:
                    - $ref: '#/components/schemas/ClaimInput'
                    - type: object
                      required: [ externalId ]
                      properties: { id: false, externalId: { type: string, minLength: 1, maxLength: 255 } }
      responses:
        '200':
          description: Both existing snapshots matched.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ClaimProvisionResult' }
        '201':
          description: Patient or claim created atomically.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ClaimProvisionResult' }
        default: { $ref: '#/components/responses/Problem' }
  /eams/lookup:
    post:
      tags: [ Directories ]
      operationId: lookupEams
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        browserBillScoped: false
      summary: Optionally look up an ADJ before creating a claim
      description: |
        Explicit read-only lookup using an ADJ number; no saved claim or bill is required.
        Never creates or changes a claim, payer, or bill, and is never a billing prerequisite.
        Requires bills:read. Browser sessions must be organization-wide with an exact allowed
        Origin. Returns only directory candidates, always requiring human review.
        Live requests use the authenticated laptop lookup connection with a 25-second
        deadline; an offline laptop returns 503. Sandbox returns not_performed without
        contacting EAMS. Name searches are not supported. Responses are not cached.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [ adj ]
              properties:
                adj:
                  type: string
                  description: ADJ followed by 1 to 20 digits; surrounding whitespace is trimmed and letters are uppercased.
                  example: ADJ123456
      responses:
        '200':
          description: Directory suggestions only; never confirms an adjuster or payer routing.
          content:
            application/json:
              schema:
                type: object
                required: [ source, status, requiresReview, adjusterVerified, candidates ]
                properties:
                  source: { const: eams }
                  status: { type: string, enum: [ not_performed, review_required, candidate_found, no_match ] }
                  requiresReview: { const: true }
                  adjusterVerified: { const: false }
                  candidates:
                    type: array
                    items:
                      type: object
                      required: [ claimsAdministratorId, name, match ]
                      properties:
                        claimsAdministratorId: { type: string }
                        name: { type: string }
                        match: { const: directory_name }
                  unmatchedParticipants: { type: integer, minimum: 0 }
                  checkedAt: { type: string, format: date-time }
                  reason: { const: sandbox }
        default: { $ref: '#/components/responses/Problem' }
  /claims/{claimId}/eams-preflight:
    post:
      tags: [ Bills ]
      operationId: preflightClaimEams
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        browserBillScoped: false
      summary: Look up a saved claim in EAMS
      description: |
        Requires bills:read and a claim linked to this partner and environment. Uses the
        saved ADJ number. Returns directory candidates; always requires human review and
        never verifies an adjuster or changes the claim. Sandbox returns not_performed.
        Service outages return 503, not permission to bill an unverified payer.
      parameters:
        - { name: claimId, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: EAMS preflight result.
          content:
            application/json:
              schema:
                type: object
                required: [ claimId, status, requiresReview, adjusterVerified, candidates ]
                properties:
                  claimId: { type: string }
                  status: { type: string, enum: [ not_performed, review_required, candidate_found, no_match ] }
                  requiresReview: { const: true }
                  adjusterVerified: { const: false }
                  candidates: { type: array, items: { type: object } }
        default: { $ref: '#/components/responses/Problem' }
  /procedure-codes:
    get:
      tags: [ Directories ]
      operationId: searchProcedureCodes
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        requiredCapability: treatmentBilling
      summary: Search treatment procedure codes
      description: |
        Search the latest imported procedure catalog for a jurisdiction by code prefix.
        Requires bills:read and treatmentBilling capability. Browser requests require
        their exact allowed Origin. Results contain codes only, without descriptions or
        fee amounts, and exclude quarantined variants, medical-legal and dental codes.
        Catalog inclusion does not establish a payable fee, coding eligibility or
        authorization. Use quoteTreatmentFee separately for supported California fee
        calculations. total counts all distinct matching codes before the limit; this
        endpoint does not paginate. An absent catalog returns an empty result with
        catalogAsOf null. Invalid or unknown query parameters return 422;
        a catalog service failure returns 503.
      parameters:
        - name: q
          in: query
          description: Alphanumeric code prefix, trimmed and converted to uppercase. Empty searches return the first codes in code order.
          schema: { type: string, maxLength: 5, pattern: '^[A-Za-z0-9]*$', default: '' }
          example: '992'
        - name: limit
          in: query
          description: Maximum number of distinct codes to return. Values outside the range are rejected.
          schema: { type: integer, minimum: 1, maximum: 100, default: 30 }
        - name: jurisdiction
          in: query
          description: Jurisdiction of the discovery catalog. This does not select a fee quote jurisdiction.
          schema: { type: string, enum: [ CA, NY, OWCP ], default: CA }
      responses:
        '200':
          description: Bounded, code-ordered matches from the latest discovery catalog.
          headers:
            Cache-Control:
              schema: { type: string, const: no-store }
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [ results, total, limit, jurisdiction, catalogAsOf ]
                properties:
                  results:
                    type: array
                    maxItems: 100
                    description: Distinct matching procedure codes in ascending code order.
                    items:
                      type: object
                      additionalProperties: false
                      required: [ code ]
                      properties:
                        code: { type: string, description: Canonical professional procedure code from the catalog., pattern: '^([0-9]{5}|[A-CE-Z][0-9]{4}|[0-9]{4}[A-Z])$' }
                  total: { type: integer, minimum: 0, description: Total distinct matching codes before applying the requested limit. }
                  limit: { type: integer, minimum: 1, maximum: 100, description: Applied result limit. }
                  jurisdiction: { type: string, enum: [ CA, NY, OWCP ], description: Selected discovery catalog jurisdiction. }
                  catalogAsOf: { type: [ string, 'null' ], format: date, description: 'Catalog capture date, not a fee effective date. Null when no catalog is installed.' }
              example:
                results: [ { code: '99213' } ]
                total: 1
                limit: 30
                jurisdiction: CA
                catalogAsOf: '2026-09-06'
        '422':
          description: Invalid search parameters. The problem code is invalid_procedure_search.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        '503':
          description: The catalog service is unavailable. The problem code is procedure_catalog_unavailable.
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        default: { $ref: '#/components/responses/Problem' }
  /fee-quotes:
    post:
      tags:
      - Bills
      operationId: quoteTreatmentFee
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        requiredCapability: treatmentBilling
      summary: Check a California treatment fee
      description: 'Requires bills:read and treatmentBilling capability. Amounts are cents. Uses

        service-date-specific sources and server-owned locality data. Supports WC report

        rules, dated physician catalog calculations and bounded 99358/99359 prolonged

        services with documented time and related evaluation context. Also supports 97110 office physical-therapy

        estimates with explicit therapyContext and authenticated private data. Adopted California equipment and nutritional supplies use dmeposContext for worker residence and rental/payment history. Returns

        requires_review for unsupported contexts or missing data;

        never substitutes zero. Imported codes do not guarantee separate payment. A saved

        provider and canonical payer can select an effective practice charge or contracted

        rate; the statutory maximum remains separately identified. This does not establish

        coding or authorization eligibility.

        '
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required:
              - code
              - dateOfService
              properties:
                drug:
                  $ref: '#/components/schemas/BilledDrug'
                pharmacyContext:
                  $ref: '#/components/schemas/PharmacyBillingContext'
                dmeposContext:
                  $ref: '#/components/schemas/CaDmeposContext'
                code:
                  type: string
                  minLength: 1
                  maxLength: 10
                dateOfService:
                  type: string
                  format: date
                chargeCents:
                  type: integer
                  minimum: 1
                  maximum: 100000000
                units:
                  type: number
                  exclusiveMinimum: 0
                  maximum: 10000
                modifiers:
                  type: array
                  maxItems: 4
                  items:
                    type: string
                    minLength: 1
                    maxLength: 2
                pages:
                  type: integer
                  minimum: 1
                  maximum: 10000
                reportKind:
                  type: string
                  enum:
                  - progress
                  - permanent_stationary_pr3
                  - permanent_stationary_pr4
                reportQualification:
                  description: Explicit report/request context for WC005, WC007, WC008 and WC009. Pages are required for these
                    quotes. Unknown or nonqualifying context requires review; this does not establish coding eligibility.
                  oneOf:
                  - type: object
                    additionalProperties: false
                    required:
                    - kind
                    - requestedBy
                    - medicalLegalEvaluation
                    - reportPayableUnderMedicalLegalSchedule
                    properties:
                      kind:
                        type: string
                        const: psychiatric_report
                      requestedBy:
                        type: string
                        enum:
                        - wcab
                        - administrative_director
                      medicalLegalEvaluation:
                        type: boolean
                        description: Whether this report is part of a medical-legal evaluation. This context is separate from
                          whether the report is payable under the medical-legal fee schedule. WC005 requires modifier 32.
                      reportPayableUnderMedicalLegalSchedule:
                        type: boolean
                        description: Whether this report is payable under the medical-legal fee schedule. A priced WC005 quote
                          requires false.
                  - type: object
                    additionalProperties: false
                    required:
                    - kind
                    - requestedBy
                    - medicalLegalEvaluation
                    - reportPayableUnderMedicalLegalSchedule
                    properties:
                      kind:
                        type: string
                        const: consultation_report
                      requestedBy:
                        type: string
                        enum:
                        - wcab
                        - administrative_director
                        - qme
                        - ame
                      medicalLegalEvaluation:
                        type: boolean
                        description: Whether this report is part of a medical-legal evaluation. QME/AME requests require true
                          and modifier 30; WCAB/Administrative Director requests require modifier 32.
                      reportPayableUnderMedicalLegalSchedule:
                        type: boolean
                        description: Whether this report is payable under the medical-legal fee schedule. A priced WC007 quote
                          requires false regardless of evaluation context.
                  - type: object
                    additionalProperties: false
                    required:
                    - kind
                    - requestedBy
                    - writtenRequest
                    properties:
                      kind:
                        type: string
                        const: chart_notes
                      requestedBy:
                        type: string
                        const: claims_administrator
                      writtenRequest:
                        type: boolean
                        description: Whether the claims administrator requested the chart notes in writing. A priced quote requires
                          true and no modifiers.
                  - type: object
                    additionalProperties: false
                    required:
                    - kind
                    - requestedBy
                    - writtenRequest
                    - relatedToBilling
                    - initialRequiredCopy
                    properties:
                      kind:
                        type: string
                        const: duplicate_report
                      requestedBy:
                        type: string
                        const: claims_administrator
                      writtenRequest:
                        type: boolean
                      relatedToBilling:
                        type: boolean
                      initialRequiredCopy:
                        type: boolean
                        description: Whether this is the initial required copy. A priced WC009 quote requires false; writtenRequest
                          and relatedToBilling must be true, with no modifiers.
                hasFeeAgreement:
                  type: boolean
                serviceZip:
                  type: string
                  pattern: ^\d{5}(?:-?\d{4})?$
                therapyContext:
                  type: object
                  additionalProperties: false
                  description: Actual calculation facts for bounded office PT estimates. Initial evaluations 97161-97163
                    support one untimed unit as the sole same-day service during July-September 2026, with
                    priorInitialEvaluationInEpisode=false. Minutes are required only for supported timed procedures.
                    Missing applicable facts return requires_review. Empty modifiers or GP and hasFeeAgreement=false
                    are required. See docs/partner-platform/therapy-fee-estimates.md for coverage and limitations.
                  properties:
                    providerKind:
                      type: string
                      enum:
                      - physical_therapist
                      - other
                    personallyPerformed:
                      type: boolean
                    placeOfService:
                      type: string
                      pattern: ^\d{2}$
                    hospitalPatient:
                      type: boolean
                    incidentToPhysicianService:
                      type: boolean
                    assistantInvolved:
                      type: boolean
                    priorInitialEvaluationInEpisode:
                      type: boolean
                      description: Whether an initial PT evaluation was already furnished in this episode of care.
                        Initial evaluations 97161-97163 require false; unknown must stay omitted.
                    directOneOnOneMinutes:
                      type: integer
                      minimum: 0
                      maximum: 1440
                    totalVisitMinutes:
                      type: integer
                      minimum: 0
                      maximum: 1440
                    visitsOnDate:
                      type: integer
                      minimum: 0
                      maximum: 100
                    completeSameDayServices:
                      type: boolean
                      description: Includes all disciplines and previously billed or pending services in the practice/group.
                    otherSameDayServices:
                      type: boolean
                    globalPeriodApplies:
                      type: boolean
                    hpsaBonusEligible:
                      type: boolean
                physicianContext:
                  type: object
                  additionalProperties: false
                  required:
                  - providerKind
                  - placeOfService
                  - standaloneService
                  - globalPeriodApplies
                  - hpsaBonusEligible
                  properties:
                    providerKind:
                      type: string
                      enum:
                      - physician
                      - physician_assistant
                      - nurse_practitioner
                      - clinical_nurse_specialist
                      - other
                    incidentToPhysicianService:
                      type: boolean
                      description: For a supported physician assistant, nurse practitioner, or clinical nurse specialist quote,
                        explicitly attest false for independently billed services. True or omitted requires review; physician
                        incident-to services also require review.
                    placeOfService:
                      type: string
                      pattern: ^\d{2}$
                    standaloneService:
                      type: boolean
                    globalPeriodApplies:
                      type: boolean
                    hpsaBonusEligible:
                      type: boolean
                billingProviderId:
                  type: string
                  minLength: 1
                  maxLength: 120
                  description: Saved provider in the authenticated organization for practice charge and contract matching.
                payerId:
                  type: string
                  minLength: 1
                  maxLength: 120
                  description: Canonical claims administrator ID for payer-specific matching.
                ndcNumber:
                  type: string
                  pattern: ^[0-9]{11}$
                historicalTelephoneContext:
                  $ref: '#/components/schemas/CaHistoricalTelephoneContext'
                catalogContext:
                  type: object
                  additionalProperties: false
                  required:
                  - codingRequirementsSatisfied
                  properties:
                    codingRequirementsSatisfied:
                      type: boolean
                    statusIAlternative:
                      type: string
                      enum:
                      - none
                      - cpt
                      - drug
                    completeSurgicalPackage:
                      type: boolean
                prolongedServiceContext:
                  type: object
                  additionalProperties: false
                  required:
                  - totalMinutes
                  - relatedEvaluationDate
                  - ongoingPatientManagement
                  - personallyPerformed
                  - timeCountedInOtherServices
                  - completeSameDayServices
                  - sameDayServices
                  properties:
                    totalMinutes:
                      type: integer
                      minimum: 0
                      maximum: 1440
                    relatedEvaluationDate:
                      type: string
                      format: date
                    ongoingPatientManagement:
                      type: boolean
                    personallyPerformed:
                      type: boolean
                    timeCountedInOtherServices:
                      type: boolean
                    completeSameDayServices:
                      type: boolean
                    sameDayServices:
                      type: array
                      minItems: 1
                      maxItems: 2
                      items:
                        type: object
                        additionalProperties: false
                        required:
                        - code
                        - units
                        properties:
                          code:
                            type: string
                            enum:
                            - '99358'
                            - '99359'
                          units:
                            type: integer
                            minimum: 1
                            maximum: 100
      responses:
        '200':
          description: Priced quote with provenance, requires_review, or not_separately_payable.
          content:
            application/json:
              schema:
                type: object
                required:
                - data
                properties:
                  data:
                    type: object
                    required:
                    - status
                    properties:
                      status:
                        type: string
                        enum:
                        - priced
                        - requires_review
                        - not_separately_payable
                      amountCents:
                        type: integer
                      scheduleMaximumCents:
                        type: integer
                      reason:
                        type: string
                      provenance:
                        type: array
                        items:
                          type: object
        default:
          $ref: '#/components/responses/Problem'
  /bills/{billId}/dispute-allowance:
    parameters:
      - $ref: '#/components/parameters/BillId'
    get:
      tags: [ Lifecycle ]
      operationId: getDisputeAllowance
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
        requiredCapability: treatmentBilling
      summary: Read treatment lines and the current allowance review
      description: Requires bills:read, treatmentBilling capability and ownership in the credential environment. The opaque reviewToken binds the submitted bill facts; it must be returned with a reviewed allowance for every line.
      responses:
        '200':
          description: Current lines, review eligibility, opaque concurrency token and optional audit.
          content:
            application/json:
              schema:
                type: object
                required: [ billId, canReview, reviewToken, lines, activeReview ]
                properties:
                  billId: { type: string }
                  canReview: { type: boolean }
                  reviewToken: { type: string, pattern: '^[a-f0-9]{64}$' }
                  lines: { type: array, items: { type: object } }
                  activeReview: { anyOf: [ { $ref: '#/components/schemas/DisputeAllowanceAudit' }, { type: 'null' } ] }
        default: { $ref: '#/components/responses/Problem' }
    post:
      tags: [ Lifecycle ]
      operationId: recordDisputeAllowance
      x-mindbill-access:
        serverScope: bills:write
        browserPermission: bills:act
        requiredCapability: treatmentBilling
      summary: Record a documented treatment allowance review
      description: |
        Requires bills:write, treatmentBilling capability and ownership in the credential
        environment. Supply each bill line exactly once. Allowances are dollars with at
        most two decimal places; zero is valid when supported by the cited basis. A bill
        must already have frozen submission and provider facts. A stale token returns 409;
        refetch and review again with a new idempotency key. Audit identity and time are
        assigned by MindBill to the authenticated credential, not a claimed human reviewer.
        This enables dispute calculations but does not change charges, payments or A/R,
        establish legal entitlement, file an IBR or send a second review by itself.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [ reviewToken, lines ]
              properties:
                reviewToken: { type: string, pattern: '^[a-f0-9]{64}$' }
                lines: { type: array, minItems: 1, maxItems: 100, items: { $ref: '#/components/schemas/DisputeAllowanceLine' } }
      responses:
        '201':
          description: Review recorded with server-owned audit attribution.
          content:
            application/json:
              schema:
                type: object
                required: [ billId, review ]
                properties:
                  billId: { type: string }
                  review: { $ref: '#/components/schemas/DisputeAllowanceAudit' }
        default: { $ref: '#/components/responses/Problem' }
  /sandbox/bills/{billId}/837p:
    parameters:
      - $ref: '#/components/parameters/BillId'
    get:
      tags: [ Bills ]
      operationId: getSandboxBill837p
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
      summary: Download the sandbox 837P wire format
      description: Requires bills:read. Generates the actual professional EDI with ISA15 test indicator T from the scoped sandbox bill. Does not transmit or enqueue a claim. Live bills are rejected.
      responses:
        '200':
          description: Test 837P text.
          content:
            text/plain:
              schema: { type: string }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/form:
    parameters:
      - $ref: '#/components/parameters/RfaId'
    post:
      tags: [ Treatment Authorization ]
      operationId: generateRfaForm
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Generate official unsigned RFA form
      description: Requires rfas:write and treatmentBilling. Generate the official unsigned DWC RFA before any bill exists. Diagnosis descriptions are keyed by exact RFA item ID and required for every item. The generated PDF is saved as an other document and is not readiness or signature evidence. Download it through its scoped document contentUrl, obtain a physician signature, then upload as rfa_form and record actual signedAt. Only draft, ready, incomplete and deferred requests may generate a form.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RfaFormRequest"
      responses:
        '200':
          description: Updated scoped RFA, including document metadata and transmission status.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/RfaEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/fax/refresh:
    parameters:
      - $ref: '#/components/parameters/RfaId'
    post:
      tags: [ Treatment Authorization ]
      operationId: refreshRfaFax
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Refresh verified RFA fax receipt
      description: Requires rfas:write and treatmentBilling. Refresh existing fax attempts against the recorded provider. Only verified delivery with an actual completion timestamp starts the receipt clock; an accepted dispatch is not approval. This does not send another fax.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              description: Send an empty JSON object.
      responses:
        '200':
          description: Updated scoped RFA, including document metadata and transmission status.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/RfaEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /browser/rfas/{rfaId}/form:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: '#/components/parameters/RfaId'
    post:
      tags: [ Treatment Authorization ]
      operationId: browserGenerateRfaForm
      x-mindbill-access:
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Generate official unsigned RFA form
      description: Requires rfas:act and treatmentBilling. Uses a scoped browser-session bearer token and allowed Origin. Generate the official unsigned DWC RFA before any bill exists. Diagnosis descriptions are keyed by exact RFA item ID and required for every item. The generated PDF is saved as an other document and is not readiness or signature evidence. Download it through its scoped document contentUrl, obtain a physician signature, then upload as rfa_form and record actual signedAt. Only draft, ready, incomplete and deferred requests may generate a form.
      security:
        - browserSessionAuth: []
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RfaFormRequest"
      responses:
        '200':
          description: Updated scoped RFA, including document metadata and transmission status.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/RfaEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /browser/rfas/{rfaId}/fax/refresh:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: '#/components/parameters/RfaId'
    post:
      tags: [ Treatment Authorization ]
      operationId: browserRefreshRfaFax
      x-mindbill-access:
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Refresh verified RFA fax receipt
      description: Requires rfas:act and treatmentBilling. Uses a scoped browser-session bearer token and allowed Origin. Refresh existing fax attempts against the recorded provider. Only verified delivery with an actual completion timestamp starts the receipt clock; an accepted dispatch is not approval. This does not send another fax.
      security:
        - browserSessionAuth: []
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              description: Send an empty JSON object.
      responses:
        '200':
          description: Updated scoped RFA, including document metadata and transmission status.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/RfaEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /browser/rfas/{rfaId}/packet:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: '#/components/parameters/RfaId'
    post:
      tags: [ Treatment Authorization ]
      operationId: browserDownloadRfaPacket
      x-mindbill-access:
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Download signed RFA packet
      description: Requires rfas:read and treatmentBilling. Uses a scoped browser-session bearer token and allowed Origin. Assemble selected stored PDFs with one signed rfa_form and clinical support. Checks document hashes and PDF contents, preserves all pages and does not transmit.
      security:
        - browserSessionAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [ documentIds ]
              properties:
                documentIds: { type: array, minItems: 2, maxItems: 100, uniqueItems: true, items: { type: string, minLength: 1 } }
      responses:
        '200':
          description: Assembled RFA PDF packet.
          content:
            application/pdf:
              schema: { type: string, format: binary }
        default: { $ref: '#/components/responses/Problem' }
  /browser/rfas/{rfaId}/fax:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: '#/components/parameters/RfaId'
    post:
      tags: [ Treatment Authorization ]
      operationId: browserSendRfaFax
      x-mindbill-access:
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Send RFA fax
      description: Requires rfas:act and treatmentBilling. Uses a scoped browser-session bearer token and allowed Origin. Send selected stored signed RFA and clinical PDF documents to an explicit authorization fax number. Live environment and enabled fax delivery are required. Dispatch acceptance is not receipt or approval. Ambiguous attempts require reconciliation before retry.
      security:
        - browserSessionAuth: []
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [ to, documentIds ]
              properties:
                documentIds: { type: array, minItems: 2, maxItems: 100, uniqueItems: true, items: { type: string, minLength: 1 } }
                to: { type: string, pattern: '^\+[1-9]\d{7,14}$' }
                nonBusinessDates: { type: array, maxItems: 366, items: { type: string, format: date } }
      responses:
        '200':
          description: Updated scoped RFA, including document metadata and transmission status.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/RfaEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/packet:
    parameters:
      - $ref: '#/components/parameters/RfaId'
    post:
      tags: [ Treatment Authorization ]
      operationId: downloadRfaPacket
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Assemble a signed RFA and supporting PDF packet
      description: Requires rfas:read and treatmentBilling. Select the exact stored RFA form and clinical supporting documents. Document hashes and PDF contents are checked before assembly. No transmission occurs.
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, additionalProperties: false, required: [ documentIds ], properties: { documentIds: { type: array, minItems: 2, maxItems: 100, uniqueItems: true, items: { type: string } } } }
      responses:
        '200':
          description: RFA packet PDF.
          content:
            application/pdf:
              schema: { type: string, format: binary }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/fax:
    parameters:
      - $ref: '#/components/parameters/RfaId'
    post:
      tags: [ Treatment Authorization ]
      operationId: sendRfaFax
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Send an RFA packet to an authorization fax number
      description: |
        Requires rfas:write, treatmentBilling, live environment and configured fax delivery.
        Uses an explicit authorization destination and stored PDF IDs. An accepted dispatch
        is not receipt or approval. Ambiguous dispatch failures require reconciliation before
        another send. Verified provider delivery starts the receipt-based clock.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [ to, documentIds ]
              properties:
                to: { type: string, pattern: '^\+[1-9]\d{7,14}$' }
                documentIds: { type: array, minItems: 2, maxItems: 100, uniqueItems: true, items: { type: string } }
                nonBusinessDates: { type: array, maxItems: 366, items: { type: string, format: date } }
      responses:
        '200':
          description: RFA with the recorded transmission attempt.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/RfaEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /report-autofill:
    post:
      tags: [Bills]
      operationId: createReportAutofillDraft
      summary: Extract report fields for a draft review
      description: |
        Available only to approved organization-wide operator integrations with the
        reportAutofill capability provisioned after a written processing agreement.
        Server scope autofill:write or explicitly delegated browser permission autofill:run
        is required. Customer-scoped and bill-scoped sessions are not supported.
        Upload exactly one unencrypted PDF containing 1 to 100 pages, at most 25 MiB.
        Returns extracted facts and saved-profile matches for explicit human review.
        Does not persist the report, create a bill, or submit anything. Responses use
        Cache-Control no-store. Missing or ambiguous facts must be entered or selected
        by the user; a match does not authorize using a record outside the session scope.
      x-mindbill-access:
        serverScope: autofill:write
        browserPermission: autofill:run
        browserBillScoped: false
        requiredCapability: reportAutofill
      security:
        - bearerAuth: []
        - browserSessionAuth: []
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              additionalProperties: false
              required: [report]
              properties:
                report:
                  type: string
                  format: binary
                  description: One PDF, at most 26214400 bytes; no other multipart fields.
            encoding:
              report: { contentType: application/pdf }
      responses:
        '200':
          description: Extracted fields and candidate matches, all requiring human review.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data: { $ref: '#/components/schemas/ReportAutofillDraft' }
        '400': { description: 'invalid_report; upload one valid, unencrypted PDF of 1 to 100 pages.', content: { application/problem+json: { schema: { $ref: '#/components/schemas/Problem' } } } }
        '403': { description: 'report_autofill_not_enabled; approved organization-wide capability and authorization required.', content: { application/problem+json: { schema: { $ref: '#/components/schemas/Problem' } } } }
        '413': { description: 'report_too_large; PDF exceeds 25 MiB.', content: { application/problem+json: { schema: { $ref: '#/components/schemas/Problem' } } } }
        '502': { description: 'report_extraction_failed; enter fields manually or try another PDF.', content: { application/problem+json: { schema: { $ref: '#/components/schemas/Problem' } } } }
        '503': { description: 'report_autofill_unavailable; extraction is not configured.', content: { application/problem+json: { schema: { $ref: '#/components/schemas/Problem' } } } }
        default: { $ref: '#/components/responses/Problem' }
  /bills:
    get:
      tags:
        - Bills
      operationId: listBills
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
      summary: List bills
      description: Find bills by your stable IDs or lifecycle state. Results use cursor pagination.
      parameters:
        - name: patientId
          in: query
          description: Canonical MindBill patient ID; use the authorized dashboard patient filter inventory.
          schema: { type: string, maxLength: 200 }
        - name: q
          in: query
          description: Case-insensitive search requiring every word across bill, patient, claim, claims administrator, status,
            external IDs, procedure codes and dates. Recognizes ISO and M/D/YYYY or MM/DD/YYYY dates.
          schema:
            type: string
            maxLength: 160
        - name: dateField
          in: query
          description: Date used by the inclusive from/to range.
          schema:
            type: string
            enum:
            - service
            - submitted
            default: submitted
        - name: from
          in: query
          description: Inclusive calendar date. Must be a real YYYY-MM-DD date; invalid dates or from after to return 400.
          schema:
            type: string
            format: date
            pattern: ^\d{4}-\d{2}-\d{2}$
        - name: to
          in: query
          description: Inclusive calendar date. Must be a real YYYY-MM-DD date; invalid dates or from after to return 400.
          schema:
            type: string
            format: date
            pattern: ^\d{4}-\d{2}-\d{2}$
        - name: customerExternalId
          in: query
          description: Optional host customer filter for server/admin calls. A customer-scoped session cannot request another customer.
          schema: { type: string, minLength: 1, maxLength: 255 }
        - name: externalId
          in: query
          description: Your stable bill or work-item ID.
          schema:
            type: string
        - name: patientExternalId
          in: query
          description: Your stable patient ID.
          schema:
            type: string
        - name: claimExternalId
          in: query
          description: Your stable claim or injury ID.
          schema:
            type: string
        - name: state
          in: query
          description: MindBill lifecycle state.
          schema:
            $ref: '#/components/schemas/BillState'
        - name: cursor
          in: query
          description: Opaque cursor returned by the previous page.
          schema:
            type: string
        - name: limit
          in: query
          description: Page size.
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 25
      responses:
        '200':
          description: A page of bills.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BillPage'
        default:
          $ref: '#/components/responses/Problem'
    post:
      tags:
        - Bills
      operationId: createAndSubmitBill
      summary: Create and submit a bill
      description: |
        Atomically validate and submit one immutable bill snapshot with its explicit
        payer-packet PDFs. A validation or pre-submission failure creates no public bill.
        Once live dispatch starts, an uncertain result retains the bill and evidence.
        A 502 response includes billId and reconciliationRequired; retrieve that bill
        and reconcile before any further submission. Retrying the identical request
        uses the same idempotency key; a new key must not bypass reconciliation.
        Store the returned bill ID and use it for every later operation.
        Use `med_legal` for med-legal services and `professional` for enabled treatment
        organizations. Professional lines require a positive explicit charge and service
        date. CMS-1500 claims require 1–12 nonblank diagnoses and at most four
        distinct diagnosis pointers per line. Multi-diagnosis claims require explicit
        pointers; a sole diagnosis defaults to pointer 1. An approved RFA item may
        be linked to a treatment line.
        Medical-legal lines may opt into a date-aware calculation with medLegalContext
        (an empty object is sufficient only for the ML201 base calculation). ML200,
        ML202 and ML203 require their code-specific eligibility facts. ML204/ML205 use
        quarter-hour units, not hours; units must match documented time and minimums.
        A contextual line requires a positive complete calculation. Historical dates
        before April 1, 2021 and unresolved combinations cannot be submitted through
        this calculation. This does not establish every service eligibility prerequisite.
        Explicit charge remains the billed amount; an omitted charge defaults to the
        calculated allowance. Read serviceLines[].pricing for amounts and citations.
        Set claimForm to ub04, ada, or ncpdp with
        the corresponding claim and line formData. The form is immutable after creation.
        The native application UI rollout flag does not restrict API access.
        Payer capability and required-field validation still apply; unsupported
        mappings fail before dispatch. Pharmacy uses the clearinghouse 837P/K3
        route; native NCPDP D.0 transport is not available.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BillSubmissionCreate'
      responses:
        '201':
          description: Bill submitted.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Bill'
        '200':
          description: Idempotent replay of the original submission.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Bill'
        '422':
          description: Request validation failed. validation_error reports malformed request fields; invalid_med_legal_context reports a medical-legal calculation that cannot produce a complete, consistent allowance. For the latter, detail explains the correction and lineIndex identifies the zero-based service line. No public bill is created.
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '502':
          description: Live transmission could not be confirmed. Retain billId and reconcile before another submission.
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/SubmissionReconciliationProblem'
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: bills:write
        browserPermission: bills:create
  /bills/{billId}:
    parameters:
      - $ref: '#/components/parameters/BillId'
    get:
      tags: [Bills]
      operationId: getBill
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
      summary: Get a bill
      description: Read the authoritative bill snapshot, documents, lines, state, and amounts.
      responses:
        '200':
          description: Bill snapshot.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Bill' }
        default: { $ref: '#/components/responses/Problem' }
  /bills/{billId}/documents:
    parameters:
      - $ref: '#/components/parameters/BillId'
    get:
      tags: [Documents]
      operationId: listBillDocuments
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: documents:read
      summary: List payer-packet documents
      description: Review exactly which documents are attached to the payer billing packet.
      responses:
        '200':
          description: Explicit payer-packet documents.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/Document' } }
        default: { $ref: '#/components/responses/Problem' }
  /bills/{billId}/documents/{documentId}:
    parameters:
      - $ref: '#/components/parameters/BillId'
      - $ref: '#/components/parameters/DocumentId'
    get:
      tags: [Documents]
      operationId: getBillDocument
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: documents:read
      summary: Download a PDF
      description: Download one authorized payer-packet document.
      responses:
        '200':
          description: PDF bytes.
          content:
            application/pdf:
              schema: { type: string, format: binary }
        default: { $ref: '#/components/responses/Problem' }
  /bills/{billId}/status:
    get:
      tags: [Lifecycle]
      operationId: getBillStatus
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
      summary: Get bill status
      description: Read the compact, authoritative lifecycle and aging surface.
      parameters:
        - $ref: '#/components/parameters/BillId'
      responses:
        '200':
          description: Current lifecycle status.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data: { $ref: '#/components/schemas/BillStatus' }
        default: { $ref: '#/components/responses/Problem' }
  /bills/{billId}/lifecycle:
    get:
      tags: [Lifecycle]
      operationId: getBillLifecycle
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
      summary: Get the complete bill workspace
      description: Read the immutable submitted bill snapshot, human-readable activity history, current lifecycle, EORs, payments, remittance, and payer contacts. Partners do not need to maintain a separate bill-history store.
      parameters:
        - $ref: '#/components/parameters/BillId'
      responses:
        '200':
          description: Complete read-only bill lifecycle workspace.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BillLifecycleEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /bills/{billId}/packet:
    get:
      tags: [Documents]
      operationId: downloadBillPacket
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
      summary: Download the complete bill packet
      description: Download one ordered PDF containing truthful submission proof and timeline, the MC 1500, selected supporting attachments, and the practice W-9 when available. Delivery proof reflects the actual e-bill, fax, mail, or email route.
      parameters:
        - $ref: '#/components/parameters/BillId'
      responses:
        '200':
          description: Complete bill packet PDF.
          headers:
            Content-Disposition:
              schema: { type: string }
              description: Attachment filename for the packet.
          content:
            application/pdf:
              schema: { type: string, format: binary }
        default: { $ref: '#/components/responses/Problem' }
  /bills/{billId}/eor:
    get:
      tags: [Lifecycle]
      operationId: getBillEor
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: eors:read
      summary: Get EOR and payment details
      description: Read parsed EOR line items, posted payments, balances, and original EOR PDFs when available.
      parameters:
        - $ref: '#/components/parameters/BillId'
      responses:
        '200':
          description: EOR and remittance data.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EorEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /bills/{billId}/actions:
    post:
      tags: [Lifecycle]
      operationId: performBillAction
      x-mindbill-access:
        serverScope: bills:write (payments:write for post_payment)
        browserPermission: bills:act
      summary: Perform the next bill action
      description: Correct and resubmit a rejected bill, close or reopen a bill, post a payment, or submit Second Bill Review for an immutable submitted bill.
      parameters:
        - $ref: '#/components/parameters/BillId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - $ref: '#/components/schemas/CloseAction'
                - $ref: '#/components/schemas/PostPaymentAction'
                - $ref: '#/components/schemas/SecondReviewAction'
                - $ref: '#/components/schemas/ReopenAction'
                - $ref: '#/components/schemas/ResubmitAction'
              discriminator: { propertyName: action }
      responses:
        '200':
          description: Action completed.
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        default: { $ref: '#/components/responses/Problem' }
  /sandbox/bills/{billId}/simulate:
    post:
      tags: [Lifecycle]
      operationId: simulateSandboxBill
      x-mindbill-access:
        serverScope: bills:submit
        browserPermission: bills:act
      summary: Simulate a sandbox lifecycle response
      description: Advance a submitted synthetic sandbox bill through deterministic accepted, processed, rejected, denied, partial-payment, or paid scenarios. This endpoint is unavailable to live credentials and is intended for demos and integration tests.
      parameters:
        - $ref: '#/components/parameters/BillId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/SandboxSimulationInput' }
      responses:
        '200':
          description: Synthetic lifecycle response applied.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SandboxSimulationEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /bills/{billId}/reviews:
    parameters:
      - $ref: '#/components/parameters/BillId'
    get:
      tags: [Lifecycle]
      operationId: listBillReviews
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
      summary: List bill reviews
      description: List Second Bill Review and IBR records linked to the original bill.
      responses:
        '200':
          description: Reviews.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/BillReview' } }
        default: { $ref: '#/components/responses/Problem' }
    post:
      tags: [Lifecycle]
      operationId: createBillReview
      x-mindbill-access:
        serverScope: bills:write
        browserPermission: bills:act
      summary: Create a bill review
      description: Create a review draft with the reason, disputed amount, and explicit supporting attachments.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/BillReviewCreate' }
      responses:
        '201':
          description: Review created.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BillReviewEnvelope' }
        '200':
          description: Idempotent replay of the original create.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BillReviewEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /bills/{billId}/reviews/{reviewId}:
    get:
      tags: [Lifecycle]
      operationId: getBillReview
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
      summary: Get a bill review
      description: Read one review and its selected attachment IDs.
      parameters:
        - $ref: '#/components/parameters/BillId'
        - $ref: '#/components/parameters/ReviewId'
      responses:
        '200':
          description: Review.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BillReviewEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /bills/{billId}/reviews/{reviewId}/packet:
    get:
      tags: [Lifecycle]
      operationId: getBillReviewFilingPacket
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: documents:read
      summary: Download the IBR filing packet
      description: >-
        For independent_bill_review reviews only. Returns a print-ready PDF:
        the completed Request for Independent Bill Review, filing instructions
        (current DWC-IBR mailing address and the $195 application fee), and a
        Proof of Service. IBR is self-filed — print, sign, enclose the fee, mail
        the packet to DWC-IBR within 30 days of the final Second Review
        determination, and concurrently serve the claims administrator
        (CCR 9792.5.7(b)). MindBill performs no IBR transport and this endpoint
        is never billed.
      parameters:
        - $ref: '#/components/parameters/BillId'
        - $ref: '#/components/parameters/ReviewId'
      responses:
        '200':
          description: PDF filing packet.
          content:
            application/pdf:
              schema: { type: string, format: binary }
        default: { $ref: '#/components/responses/Problem' }
  /bills/{billId}/reviews/{reviewId}/submissions:
    post:
      tags: [Lifecycle]
      operationId: submitBillReview
      x-mindbill-access:
        serverScope: bills:submit
        browserPermission: bills:act
      summary: Submit a bill review
      description: >-
        Submit the review draft with its selected supporting documents.
        second_review submissions are transmitted by MindBill on the bill's
        delivery route. independent_bill_review submissions are self-filed:
        submitting records the IBR on the bill lifecycle and the response's
        filing object points at the printable packet — no transport is
        performed and no charge is metered.
      parameters:
        - $ref: '#/components/parameters/BillId'
        - $ref: '#/components/parameters/ReviewId'
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '202':
          description: Review submission accepted.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BillReviewEnvelope' }
        '200':
          description: Review was already submitted or this is an idempotent replay.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BillReviewEnvelope' }
        default: { $ref: '#/components/responses/Problem' }
  /events:
    get:
      tags: [Events]
      operationId: listEvents
      security:
        - bearerAuth: []
      summary: List lifecycle events
      description: Recover missed webhook events in sequence order. Persist the returned cursor.
      parameters:
        - { name: cursor, in: query, description: Opaque cursor returned by the previous page., schema: { type: string } }
        - { name: limit, in: query, description: Page size., schema: { type: integer, minimum: 1, maximum: 100, default: 50 } }
      responses:
        '200':
          description: Event page.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EventPage' }
        default: { $ref: '#/components/responses/Problem' }
  /webhook-deliveries:
    get:
      tags: [Events]
      operationId: listWebhookDeliveries
      security:
        - bearerAuth: []
      summary: List webhook deliveries
      description: Inspect delivery attempts for operational reconciliation.
      parameters:
        - { name: cursor, in: query, description: Opaque cursor returned by the previous page., schema: { type: string } }
        - { name: limit, in: query, description: Page size., schema: { type: integer, minimum: 1, maximum: 100, default: 50 } }
      responses:
        '200':
          description: Delivery page.
          content:
            application/json:
              schema:
                type: object
                required: [deliveries]
                properties:
                  deliveries: { type: array, items: { $ref: '#/components/schemas/WebhookDelivery' } }
        default: { $ref: '#/components/responses/Problem' }
  /rfa-inbound-faxes:
    get:
      tags: [ Treatment Authorization ]
      operationId: listRfaInboundFaxes
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: List incoming authorization response faxes
      description: Lists only faxes attributed by verified receiving-number configuration to the authenticated partner, organization and environment. OCR suggestions never grant access. Customer-scoped and bill-scoped sessions are unsupported. Unmatched faxes are returned by default. Follow nextCursor until null.
      parameters:
        - { name: includeMatched, in: query, schema: { type: boolean, default: false } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 100 } }
        - { name: cursor, in: query, schema: { type: string }, description: Opaque nextCursor from the previous page with the same scope and includeMatched filter. }
      responses:
        '200': { description: Scoped response inbox, content: { application/json: { schema: { type: object, required: [ data, hasMore, nextCursor ], properties: { data: { type: array, items: { $ref: '#/components/schemas/RfaInboundFax' } }, hasMore: { type: boolean }, nextCursor: { type: [ string, 'null' ] } } } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfa-inbound-faxes/{faxId}/content:
    get:
      tags: [ Treatment Authorization ]
      operationId: getRfaInboundFaxContent
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Review an incoming authorization fax PDF
      description: Returns the authenticated source PDF after checking receiving-number attribution. A preview is not a match or a recorded utilization review decision.
      parameters:
        - { name: faxId, in: path, required: true, schema: { type: string } }
      responses:
        '200': { description: Incoming fax PDF, content: { application/pdf: { schema: { type: string, format: binary } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfa-inbound-faxes/{faxId}/match:
    post:
      tags: [ Treatment Authorization ]
      operationId: matchRfaInboundFax
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Match a reviewed response fax to an RFA
      description: Associates the fax with an eligible submitted RFA in the same partner, organization and environment, retains its PDF as a UR response document, and reconciles the Post UR task. Repeating the same match returns the existing document; matching to another request returns 409. A fax already associated with a bill cannot be matched. Does not infer receipt, create treatment decisions, or clear No Response tasks.
      parameters:
        - { name: faxId, in: path, required: true, schema: { type: string } }
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, additionalProperties: false, required: [ rfaId ], properties: { rfaId: { type: string, minLength: 1, maxLength: 200 } } } } }
      responses:
        '200': { description: Retained response association, content: { application/json: { schema: { type: object, properties: { data: { type: object, required: [ faxId, rfaId, documentId, alreadyAttached ], properties: { faxId: { type: string }, rfaId: { type: string }, documentId: { type: string }, alreadyAttached: { type: boolean } } } } } } } }
        default: { $ref: '#/components/responses/Problem' }
  /browser/rfa-inbound-faxes:
    get:
      tags: [ Treatment Authorization ]
      operationId: browserListRfaInboundFaxes
      security: [{ browserSessionAuth: [] }]
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: List incoming authorization response faxes
      description: Lists only faxes attributed by verified receiving-number configuration to the authenticated partner, organization and environment. OCR suggestions never grant access. Customer-scoped and bill-scoped sessions are unsupported. Unmatched faxes are returned by default. Follow nextCursor until null.
      parameters:
        - { name: includeMatched, in: query, schema: { type: boolean, default: false } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 100 } }
        - { name: cursor, in: query, schema: { type: string }, description: Opaque nextCursor from the previous page with the same scope and includeMatched filter. }
      responses:
        '200': { description: Scoped response inbox, content: { application/json: { schema: { type: object, required: [ data, hasMore, nextCursor ], properties: { data: { type: array, items: { $ref: '#/components/schemas/RfaInboundFax' } }, hasMore: { type: boolean }, nextCursor: { type: [ string, 'null' ] } } } } } }
        default: { $ref: '#/components/responses/Problem' }
  /browser/rfa-inbound-faxes/{faxId}/content:
    get:
      tags: [ Treatment Authorization ]
      operationId: browserGetRfaInboundFaxContent
      security: [{ browserSessionAuth: [] }]
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Review an incoming authorization fax PDF
      description: Returns the authenticated source PDF after checking receiving-number attribution. A preview is not a match or a recorded utilization review decision.
      parameters:
        - { name: faxId, in: path, required: true, schema: { type: string } }
      responses:
        '200': { description: Incoming fax PDF, content: { application/pdf: { schema: { type: string, format: binary } } } }
        default: { $ref: '#/components/responses/Problem' }
  /browser/rfa-inbound-faxes/{faxId}/match:
    post:
      tags: [ Treatment Authorization ]
      operationId: browserMatchRfaInboundFax
      security: [{ browserSessionAuth: [] }]
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Match a reviewed response fax to an RFA
      description: Associates the fax with an eligible submitted RFA in the same partner, organization and environment, retains its PDF as a UR response document, and reconciles the Post UR task. Repeating the same match returns the existing document; matching to another request returns 409. A fax already associated with a bill cannot be matched. Does not infer receipt, create treatment decisions, or clear No Response tasks.
      parameters:
        - { name: faxId, in: path, required: true, schema: { type: string } }
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, additionalProperties: false, required: [ rfaId ], properties: { rfaId: { type: string, minLength: 1, maxLength: 200 } } } } }
      responses:
        '200': { description: Retained response association, content: { application/json: { schema: { type: object, properties: { data: { type: object, required: [ faxId, rfaId, documentId, alreadyAttached ], properties: { faxId: { type: string }, rfaId: { type: string }, documentId: { type: string }, alreadyAttached: { type: boolean } } } } } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfa-follow-ups:
    get:
      tags: [ Treatment Authorization ]
      operationId: listRfaFollowUps
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: List RFA follow-up tasks
      description: Requires rfas:read and treatmentBilling. Returns a page of tasks for this partner, organization and environment. Open tasks are returned by default, ordered by next follow-up time and ID. Follow nextCursor until null; cursors are bound to the authenticated scope and filters. Notes remain private to this authenticated workflow.
      parameters:
        - { name: claimId, in: query, schema: { type: string } }
        - { name: patientId, in: query, schema: { type: string } }
        - { name: renderingProviderId, in: query, schema: { type: string } }
        - { name: includeResolved, in: query, schema: { type: boolean, default: false } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 200, default: 200 } }
        - { name: cursor, in: query, schema: { type: string }, description: Opaque nextCursor from the previous page with the same filters. }
      responses:
        '200': { description: Follow-up tasks, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: '#/components/schemas/RfaFollowUp' } }, nextCursor: { type: [ string, 'null' ] } } } } } }
        default: { $ref: '#/components/responses/Problem' }
    post:
      tags: [ Treatment Authorization ]
      operationId: refreshRfaFollowUps
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Reconcile RFA follow-up conditions
      description: Requires rfas:write and treatmentBilling. Rechecks up to 500 requests in this authenticated scope. Creates or resolves tasks from recorded lifecycle evidence. Does not send an RFA or infer authorization. The scheduled worker also performs this reconciliation. Webhooks rfa.follow_up_opened, rfa.follow_up_due, rfa.follow_up_updated and rfa.follow_up_resolved contain opaque IDs and task kind, without contact notes.
      parameters: [ { $ref: '#/components/parameters/IdempotencyKey' } ]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, additionalProperties: false } } }
      responses:
        '200': { description: Reconciliation counts, content: { application/json: { schema: { type: object, properties: { data: { type: object, properties: { checked: { type: integer }, changed: { type: integer } } } } } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfa-follow-ups/{id}:
    patch:
      tags: [ Treatment Authorization ]
      operationId: updateRfaFollowUp
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Assign a task or record a contact attempt
      description: Requires rfas:write and treatmentBilling. A contact outcome requires both a note and a future follow-up time within 90 days. Tasks remain open until their underlying lifecycle condition clears; a contact outcome is not an authorization decision. Resolved or stale tasks return 409.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/UpdateRfaFollowUp' } } }
      responses:
        '200': { description: Updated follow-up, content: { application/json: { schema: { type: object, properties: { data: { $ref: '#/components/schemas/RfaFollowUp' } } } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfa-templates:
    get:
      tags: [ Treatment Authorization ]
      operationId: listRfaTemplates
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: List reusable treatment request templates
      description: Requires rfas:read and treatmentBilling. Templates are isolated by partner, organization and environment. Includes inactive templates for management.
      parameters:
        - { name: billingProviderId, in: query, schema: { type: string } }
      responses:
        '200': { description: Templates, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: '#/components/schemas/RfaTemplate' } } } } } } }
        default: { $ref: '#/components/responses/Problem' }
    post:
      tags: [ Treatment Authorization ]
      operationId: createRfaTemplate
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:create
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Save a reusable treatment request template
      description: Requires rfas:write and treatmentBilling. Templates contain service defaults, not patient details, dates, signatures or authorization evidence. Review services against the individual patient's needs before creating each RFA.
      parameters: [ { $ref: '#/components/parameters/IdempotencyKey' } ]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/SaveRfaTemplate' } } }
      responses:
        '201': { description: Template created, content: { application/json: { schema: { type: object, properties: { data: { $ref: '#/components/schemas/RfaTemplate' } } } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfa-templates/{id}:
    patch:
      tags: [ Treatment Authorization ]
      operationId: updateRfaTemplate
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:edit
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Replace template defaults or deactivate a template
      description: Requires rfas:write and treatmentBilling. Supply the complete template. Existing RFAs keep their original services.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/SaveRfaTemplate' } } }
      responses:
        '200': { description: Template updated, content: { application/json: { schema: { type: object, properties: { data: { $ref: '#/components/schemas/RfaTemplate' } } } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfas:
    get:
      tags: [ Treatment Authorization ]
      operationId: listRfas
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: List treatment authorization requests
      description: Requires rfas:read and treatmentBilling. Results are isolated by partner, organization and environment and ordered globally by the selected field with a stable ID tie-breaker (default creation time descending; null values last). Follow nextCursor until null. summary covers the complete filtered set, not only this page; byStatus retains raw workflow/clinical statuses; byLifecycleStatus groups incomplete, sent, failed, received, closed and canceled. Both omit zero results. lifecycleStatus is derived from the latest submission attempt and receipt evidence, ignoring forwards; clinical outcomes remain on status and each item. Dates are inclusive UTC creation days. Invalid filters or a cursor from different filters or scope return 422.
      parameters:
        - { name: patientId, in: query, schema: { type: string, minLength: 1, maxLength: 200 } }
        - name: search
          in: query
          schema: { type: string, maxLength: 200 }
          description: Case-insensitive literal search across RFA and external IDs, patient and physician names, claim number, claims administrator name, status and treatment codes or descriptions.
        - { name: sortBy, in: query, schema: { type: string, enum: [createdAt, employeeName, providerName, submittedAt, status, lifecycleStatus], default: createdAt } }
        - { name: sortDirection, in: query, schema: { type: string, enum: [asc, desc], default: desc } }
        - name: claimId
          in: query
          schema:
            type: string
            minLength: 1
            maxLength: 200
        - name: renderingProviderId
          in: query
          schema:
            type: string
            minLength: 1
            maxLength: 200
        - name: status
          in: query
          schema:
            $ref: "#/components/schemas/RfaStatus"
          description: Raw workflow or aggregate clinical status. May be combined with lifecycleStatus.
        - name: agingBucket
          in: query
          description: UTC calendar days since submission for unresolved sent or received RFAs. Closed, failed, canceled and incomplete requests have no aging bucket.
          schema: { type: string, enum: ['0_5', '6_14', '15_30', '31_plus'] }
        - name: lifecycleStatus
          in: query
          schema:
            $ref: "#/components/schemas/RfaLifecycleStatus"
          description: Derived delivery lifecycle; use this for incomplete, sent, failed, received, closed or canceled dashboard groups.
        - name: createdFrom
          in: query
          schema:
            type: string
            format: date
          description: Inclusive RFA creation date in UTC (YYYY-MM-DD).
        - name: createdTo
          in: query
          schema:
            type: string
            format: date
          description: Inclusive RFA creation date in UTC (YYYY-MM-DD).
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 100
        - name: cursor
          in: query
          schema:
            type: string
            minLength: 1
            maxLength: 2000
          description: Opaque nextCursor from the preceding page. Keep the same filters and authenticated scope.
      responses:
        '200': { description: RFA list, content: { application/json: { schema: { $ref: '#/components/schemas/RfaListEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
    post:
      tags: [ Treatment Authorization ]
      operationId: createRfa
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:create
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Create an RFA and its requested treatment items
      description: Requires rfas:write and treatmentBilling. Create a request, then generate and explicitly sign a reviewed form using rfas:sign, or upload an externally signed form and record its actual signedAt. Attach clinical support before sending. Signing and fax transmission are separate explicit operations. MindBill does not infer authorization from carrier silence.
      parameters: [ { $ref: '#/components/parameters/IdempotencyKey' } ]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/CreateRfaRequest' } } }
      responses:
        '201': { description: RFA created, content: { application/json: { schema: { $ref: '#/components/schemas/RfaEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}:
    get:
      tags: [ Treatment Authorization ]
      operationId: getRfa
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Retrieve an RFA with its complete lifecycle
      parameters: [ { $ref: '#/components/parameters/RfaId' } ]
      responses:
        '200': { description: RFA, content: { application/json: { schema: { $ref: '#/components/schemas/RfaEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
    patch:
      tags: [ Treatment Authorization ]
      operationId: updateRfa
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:edit
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Update RFA readiness or close its lifecycle
      parameters:
        - $ref: '#/components/parameters/RfaId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/UpdateRfaRequest' } } }
      responses:
        '200': { description: RFA updated, content: { application/json: { schema: { $ref: '#/components/schemas/RfaEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/documents:
    get:
      tags: [ Treatment Authorization ]
      operationId: listRfaDocumentSources
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: List saved PDFs available to copy into an RFA
      description: Returns accessible PDFs saved on the same injury, its bills, or the assigned billing provider library, scoped to the organization, partner and environment. These are source candidates, not the RFA's attached documents. Storage keys are never exposed. Bill-restricted browser sessions cannot use this operation.
      parameters:
        - $ref: '#/components/parameters/RfaId'
      responses:
        '200':
          description: Accessible source PDFs
          content:
            application/json:
              schema:
                type: object
                required: [ data ]
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/RfaDocumentCandidate' } }
        default: { $ref: '#/components/responses/Problem' }
    post:
      tags: [ Treatment Authorization ]
      operationId: createRfaDocument
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:edit
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Upload or copy an RFA lifecycle document
      description: Upload a PDF between 1 byte and 25 MB, or send JSON to copy an accessible saved injury, bill, or billing provider library PDF. Copies retain independent bytes and a content hash with source provenance in the audit history. JSON copies require the current contentRevision; stale revisions are rejected. The returned RFA includes the new document and updated readiness. Select the attached copy when preparing the outgoing packet.
      parameters:
        - $ref: '#/components/parameters/RfaId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CopyRfaDocumentRequest' }
          multipart/form-data:
            schema:
              type: object
              additionalProperties: false
              required: [ file, documentType ]
              properties:
                file: { type: string, format: binary }
                documentType: { $ref: '#/components/schemas/RfaDocumentType' }
                contentRevision:
                  type: integer
                  minimum: 1
      responses:
        '201': { description: Document uploaded or copied, content: { application/json: { schema: { $ref: '#/components/schemas/RfaEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/documents/{documentId}:
    get:
      tags: [ Treatment Authorization ]
      operationId: getRfaDocument
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: documents:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Download an RFA lifecycle PDF
      parameters:
        - $ref: '#/components/parameters/RfaId'
        - $ref: '#/components/parameters/RfaDocumentId'
      responses:
        '200':
          description: RFA document
          headers:
            Content-Disposition: { schema: { type: string } }
          content: { application/pdf: { schema: { type: string, format: binary } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/document-library:
    get:
      tags: [ Treatment Authorization ]
      operationId: listRfaDocumentLibrary
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: List the billing provider document library
      description: The billing provider is derived from the authorized RFA claim. Access is limited to the same organization, partner and environment. Storage keys are never exposed. Returns billingProviderId null and no documents when the claim has no assigned provider. canManage reflects current library management permissions.
      parameters:
        - $ref: '#/components/parameters/RfaId'
      responses:
        '200': { description: List the billing provider document library, content: { application/json: { schema: { $ref: '#/components/schemas/RfaLibraryListEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
    post:
      tags: [ Treatment Authorization ]
      operationId: createRfaLibraryDocument
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:edit
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Upload an immutable billing provider library PDF
      description: The billing provider is derived from the authorized RFA claim. Access is limited to the same organization, partner and environment. Storage keys are never exposed. Library changes also require orgs:write for server keys, organization:manage for embedded sessions, or current active organization administrator permissions for native browser users. Existing RFA copies remain independent of library changes. Send expectedBillingProviderId from the library list; the server rejects a changed claim provider with 409. Accepts one PDF of 1 byte to 25 MB. Retry an uncertain response with the same Idempotency-Key and unchanged file and metadata.
      parameters:
        - $ref: '#/components/parameters/RfaId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              additionalProperties: false
              required: [ file, expectedBillingProviderId ]
              properties:
                file: { type: string, format: binary }
                expectedBillingProviderId: { type: string, minLength: 1, description: Billing provider ID from the latest library list; a precondition only. A changed provider returns 409. }
                description: { type: string, maxLength: 500, default: '' }
                reportType: { type: string, minLength: 1, maxLength: 100, default: Supporting Document }
      responses:
        '201': { description: Upload an immutable billing provider library PDF, content: { application/json: { schema: { $ref: '#/components/schemas/RfaLibraryDocumentEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/document-library/{documentId}:
    get:
      tags: [ Treatment Authorization ]
      operationId: getRfaLibraryDocument
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Download a billing provider library PDF
      description: The billing provider is derived from the authorized RFA claim. Access is limited to the same organization, partner and environment. Storage keys are never exposed.
      parameters:
        - $ref: '#/components/parameters/RfaId'
        - $ref: '#/components/parameters/RfaDocumentId'
      responses:
        '200': { description: Download a billing provider library PDF, content: { application/pdf: { schema: { type: string, format: binary } } } }
        default: { $ref: '#/components/responses/Problem' }
    patch:
      tags: [ Treatment Authorization ]
      operationId: updateRfaLibraryDocument
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:edit
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Edit library document metadata
      description: The billing provider is derived from the authorized RFA claim. Access is limited to the same organization, partner and environment. Storage keys are never exposed. Library changes also require orgs:write for server keys, organization:manage for embedded sessions, or current active organization administrator permissions for native browser users. Existing RFA copies remain independent of library changes. Send the last returned updatedAt; a concurrent metadata edit returns 409 library_document_changed. File bytes and filename are immutable.
      parameters:
        - $ref: '#/components/parameters/RfaId'
        - $ref: '#/components/parameters/RfaDocumentId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [ updatedAt ]
              properties:
                updatedAt: { type: string, format: date-time }
                description: { type: string, maxLength: 500, default: '' }
                reportType: { type: string, minLength: 1, maxLength: 100, default: Supporting Document }
      responses:
        '200': { description: Edit library document metadata, content: { application/json: { schema: { $ref: '#/components/schemas/RfaLibraryDocumentEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
    delete:
      tags: [ Treatment Authorization ]
      operationId: archiveRfaLibraryDocument
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:edit
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Archive a library PDF while preserving existing RFA copies
      description: The billing provider is derived from the authorized RFA claim. Access is limited to the same organization, partner and environment. Storage keys are never exposed. Library changes also require orgs:write for server keys, organization:manage for embedded sessions, or current active organization administrator permissions for native browser users. Existing RFA copies remain independent of library changes.
      parameters:
        - $ref: '#/components/parameters/RfaId'
        - $ref: '#/components/parameters/RfaDocumentId'
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '200': { description: Archive a library PDF while preserving existing RFA copies, content: { application/json: { schema: { $ref: '#/components/schemas/RfaLibraryArchiveEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/transmissions:
    post:
      tags: [ Treatment Authorization ]
      operationId: recordRfaTransmission
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Record submission, delivery, or receipt evidence
      description: >-
        A sent, delivered, or received record requires a provider message ID or a previously uploaded proof document. Recording carrier receipt starts the applicable 72-hour, five-business-day, or 30-calendar-day decision clock.
      parameters:
        - $ref: '#/components/parameters/RfaId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/RecordRfaTransmissionRequest' } } }
      responses:
        '201': { description: Transmission recorded, content: { application/json: { schema: { $ref: '#/components/schemas/RfaEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/information-requests:
    post:
      tags: [ Treatment Authorization ]
      operationId: createRfaInformationRequest
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Record a utilization-review request for additional information
      parameters:
        - $ref: '#/components/parameters/RfaId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/CreateRfaInformationRequestRequest' } } }
      responses:
        '201': { description: Information request recorded, content: { application/json: { schema: { $ref: '#/components/schemas/RfaEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/information-receipt-review:
    post:
      tags: [ Treatment Authorization ]
      operationId: reviewRfaInformationReceipt
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Review evidence of complete supplemental information receipt
      description: >-
        Records an immutable review for standard prospective or concurrent missing-information requests under 8 CCR 9792.9.6(a)(1)(A).
        All recorded requests must have responses, be timely within five business days of the original complete receipt, and be covered by the review.
        Actual supplemental receipt must follow every response, be within fourteen calendar days of the complete request, and not be in the future.
        The original receipt must match the stored receipt instant. Same-RFA evidence documents and all explicit attestations are required.
        The effective deadline is the end of the fifth business day after actual supplemental receipt in America/Los_Angeles.
        The original baseline is retained. Any newer exception invalidates this review. Unsupported history, special review rules, or an unverified calendar returns 422; stale or already reviewed exception evidence returns 409.
      parameters:
        - $ref: '#/components/parameters/RfaId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/ReviewRfaInformationReceiptRequest' } } }
      responses:
        '201': { description: Receipt evidence reviewed, content: { application/json: { schema: { $ref: '#/components/schemas/RfaEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/information-requests/{requestId}:
    post:
      tags: [ Treatment Authorization ]
      operationId: respondRfaInformationRequest
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Record a response to an additional-information request
      description: Every response document ID must refer to a PDF already uploaded to this RFA.
      parameters:
        - $ref: '#/components/parameters/RfaId'
        - $ref: '#/components/parameters/RfaInformationRequestId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/RespondRfaInformationRequestRequest' } } }
      responses:
        '200': { description: Information response recorded, content: { application/json: { schema: { $ref: '#/components/schemas/RfaEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/decisions:
    post:
      tags: [ Treatment Authorization ]
      operationId: recordRfaDecision
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Record item-level utilization-review decisions
      description: >-
        Decisions may be mixed across requested treatment items. Approved and modified items require an authorization number. Modified or denied items require the reviewing physician's name, phone, reason, and an uploaded official IMR form.
      parameters:
        - $ref: '#/components/parameters/RfaId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/RecordRfaDecisionRequest' } } }
      responses:
        '201': { description: Decision recorded, content: { application/json: { schema: { $ref: '#/components/schemas/RfaEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/decision-corrections:
    post:
      tags: [ Treatment Authorization ]
      operationId: correctRfaDecision
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Correct one recorded treatment decision before scheduling or billing
      description: >-
        Explicitly replaces the current decision for exactly one item while retaining the original decision and correction reason in the immutable RFA audit trail.
        Read the RFA first and pass the selected item's currentDecisionEventId as expectedDecisionEventId.
        The replacement must contain exactly one decision for that same item, with a same-RFA ur_response PDF and an imr_form PDF when modified or denied.
        Omitted optional decision fields are cleared; this is a complete replacement, not a partial update.
        The decision timestamp cannot be in the future or precede stored submission or receipt.
        Any bill linked to any item on the RFA, or any currently scheduled item, blocks correction.
        A stale expected event returns 409 rfa_decision_changed; bill and scheduling conflicts return 409 rfa_decision_correction_bill_linked and rfa_decision_correction_scheduled.
        Invalid chronology returns 422 rfa_decision_date_invalid. Success emits rfa.decision_corrected and returns updated per-item current decision and evidence IDs.
      parameters:
        - $ref: '#/components/parameters/RfaId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/CorrectRfaDecisionRequest' } } }
      responses:
        '201': { description: Decision corrected with immutable history retained, content: { application/json: { schema: { $ref: '#/components/schemas/RfaEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
  /rfas/{rfaId}/events:
    get:
      tags: [ Treatment Authorization ]
      operationId: listRfaEvents
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: List the immutable RFA audit trail
      parameters: [ { $ref: '#/components/parameters/RfaId' } ]
      responses:
        '200': { description: RFA events, content: { application/json: { schema: { $ref: '#/components/schemas/RfaEventListEnvelope' } } } }
        default: { $ref: '#/components/responses/Problem' }
    post:
      tags: [ Treatment Authorization ]
      operationId: addRfaNote
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:edit
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Add an immutable RFA history note
      description: Adds a note without changing request content, signature, decisions or submission state. Note text is available in authorized history; webhook events contain only identifiers.
      parameters: [ { $ref: '#/components/parameters/RfaId' }, { $ref: '#/components/parameters/IdempotencyKey' } ]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [text]
              properties:
                text: { type: string, minLength: 1, maxLength: 10000, description: Trimmed non-empty note text. }
      responses:
        '201':
          description: Saved note event
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data: { $ref: '#/components/schemas/RfaEvent' }
        default: { $ref: '#/components/responses/Problem' }
  /browser-sessions:
    post:
      tags:
        - Browser sessions
      operationId: createBrowserSession
      summary: Mint an origin-bound browser session
      description: |
        Exchange the server-only API key for a short-lived token. The workspace billing
        context is inferred from the key; no organization header is required. Derive
        resource.customerExternalId from your authenticated host user to allow creation
        and access only within that customer. MindBill stamps the customer on new resources
        and enforces it on reads, actions, documents, lists and reports. subject is audit
        identity, not an access boundary. Include resource.billId for an existing-bill-only
        session; both restrictions may be combined. Customer sessions cannot use shared
        provider profiles, organization:manage, team:manage, autofill:run or RFA permissions. Omit resource only for
        workspace administrators who may access all workspace bills. The browser calls
        MindBill directly with this token; the permanent API key stays on your server.
        Delegating team:manage requires explicit orgs:team:write on the server credential
        and an organization-wide session. organization:manage does not grant team access.
        Delegating autofill:run requires explicit autofill:write on an operator credential,
        an approved reportAutofill capability and an organization-wide session.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required:
                - subject
                - allowedOrigin
                - permissions
              properties:
                subject:
                  type: string
                  minLength: 1
                  maxLength: 255
                  description: Stable ID for the signed-in user.
                allowedOrigin:
                  type: string
                  format: uri
                  description: Exact HTTPS browser origin with no path.
                permissions:
                  type: array
                  minItems: 1
                  maxItems: 14
                  uniqueItems: true
                  items:
                    $ref: '#/components/schemas/BrowserPermission'
                  description: Actions authorized for this user by your server.
                resource:
                  type: object
                  additionalProperties: false
                  anyOf:
                    - required: [ billId ]
                    - required: [ customerExternalId ]
                  properties:
                    billId:
                      type: string
                      description: Restrict access to one existing bill. Cannot include bills:create, team:manage or any rfas permission. Organization settings collections are also unavailable.
                    customerExternalId:
                      type: string
                      minLength: 1
                      maxLength: 255
                      description: Stable host-owned customer ID, derived by your authenticated backend. New bills inherit this scope. Cannot include organization:manage, team:manage or any rfas permission.
                expiresIn:
                  type: integer
                  minimum: 60
                  maximum: 3600
                  default: 900
                  description: Token lifetime in seconds.
      responses:
        '201':
          description: Short-lived browser session.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BrowserSession'
        default:
          $ref: '#/components/responses/Problem'
      security:
        - bearerAuth: []
  /rfas/{rfaId}/draft:
    parameters:
      - $ref: "#/components/parameters/RfaId"
    patch:
      tags:
        - Treatment Authorization
      operationId: editRfaDraft
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:edit
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Replace an unsent RFA draft
      description: Requires rfas:write and treatmentBilling. Supply the complete editable content and expectedRevision. Claim, patient and rendering-provider identities cannot change. Existing item IDs preserve the selected items; omitted items are removed. Successful replacement increments contentRevision, clears signing evidence and requires a new form for the current revision. Stale revisions or submitted requests return 409.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/EditRfaDraftRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaEnvelope"
        default:
          $ref: "#/components/responses/Problem"
  /rfas/{rfaId}/copy:
    parameters:
      - $ref: "#/components/parameters/RfaId"
    post:
      tags:
        - Treatment Authorization
      operationId: copyRfa
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:create
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Copy an RFA into a fresh draft
      description: Requires rfas:write and treatmentBilling. Copy the exact expectedRevision into a new request with the same authorized identities and requested services. Signatures, authorization decisions, documents and transmission evidence are not copied.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CopyRfaRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaEnvelope"
        default:
          $ref: "#/components/responses/Problem"
  /rfas/{rfaId}/signing-preview:
    parameters:
      - $ref: "#/components/parameters/RfaId"
    post:
      tags:
        - Treatment Authorization
      operationId: previewRfaSigning
      x-mindbill-access:
        serverScope: rfas:sign
        browserPermission: rfas:sign
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Prepare an RFA for physician review
      description: Requires rfas:sign and treatmentBilling. Prepare an immutable unsigned preview of the current revision and saved provider signature. Diagnosis descriptions must cover exactly every RFA item. Review previewDocumentId through the scoped document download before signing. The snapshot expires after 30 minutes. This operation does not sign or send the request.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RfaFormRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaSigningPreview"
        default:
          $ref: "#/components/responses/Problem"
  /rfas/{rfaId}/sign:
    parameters:
      - $ref: "#/components/parameters/RfaId"
    post:
      tags:
        - Treatment Authorization
      operationId: signRfa
      x-mindbill-access:
        serverScope: rfas:sign
        browserPermission: rfas:sign
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Sign the reviewed RFA
      description: Requires rfas:sign and treatmentBilling. Explicitly attest physician authorization for the reviewed snapshot, content hash and rendering provider. Requires an unsent request and unchanged content revision and saved signature. Binds the resulting signed document to that exact review; expired or stale snapshots return 409. The sign scope is separate from write or act permission. This does not send the request.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SignRfaRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaEnvelope"
        default:
          $ref: "#/components/responses/Problem"
  /rfas/{rfaId}/delivery-preview:
    parameters:
      - $ref: "#/components/parameters/RfaId"
    post:
      tags: [Treatment Authorization]
      operationId: prepareRfaDelivery
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Prepare the exact RFA packet for review
      description: Retain an immutable signed packet with the selected delivery channel, recipient and optional message on its cover. Requires one current signed form and clinical support. Download the returned packetId using the retained-packet endpoint and review its bytes before submitting. Preparation does not send or change receipt clocks and is available in sandbox. Maximum 20 MB and 500 pages.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RfaDeliveryPreviewRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaDeliveryPreviewEnvelope"
        default:
          $ref: "#/components/responses/Problem"
  /rfas/{rfaId}/submit:
    parameters:
      - $ref: "#/components/parameters/RfaId"
    post:
      tags: [Treatment Authorization]
      operationId: submitRfaDelivery
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Submit a reviewed RFA by fax or email
      description: Submit exactly the retained packet and destination reviewed through delivery-preview. The SHA-256, channel, destination, message, signed content revision and document hashes must still match; changes require a fresh preview. Live environment and enabled transport are required; sandbox never dispatches. Accepted delivery marks submitted, not received. Uncertain attempts block automatic retries; an identical accepted retry only recovers bookkeeping.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RfaDeliverySubmitRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaDeliverySubmitEnvelope"
        default:
          $ref: "#/components/responses/Problem"
  /browser/rfas/providers/{providerId}/signature:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - in: path
        name: providerId
        required: true
        schema: { type: string, minLength: 1 }
    post:
      tags: [Treatment Authorization]
      operationId: browserSaveRfaProviderSignature
      x-mindbill-access:
        browserPermission: rfas:sign
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Configure an authorized physician signature
      description: Requires both rfas:sign and organization:manage in an organization-wide browser session. Customer-scoped or bill-scoped sessions cannot configure signatures. Saves an authorized PNG for the selected active rendering provider and records an attestation. Does not sign a request; review and sign each generated RFA separately.
      security:
        - browserSessionAuth: []
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RfaProviderSignatureRequest"
      responses:
        "200":
          description: Signature saved.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: object
                    required: [providerId, signatureConfigured]
                    properties:
                      providerId: { type: string }
                      signatureConfigured: { type: boolean, const: true }
        default:
          $ref: "#/components/responses/Problem"
  /browser/rfas/{rfaId}/delivery-preview:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: "#/components/parameters/RfaId"
    post:
      tags: [Treatment Authorization]
      operationId: browserPrepareRfaDelivery
      x-mindbill-access:
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Prepare the exact RFA packet for review
      description: Retain an immutable signed packet with the selected delivery channel, recipient and optional message on its cover. Requires one current signed form and clinical support. Download the returned packetId using the retained-packet endpoint and review its bytes before submitting. Preparation does not send or change receipt clocks and is available in sandbox. Maximum 20 MB and 500 pages.
      security:
        - browserSessionAuth: []
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RfaDeliveryPreviewRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaDeliveryPreviewEnvelope"
        default:
          $ref: "#/components/responses/Problem"
  /browser/rfas/{rfaId}/submit:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: "#/components/parameters/RfaId"
    post:
      tags: [Treatment Authorization]
      operationId: browserSubmitRfaDelivery
      x-mindbill-access:
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Submit a reviewed RFA by fax or email
      description: Submit exactly the retained packet and destination reviewed through delivery-preview. The SHA-256, channel, destination, message, signed content revision and document hashes must still match; changes require a fresh preview. Live environment and enabled transport are required; sandbox never dispatches. Accepted delivery marks submitted, not received. Uncertain attempts block automatic retries; an identical accepted retry only recovers bookkeeping.
      security:
        - browserSessionAuth: []
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RfaDeliverySubmitRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaDeliverySubmitEnvelope"
        default:
          $ref: "#/components/responses/Problem"
  /rfas/{rfaId}/packets:
    parameters:
      - $ref: "#/components/parameters/RfaId"
    get:
      tags:
        - Treatment Authorization
      operationId: listRfaPackets
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: List immutable RFA packets and sent history
      description: Requires rfas:read and treatmentBilling. Lists retained packet metadata and outbound transmission attempts, including separate forwarding attempts. A legacy transmission with packetId null has no retained original packet; regenerating it does not recover its original bytes.
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaPacketHistoryEnvelope"
        default:
          $ref: "#/components/responses/Problem"
    post:
      tags:
        - Treatment Authorization
      operationId: retainRfaPacket
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Retain a signed RFA packet
      description: Requires rfas:write and treatmentBilling. Assemble and retain exact PDF bytes from the selected current signed form and clinical support. Validates document ownership, revision, signature identity, hashes and PDF content. Maximum 20 MB and 500 pages. Creates download history without changing submission or receipt clocks.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RetainRfaPacketRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaPacketEnvelope"
        default:
          $ref: "#/components/responses/Problem"
  /rfas/{rfaId}/forwards:
    parameters:
      - $ref: "#/components/parameters/RfaId"
    post:
      tags:
        - Treatment Authorization
      operationId: forwardRfaPacket
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Forward an original RFA packet
      description: Requires rfas:write and treatmentBilling. Forward the exact retained packet bytes to an explicit fax number or email recipient. Requires live environment and enabled delivery for the chosen channel. A submission snapshot requires an accepted original submission; downloaded snapshots can also be forwarded. Records a separate forward attempt and preserves original submission, receipt and utilization-review deadlines. Retrying a queued or uncertain attempt cannot send duplicates; reconcile uncertain delivery before trying again. A 502 can mean the transport outcome is uncertain and evidence is retained.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ForwardRfaPacketRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaForwardEnvelope"
        default:
          $ref: "#/components/responses/Problem"
  /rfas/{rfaId}/packets/{packetId}:
    parameters:
      - $ref: "#/components/parameters/RfaId"
      - name: packetId
        in: path
        required: true
        schema:
          type: string
    get:
      tags:
        - Treatment Authorization
      operationId: downloadRetainedRfaPacket
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Download the original retained RFA packet
      description: "Requires rfas:read and treatmentBilling. Returns the original immutable PDF bytes after hash and size verification. Missing or out-of-scope packets return 404; mismatched stored bytes return 409. Response uses Cache-Control: no-store."
      responses:
        "200":
          description: Original retained PDF.
          content:
            application/pdf:
              schema:
                type: string
                format: binary
        default:
          $ref: "#/components/responses/Problem"
  /rfas/export:
    get:
      tags:
        - Treatment Authorization
      operationId: exportRfas
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Export requested treatments and authorization outcomes
      description: Requires rfas:read and treatmentBilling. Exports the complete filtered set as CSV, one row per treatment item, including request IDs, provider, raw status, derived lifecycle_status, dates, requested service and written authorization fields. Pagination cursors are rejected. More than 50,000 treatment rows returns 413; narrow the filters. Spreadsheet formula cells are neutralized.
      parameters:
        - { name: patientId, in: query, schema: { type: string, minLength: 1, maxLength: 200 } }
        - name: search
          in: query
          schema: { type: string, maxLength: 200 }
          description: Case-insensitive literal search across RFA and external IDs, patient and physician names, claim number, claims administrator name, status and treatment codes or descriptions.
        - name: claimId
          in: query
          schema:
            type: string
            minLength: 1
            maxLength: 200
        - name: renderingProviderId
          in: query
          schema:
            type: string
            minLength: 1
            maxLength: 200
        - name: status
          in: query
          schema:
            $ref: "#/components/schemas/RfaStatus"
          description: Raw workflow or aggregate clinical status. May be combined with lifecycleStatus.
        - name: agingBucket
          in: query
          description: UTC calendar days since submission for unresolved sent or received RFAs. Closed, failed, canceled and incomplete requests have no aging bucket.
          schema: { type: string, enum: ['0_5', '6_14', '15_30', '31_plus'] }
        - name: lifecycleStatus
          in: query
          schema:
            $ref: "#/components/schemas/RfaLifecycleStatus"
          description: Derived delivery lifecycle; use this for incomplete, sent, failed, received, closed or canceled dashboard groups.
        - name: createdFrom
          in: query
          schema:
            type: string
            format: date
          description: Inclusive RFA creation date in UTC (YYYY-MM-DD).
        - name: createdTo
          in: query
          schema:
            type: string
            format: date
          description: Inclusive RFA creation date in UTC (YYYY-MM-DD).
      responses:
        "200":
          description: Treatment rows in CSV format.
          content:
            text/csv:
              schema:
                type: string
        default:
          $ref: "#/components/responses/Problem"
  /browser/rfas/{rfaId}/draft:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: "#/components/parameters/RfaId"
    patch:
      tags:
        - Treatment Authorization
      operationId: browserEditRfaDraft
      x-mindbill-access:
        browserPermission: rfas:edit
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Replace an unsent RFA draft
      description: Requires rfas:edit and treatmentBilling. Uses a scoped browser-session bearer token and its allowed Origin. Supply the complete editable content and expectedRevision. Claim, patient and rendering-provider identities cannot change. Existing item IDs preserve the selected items; omitted items are removed. Successful replacement increments contentRevision, clears signing evidence and requires a new form for the current revision. Stale revisions or submitted requests return 409.
      security:
        - browserSessionAuth: []
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/EditRfaDraftRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaEnvelope"
        default:
          $ref: "#/components/responses/Problem"
  /browser/rfas/{rfaId}/copy:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: "#/components/parameters/RfaId"
    post:
      tags:
        - Treatment Authorization
      operationId: browserCopyRfa
      x-mindbill-access:
        browserPermission: rfas:create
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Copy an RFA into a fresh draft
      description: Requires rfas:create and treatmentBilling. Uses a scoped browser-session bearer token and its allowed Origin. Copy the exact expectedRevision into a new request with the same authorized identities and requested services. Signatures, authorization decisions, documents and transmission evidence are not copied.
      security:
        - browserSessionAuth: []
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CopyRfaRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaEnvelope"
        default:
          $ref: "#/components/responses/Problem"
  /browser/rfas/{rfaId}/signing-preview:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: "#/components/parameters/RfaId"
    post:
      tags:
        - Treatment Authorization
      operationId: browserPreviewRfaSigning
      x-mindbill-access:
        browserPermission: rfas:sign
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Prepare an RFA for physician review
      description: Requires rfas:sign and treatmentBilling. Uses a scoped browser-session bearer token and its allowed Origin. Prepare an immutable unsigned preview of the current revision and saved provider signature. Diagnosis descriptions must cover exactly every RFA item. Review previewDocumentId through the scoped document download before signing. The snapshot expires after 30 minutes. This operation does not sign or send the request.
      security:
        - browserSessionAuth: []
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RfaFormRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaSigningPreview"
        default:
          $ref: "#/components/responses/Problem"
  /browser/rfas/{rfaId}/sign:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: "#/components/parameters/RfaId"
    post:
      tags:
        - Treatment Authorization
      operationId: browserSignRfa
      x-mindbill-access:
        browserPermission: rfas:sign
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Sign the reviewed RFA
      description: Requires rfas:sign and treatmentBilling. Uses a scoped browser-session bearer token and its allowed Origin. Explicitly attest physician authorization for the reviewed snapshot, content hash and rendering provider. Requires an unsent request and unchanged content revision and saved signature. Binds the resulting signed document to that exact review; expired or stale snapshots return 409. The sign scope is separate from write or act permission. This does not send the request.
      security:
        - browserSessionAuth: []
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SignRfaRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaEnvelope"
        default:
          $ref: "#/components/responses/Problem"
  /browser/rfas/{rfaId}/packets:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: "#/components/parameters/RfaId"
    get:
      tags:
        - Treatment Authorization
      operationId: browserListRfaPackets
      x-mindbill-access:
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: List immutable RFA packets and sent history
      description: Requires rfas:read and treatmentBilling. Uses a scoped browser-session bearer token and its allowed Origin. Lists retained packet metadata and outbound transmission attempts, including separate forwarding attempts. A legacy transmission with packetId null has no retained original packet; regenerating it does not recover its original bytes.
      security:
        - browserSessionAuth: []
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaPacketHistoryEnvelope"
        default:
          $ref: "#/components/responses/Problem"
    post:
      tags:
        - Treatment Authorization
      operationId: browserRetainRfaPacket
      x-mindbill-access:
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Retain a signed RFA packet
      description: Requires rfas:act and treatmentBilling. Uses a scoped browser-session bearer token and its allowed Origin. Assemble and retain exact PDF bytes from the selected current signed form and clinical support. Validates document ownership, revision, signature identity, hashes and PDF content. Maximum 20 MB and 500 pages. Creates download history without changing submission or receipt clocks.
      security:
        - browserSessionAuth: []
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RetainRfaPacketRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaPacketEnvelope"
        default:
          $ref: "#/components/responses/Problem"
  /browser/rfas/{rfaId}/forwards:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: "#/components/parameters/RfaId"
    post:
      tags:
        - Treatment Authorization
      operationId: browserForwardRfaPacket
      x-mindbill-access:
        browserPermission: rfas:act
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Forward an original RFA packet
      description: Requires rfas:act and treatmentBilling. Uses a scoped browser-session bearer token and its allowed Origin. Forward the exact retained packet bytes to an explicit fax number or email recipient. Requires live environment and enabled delivery for the chosen channel. A submission snapshot requires an accepted original submission; downloaded snapshots can also be forwarded. Records a separate forward attempt and preserves original submission, receipt and utilization-review deadlines. Retrying a queued or uncertain attempt cannot send duplicates; reconcile uncertain delivery before trying again. A 502 can mean the transport outcome is uncertain and evidence is retained.
      security:
        - browserSessionAuth: []
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ForwardRfaPacketRequest"
      responses:
        "200":
          description: Scoped result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaForwardEnvelope"
        default:
          $ref: "#/components/responses/Problem"
  /browser/rfas/{rfaId}/packets/{packetId}:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: "#/components/parameters/RfaId"
      - name: packetId
        in: path
        required: true
        schema:
          type: string
    get:
      tags:
        - Treatment Authorization
      operationId: browserDownloadRetainedRfaPacket
      x-mindbill-access:
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Download the original retained RFA packet
      description: "Requires rfas:read and treatmentBilling. Uses a scoped browser-session token and allowed Origin. Returns the original immutable PDF bytes after hash and size verification. Missing or out-of-scope packets return 404; mismatched stored bytes return 409. Response uses Cache-Control: no-store."
      security:
        - browserSessionAuth: []
      responses:
        "200":
          description: Original retained PDF.
          content:
            application/pdf:
              schema:
                type: string
                format: binary
        default:
          $ref: "#/components/responses/Problem"
  /browser/rfas/export:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
    get:
      tags:
        - Treatment Authorization
      operationId: browserExportRfas
      x-mindbill-access:
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Export requested treatments and authorization outcomes
      description: Requires rfas:read and treatmentBilling. Uses a scoped browser-session token and allowed Origin. Exports the complete filtered set as CSV, one row per treatment item, including request IDs, provider, raw status, derived lifecycle_status, dates, requested service and written authorization fields. Pagination cursors are rejected. More than 50,000 treatment rows returns 413; narrow the filters. Spreadsheet formula cells are neutralized.
      parameters:
        - { name: patientId, in: query, schema: { type: string, minLength: 1, maxLength: 200 } }
        - name: search
          in: query
          schema: { type: string, maxLength: 200 }
          description: Case-insensitive literal search across RFA and external IDs, patient and physician names, claim number, claims administrator name, status and treatment codes or descriptions.
        - name: claimId
          in: query
          schema:
            type: string
            minLength: 1
            maxLength: 200
        - name: renderingProviderId
          in: query
          schema:
            type: string
            minLength: 1
            maxLength: 200
        - name: status
          in: query
          schema:
            $ref: "#/components/schemas/RfaStatus"
          description: Raw workflow or aggregate clinical status. May be combined with lifecycleStatus.
        - name: agingBucket
          in: query
          description: UTC calendar days since submission for unresolved sent or received RFAs. Closed, failed, canceled and incomplete requests have no aging bucket.
          schema: { type: string, enum: ['0_5', '6_14', '15_30', '31_plus'] }
        - name: lifecycleStatus
          in: query
          schema:
            $ref: "#/components/schemas/RfaLifecycleStatus"
          description: Derived delivery lifecycle; use this for incomplete, sent, failed, received, closed or canceled dashboard groups.
        - name: createdFrom
          in: query
          schema:
            type: string
            format: date
          description: Inclusive RFA creation date in UTC (YYYY-MM-DD).
        - name: createdTo
          in: query
          schema:
            type: string
            format: date
          description: Inclusive RFA creation date in UTC (YYYY-MM-DD).
      security:
        - browserSessionAuth: []
      responses:
        "200":
          description: Treatment rows in CSV format.
          content:
            text/csv:
              schema:
                type: string
        default:
          $ref: "#/components/responses/Problem"
  /browser/rfas:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
    get:
      tags:
        - Treatment Authorization
      operationId: browserListRfas
      x-mindbill-access:
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: List treatment authorization requests
      description: Requires rfas:read and treatmentBilling. Results are isolated by partner, organization and environment and ordered globally by the selected field with a stable ID tie-breaker (default creation time descending; null values last). Follow nextCursor until null. summary covers the complete filtered set, not only this page; byStatus retains raw workflow/clinical statuses; byLifecycleStatus groups incomplete, sent, failed, received, closed and canceled. Both omit zero results. lifecycleStatus is derived from the latest submission attempt and receipt evidence, ignoring forwards; clinical outcomes remain on status and each item. Dates are inclusive UTC creation days. Invalid filters or a cursor from different filters or scope return 422. Uses a scoped browser-session bearer token and allowed Origin.
      parameters:
        - { name: patientId, in: query, schema: { type: string, minLength: 1, maxLength: 200 } }
        - name: search
          in: query
          schema: { type: string, maxLength: 200 }
          description: Case-insensitive literal search across RFA and external IDs, patient and physician names, claim number, claims administrator name, status and treatment codes or descriptions.
        - { name: sortBy, in: query, schema: { type: string, enum: [createdAt, employeeName, providerName, submittedAt, status, lifecycleStatus], default: createdAt } }
        - { name: sortDirection, in: query, schema: { type: string, enum: [asc, desc], default: desc } }
        - name: claimId
          in: query
          schema:
            type: string
            minLength: 1
            maxLength: 200
        - name: renderingProviderId
          in: query
          schema:
            type: string
            minLength: 1
            maxLength: 200
        - name: status
          in: query
          schema:
            $ref: "#/components/schemas/RfaStatus"
          description: Raw workflow or aggregate clinical status. May be combined with lifecycleStatus.
        - name: agingBucket
          in: query
          description: UTC calendar days since submission for unresolved sent or received RFAs. Closed, failed, canceled and incomplete requests have no aging bucket.
          schema: { type: string, enum: ['0_5', '6_14', '15_30', '31_plus'] }
        - name: lifecycleStatus
          in: query
          schema:
            $ref: "#/components/schemas/RfaLifecycleStatus"
          description: Derived delivery lifecycle; use this for incomplete, sent, failed, received, closed or canceled dashboard groups.
        - name: createdFrom
          in: query
          schema:
            type: string
            format: date
          description: Inclusive RFA creation date in UTC (YYYY-MM-DD).
        - name: createdTo
          in: query
          schema:
            type: string
            format: date
          description: Inclusive RFA creation date in UTC (YYYY-MM-DD).
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 100
        - name: cursor
          in: query
          schema:
            type: string
            minLength: 1
            maxLength: 2000
          description: Opaque nextCursor from the preceding page. Keep the same filters and authenticated scope.
      responses:
        "200":
          description: RFA list
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RfaListEnvelope"
        default:
          $ref: "#/components/responses/Problem"
      security:
        - browserSessionAuth: []
  /rfas/{rfaId}/scheduling:
    parameters:
      - $ref: "#/components/parameters/RfaId"
    get:
      tags: [ Treatment Authorization ]
      operationId: listRfaScheduling
      x-mindbill-access:
        serverScope: rfas:read
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: List treatment scheduling
      description: Requires rfas:read and treatmentBilling. Lists requested services and scheduling state. version starts at zero; current is false until a disposition is saved against the current written authorization. A changed authorization makes the saved disposition stale and reopens schedule_treatment follow-up. eligible requires approved or modified treatment with a written authorization number on an open request.
      responses:
        "200":
          description: Scheduling state for all requested services.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RfaSchedulingEnvelope" }
        default: { $ref: "#/components/responses/Problem" }
  /rfas/{rfaId}/items/{itemId}/scheduling:
    parameters:
      - $ref: "#/components/parameters/RfaId"
      - name: itemId
        in: path
        required: true
        schema: { type: string }
    patch:
      tags: [ Treatment Authorization ]
      operationId: updateRfaScheduling
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:edit
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Update treatment scheduling
      description: Requires rfas:write and treatmentBilling. Record an appointment, a reason no appointment is needed, or cancellation. Supply version and authorizationToken from the latest scheduling read. Stale authorization or version returns 409; a missing scoped item returns 404. Approved or modified treatment with a written authorization number is required for scheduled and no_appointment dispositions. Appointment dates must fall within the authorization period in America/Los_Angeles or return 422. Cancellation requires an existing scheduling record, is allowed after authorization is revoked, and reopens follow-up only while the item remains eligible. Scheduling records track one appointment per requested service; they do not book an appointment with an external provider. Returns all scheduling rows for this request. Emits rfa.updated with action scheduling_updated, itemId, disposition and version; webhook payloads omit appointment details.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/UpdateRfaSchedulingRequest" }
      responses:
        "200":
          description: Scheduling state for all requested services.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RfaSchedulingEnvelope" }
        default: { $ref: "#/components/responses/Problem" }
  /browser/rfas/{rfaId}/scheduling:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: "#/components/parameters/RfaId"
    get:
      tags: [ Treatment Authorization ]
      operationId: browserListRfaScheduling
      x-mindbill-access:
        browserPermission: rfas:read
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: List treatment scheduling
      description: Requires rfas:read and treatmentBilling. Lists requested services and scheduling state. version starts at zero; current is false until a disposition is saved against the current written authorization. A changed authorization makes the saved disposition stale and reopens schedule_treatment follow-up. eligible requires approved or modified treatment with a written authorization number on an open request.
      security:
        - browserSessionAuth: []
      responses:
        "200":
          description: Scheduling state for all requested services.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RfaSchedulingEnvelope" }
        default: { $ref: "#/components/responses/Problem" }
  /browser/rfas/{rfaId}/items/{itemId}/scheduling:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: "#/components/parameters/RfaId"
      - name: itemId
        in: path
        required: true
        schema: { type: string }
    patch:
      tags: [ Treatment Authorization ]
      operationId: browserUpdateRfaScheduling
      x-mindbill-access:
        browserPermission: rfas:edit
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Update treatment scheduling
      description: Requires rfas:edit and treatmentBilling. Record an appointment, a reason no appointment is needed, or cancellation. Supply version and authorizationToken from the latest scheduling read. Stale authorization or version returns 409; a missing scoped item returns 404. Approved or modified treatment with a written authorization number is required for scheduled and no_appointment dispositions. Appointment dates must fall within the authorization period in America/Los_Angeles or return 422. Cancellation requires an existing scheduling record, is allowed after authorization is revoked, and reopens follow-up only while the item remains eligible. Scheduling records track one appointment per requested service; they do not book an appointment with an external provider. Returns all scheduling rows for this request. Emits rfa.updated with action scheduling_updated, itemId, disposition and version; webhook payloads omit appointment details.
      security:
        - browserSessionAuth: []
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/UpdateRfaSchedulingRequest" }
      responses:
        "200":
          description: Scheduling state for all requested services.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RfaSchedulingEnvelope" }
        default: { $ref: "#/components/responses/Problem" }
  /rfas/{rfaId}/items/{itemId}/closure:
    parameters:
      - $ref: "#/components/parameters/RfaId"
      - name: itemId
        in: path
        required: true
        schema: { type: string }
    patch:
      tags: [ Treatment Authorization ]
      operationId: updateRfaTreatmentClosure
      x-mindbill-access:
        serverScope: rfas:write
        browserPermission: rfas:edit
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Close or reopen a requested treatment
      description: Administratively close a pending treatment when a decision is no longer required, or reopen it. Requires a reason and expectedVersion (zero before the first closure). Only submitted requests with a pending item and no clinical decision are eligible. Stale versions and unchanged dispositions return 409. Does not change clinical outcomes, authorization, review clocks or submitted documents. Every change retains actor, time and reason in RFA history. A request has lifecycleStatus closed when every treatment has a final clinical decision or an administrative closure. Closing all outstanding items resolves decision follow-ups; reopening restores applicable follow-ups. Approved sibling scheduling and unread-response review tasks remain. Webhooks emit rfa.updated with action treatment_closed or treatment_reopened, itemId and version, without the reason.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/UpdateRfaTreatmentClosureRequest" }
      responses:
        "200":
          description: Updated RFA detail.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RfaEnvelope" }
        default: { $ref: "#/components/responses/Problem" }
  /browser/rfas/{rfaId}/items/{itemId}/closure:
    parameters:
      - $ref: "#/components/parameters/BrowserOrigin"
      - $ref: "#/components/parameters/RfaId"
      - name: itemId
        in: path
        required: true
        schema: { type: string }
    patch:
      tags: [ Treatment Authorization ]
      operationId: browserUpdateRfaTreatmentClosure
      x-mindbill-access:
        browserPermission: rfas:edit
        browserBillScoped: false
        requiredCapability: treatmentBilling
      summary: Close or reopen a requested treatment
      description: Administratively close a pending treatment when a decision is no longer required, or reopen it. Requires a reason and expectedVersion (zero before the first closure). Only submitted requests with a pending item and no clinical decision are eligible. Stale versions and unchanged dispositions return 409. Does not change clinical outcomes, authorization, review clocks or submitted documents. Every change retains actor, time and reason in RFA history. A request has lifecycleStatus closed when every treatment has a final clinical decision or an administrative closure. Closing all outstanding items resolves decision follow-ups; reopening restores applicable follow-ups. Approved sibling scheduling and unread-response review tasks remain. Webhooks emit rfa.updated with action treatment_closed or treatment_reopened, itemId and version, without the reason.
      security:
        - browserSessionAuth: []
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/UpdateRfaTreatmentClosureRequest" }
      responses:
        "200":
          description: Updated RFA detail.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RfaEnvelope" }
        default: { $ref: "#/components/responses/Problem" }
  /notifications/recipients/{externalUserId}:
    parameters:
      - $ref: '#/components/parameters/NotificationExternalUserId'
      - $ref: '#/components/parameters/NotificationOrganization'
    get:
      tags: [Notifications]
      operationId: getNotificationRecipient
      security: [{ bearerAuth: [] }]
      x-mindbill-access: { serverScope: 'orgs:write' }
      summary: Read an external user's notification preferences
      description: |
        Server-only, partner-managed organization and key-environment scoped. No console
        account is required. Returns availability, current verified consent eligibility,
        and exact assigned bill IDs. A disabled feature returns available=false and
        recipient=null. Host-provided email dropdown options do not enroll recipients.
      responses:
        '200':
          description: Current recipient preferences, or null when not enrolled or unavailable.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: object
                    required: [externalUserId, available, recipient]
                    properties:
                      externalUserId: { type: string }
                      available: { type: boolean }
                      recipient:
                        oneOf:
                          - $ref: '#/components/schemas/NotificationRecipient'
                          - { type: 'null' }
        default: { $ref: '#/components/responses/Problem' }
    put:
      tags: [Notifications]
      operationId: saveNotificationRecipient
      security: [{ bearerAuth: [] }]
      x-mindbill-access: { serverScope: 'orgs:write' }
      summary: Enroll a verified, consenting external recipient
      description: |
        Your trusted server must authenticate the user, verify their email, and obtain
        explicit consent for the selected audience and categories. Audience is required:
        use assigned_bills for a restricted doctor; practice authorizes all bills in this
        managed organization and environment. Consent must be within 24 hours, not in the
        future, and after verification. Changed preferences or re-enrollment require newer
        consent; changed email also requires fresh verification. Identical retries are
        idempotent and cannot resurrect a revoked enrollment. New consent starts at server
        receipt time, with no historical catch-up. Changing audience clears bill assignments.
        Status and 30/60/90-day aging emails contain no patient or bill details and include
        account-free unsubscribe. Both notification feature gates must be enabled; default
        is off and this endpoint returns 503 while unavailable. No email is sent by this call.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/NotificationEnrollment' }
      responses:
        '200':
          description: Verified consent saved.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: object
                    required: [externalUserId, enabled, audience]
                    properties:
                      externalUserId: { type: string }
                      enabled: { const: true }
                      audience: { enum: [practice, assigned_bills] }
        default: { $ref: '#/components/responses/Problem' }
    delete:
      tags: [Notifications]
      operationId: revokeNotificationRecipient
      security: [{ bearerAuth: [] }]
      x-mindbill-access: { serverScope: 'orgs:write' }
      summary: Revoke external notification consent
      description: |
        Idempotently disable this user's notifications only in the selected organization
        and key environment. Suppresses pending deliveries and retains a consent tombstone
        so old enrollment retries cannot revive consent. Call when the user opts out or
        loses application access. Already authorized transport attempts may be in flight.
      responses:
        '200':
          description: Recipient disabled.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: object
                    required: [externalUserId, enabled]
                    properties:
                      externalUserId: { type: string }
                      enabled: { const: false }
        default: { $ref: '#/components/responses/Problem' }
  /notifications/recipients/{externalUserId}/bills/{billId}:
    parameters:
      - $ref: '#/components/parameters/NotificationExternalUserId'
      - $ref: '#/components/parameters/NotificationOrganization'
      - $ref: '#/components/parameters/BillId'
    put:
      tags: [Notifications]
      operationId: assignNotificationBill
      security: [{ bearerAuth: [] }]
      x-mindbill-access: { serverScope: 'orgs:write' }
      summary: Associate one bill with an opted-in doctor
      description: |
        Bodyless server-only assertion of your trusted user-to-bill relationship. Requires
        active verified consent with audience=assigned_bills and a bill belonging to the
        same partner, managed organization and key environment. Adds only this association;
        does not replace other assignments. Repeated PUT preserves its start time. No events
        before assignment are replayed. Each delivery rechecks consent and assignment.
        Same-ID updates retain the association; corrections or resubmissions returning a
        new bill ID require a new explicit association. No relationship is inferred from
        provider NPI, case ID, or correction chains. Returns 503 while feature gates are off.
      responses:
        '200':
          description: Association created or already present.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/NotificationBillAssignmentResult' }
        default: { $ref: '#/components/responses/Problem' }
    delete:
      tags: [Notifications]
      operationId: removeNotificationBill
      security: [{ bearerAuth: [] }]
      x-mindbill-access: { serverScope: 'orgs:write' }
      summary: Remove one doctor's bill association
      description: |
        Bodyless, idempotent removal of this one association. Other assignments remain.
        Pending deliveries for the bill are suppressed and the worker rechecks authorization.
        Re-adding starts a new authorization period and does not replay the removed period.
        Host servers must remove associations when the user's bill access is revoked.
      responses:
        '200':
          description: Association removed or already absent; assigned is false.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/NotificationBillAssignmentResult' }
        default: { $ref: '#/components/responses/Problem' }
  /bill-dashboard:
    get:
      tags:
      - Lifecycle
      operationId: getBillDashboard
      summary: List the bill dashboard
      description: 'Organization-wide page pagination and dashboard filters. GET /bills retains its cursor contract.
        Bill-scoped browser sessions cannot list collections. Server scope: bills:read. Browser permission: bills:read.
        Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: page
        in: query
        required: false
        description: Page number.
        schema:
          type: integer
          minimum: 1
          default: 1
      - name: pageSize
        in: query
        required: false
        description: Rows per page.
        schema:
          type: integer
          minimum: 1
          maximum: 100
          default: 25
      - name: patientId
        in: query
        description: Canonical MindBill patient ID; use the authorized dashboard patient filter inventory.
        schema: { type: string, maxLength: 200 }
      - name: q
        in: query
        description: Case-insensitive search requiring every word across bill, patient, claim, claims administrator, status,
          external IDs, procedure codes and dates. Recognizes ISO and M/D/YYYY or MM/DD/YYYY dates.
        schema:
          type: string
          maxLength: 160
      - name: dateField
        in: query
        description: Date used by the inclusive from/to range.
        schema:
          type: string
          enum:
          - service
          - submitted
          default: submitted
      - name: from
        in: query
        description: Inclusive calendar date. Must be a real YYYY-MM-DD date; invalid dates or from after to return 400.
        schema:
          type: string
          format: date
          pattern: ^\d{4}-\d{2}-\d{2}$
      - name: to
        in: query
        description: Inclusive calendar date. Must be a real YYYY-MM-DD date; invalid dates or from after to return 400.
        schema:
          type: string
          format: date
          pattern: ^\d{4}-\d{2}-\d{2}$
      - name: status
        in: query
        required: false
        description: 'Comma-separated dashboard status keys: incomplete,send,sent,accepted,accepted_no_response,processed,paid,denied,rejected,appealing,lien,ibr,closed.'
        schema:
          type: string
      - name: age
        in: query
        required: false
        description: Age in days since latest submission (Pacific calendar dates). 91-120 includes days 91 through 120; 91+ remains open-ended. Use openAr=true to restrict to open receivables.
        schema:
          type: string
          enum:
          - 0-30
          - 31-60
          - 61-90
          - 91+
          - 91-120
          - 91-180
          - 181+
      - name: sort
        in: query
        required: false
        description: Sort column.
        schema:
          type: string
          enum:
          - billNumber
          - patient
          - dos
          - submitted
          - balanceDue
          - claimsAdmin
      - name: dir
        in: query
        required: false
        description: Sort direction.
        schema:
          type: string
          enum:
          - asc
          - desc
          default: desc
      - name: claimsAdminId
        in: query
        required: false
        description: ''
        schema:
          type: string
      - name: billingProviderId
        in: query
        required: false
        description: ''
        schema:
          type: string
      - name: renderingProviderId
        in: query
        required: false
        description: 'Doctor filter from filters.renderingProviders. Accepts a saved provider ID or npi: followed by the submitted rendering NPI; scoped to this partner, organization, and environment.'
        schema: { type: string }
      - name: taskKind
        in: query
        required: false
        description: ''
        schema:
          type: string
      - name: taskLabel
        in: query
        required: false
        description: Task label, used with a valid taskKind; maximum 120 characters.
        schema:
          type: string
      - name: openAr
        in: query
        required: false
        description: Set to 1 for open accounts receivable.
        schema:
          type: string
      responses:
        '200':
          description: List the bill dashboard.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BillDashboardPage'
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
  /bill-tasks:
    get:
      tags:
      - Lifecycle
      operationId: getBillTasks
      summary: Get bill tasks
      description: 'Organization-wide task dashboard and waiting queues. Bill-scoped browser sessions are rejected.
        Server scope: bills:read. Browser permission: bills:read. Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: renderingProviderId
        in: query
        required: false
        description: 'Doctor filter from filters.renderingProviders; a saved provider ID or npi: followed by the submitted rendering NPI.'
        schema: { type: string }
      - name: claimsAdminId
        in: query
        required: false
        description: ''
        schema:
          type: string
      responses:
        '200':
          description: Get bill tasks.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      dashboard:
                        type: object
                        properties: {}
                      waiting:
                        type: object
                        properties: {}
                      filters:
                        type: object
                        properties:
                          claimsAdministrators:
                            type: array
                            items:
                              type: object
                              properties: {}
                          renderingProviders:
                            type: array
                            description: All available doctors in this partner, organization, and environment, independent of pagination.
                            items:
                              type: object
                              required: [id, name]
                              properties:
                                id: { type: string }
                                name: { type: string }
                required:
                - data
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
  /reports/payments:
    get:
      tags: [Lifecycle]
      operationId: getPaymentReview
      summary: Review confirmed posted payments
      description: >-
        Organization-wide confirmed cash ledger, isolated to this partner and sandbox/live environment.
        Pending EOR/835 payment promises, bounced payments, void bills, and historical imported payments
        are excluded. New cash posted after an import remains visible. Summary totals cover the full
        filtered result, not just the current page. Requires bills:read; bill-scoped browser sessions
        are rejected. Browser requests require the exact allowed Origin. Read-only: does not post money.
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - { name: q, in: query, schema: { type: string, maxLength: 200 }, description: Search patient, bill number, claim, payer identifier or check. }
      - { name: receivedFrom, in: query, schema: { type: string, format: date }, description: Inclusive received date. }
      - { name: receivedTo, in: query, schema: { type: string, format: date }, description: Inclusive received date. }
      - { name: renderingProviderId, in: query, schema: { type: string }, description: Saved provider ID or npi-prefixed ten-digit NPI from dashboard filter options. }
      - { name: page, in: query, description: One-based page number., schema: { type: integer, minimum: 1, maximum: 1000000, default: 1 } }
      - { name: pageSize, in: query, description: Maximum entries per page., schema: { type: integer, minimum: 1, maximum: 250, default: 50 } }
      responses:
        '200':
          description: Confirmed cash ledger; response is private and not cacheable.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: object
                    required: [items, total, page, pageSize, summary]
                    properties:
                      total: { type: integer }
                      page: { type: integer }
                      pageSize: { type: integer }
                      summary:
                        type: object
                        required: [postedTotal, entryCount, uniquePatients]
                        properties:
                          postedTotal: { type: number, description: Confirmed cash in dollars across all filtered entries. }
                          entryCount: { type: integer }
                          uniquePatients: { type: integer }
                      items:
                        type: array
                        items:
                          type: object
                          required: [id, billId, billNumber, patientName, claimNumber, dateOfService, receivedDate, postedDate, status, method, source, checkNumber, amount]
                          properties:
                            id: { type: string }
                            billId: { type: string }
                            billNumber: { type: [integer, 'null'] }
                            patientName: { type: string }
                            claimNumber: { type: [string, 'null'] }
                            dateOfService: { type: [string, 'null'], format: date }
                            receivedDate: { type: [string, 'null'], format: date }
                            postedDate: { type: [string, 'null'] }
                            status: { type: string, enum: [received] }
                            method: { type: string }
                            source: { type: string }
                            checkNumber: { type: string }
                            amount: { type: number, description: Confirmed cash in dollars. }
        '400': { description: Invalid date range or pagination. }
        '401': { description: Invalid or expired credential. }
        '403': { description: Missing permission or organization-wide browser session. }
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
  /reports/productivity:
    get:
      tags:
      - Lifecycle
      operationId: getProductivityReport
      summary: Get biller productivity
      description: 'Organization-wide report for the date range. Activity is scoped to this partner and environment.
        Bill-scoped browser sessions are rejected. Server scope: bills:read. Browser permission: bills:read. Browser
        requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: from
        in: query
        required: true
        description: Inclusive date (YYYY-MM-DD). Required.
        schema:
          type: string
          format: date
      - name: to
        in: query
        required: true
        description: Inclusive date (YYYY-MM-DD). Required.
        schema:
          type: string
          format: date
      responses:
        '200':
          description: Get biller productivity.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type:
                    - object
                    - 'null'
                    properties:
                      lo:
                        type: string
                      hi:
                        type: string
                      dayKeys:
                        type: array
                        items:
                          type: string
                      billers:
                        type: array
                        items:
                          type: object
                          properties:
                            name:
                              type: string
                            initials:
                              type: string
                      created:
                        type: array
                        items:
                          type: array
                          items:
                            type: number
                      sent:
                        type: array
                        items:
                          type: array
                          items:
                            type: number
                      createdTotal:
                        type: array
                        items:
                          type: number
                      sentTotal:
                        type: array
                        items:
                          type: number
                      submittedTotal:
                        type: array
                        items:
                          type: number
                      cleanTotal:
                        type: array
                        items:
                          type: number
                      createdByDay:
                        type: array
                        items:
                          type: number
                      sentByDay:
                        type: array
                        items:
                          type: number
                      totalCreated:
                        type: number
                      totalSent:
                        type: number
                      totalSubmitted:
                        type: number
                      totalClean:
                        type: number
                      maxSentCell:
                        type: number
                required:
                - data
        default:
          $ref: '#/components/responses/Problem'
        '400':
          description: Invalid request or unavailable resource. This handler returns a top-level error string.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  detail:
                    type: string
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
  /reports/service-line-items:
    get:
      tags:
      - Lifecycle
      operationId: getServiceLineItemsReport
      summary: Get service line items
      description: 'Organization-wide report for the date range. Activity is scoped to this partner and environment.
        Bill-scoped browser sessions are rejected. Server scope: bills:read. Browser permission: bills:read. Browser
        requests require the exact allowed Origin. providerCptRows groups rendering providers by valid NPI (npi: plus ten digits),
        falling back to the saved provider ID or null when unassigned. paid sums recorded service-line payment allocations;
        it is not a deposit reconciliation total. Existing report date, original-claim and duplicate-selection rules apply.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: from
        in: query
        required: false
        description: Inclusive date (YYYY-MM-DD). Omit for the default report window.
        schema:
          type: string
          format: date
      - name: to
        in: query
        required: false
        description: Inclusive date (YYYY-MM-DD). Omit for the default report window.
        schema:
          type: string
          format: date
      responses:
        '200':
          description: Get service line items.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      from:
                        type: string
                      to:
                        type: string
                      windowLabel:
                        type: string
                      cptRows:
                        type: array
                        items:
                          type: object
                          properties:
                            code:
                              type: string
                            bills:
                              type: integer
                            lines:
                              type: integer
                            billed:
                              type: number
                      providerCptRows:
                        type: array
                        items:
                          type: object
                          properties:
                            providerId:
                              type: [string, 'null']
                              description: Rendering provider identity for dashboard providerId filtering (npi-prefixed NPI or saved ID); null means unassigned.
                            providerName:
                              type: [string, 'null']
                            code:
                              type: string
                            bills:
                              type: integer
                              description: Distinct bills for this provider and code.
                            lines:
                              type: integer
                            billed:
                              type: number
                              description: Sum of extended service-line charges, without multiplying by units again.
                            paid:
                              type: number
                              description: Sum of recorded service-line payment allocations.
                      billRows:
                        type: array
                        items:
                          type: object
                          properties:
                            billingProviderId:
                              type: [string, 'null']
                            renderingProviderId:
                              type: [string, 'null']
                              description: Saved rendering provider ID; inline-only providers may have no saved ID.
                            renderingProviderNpi:
                              type: [string, 'null']
                              description: Bill snapshot NPI, falling back to the saved rendering provider.
                            renderingProviderName:
                              type: [string, 'null']
                      flat:
                        type: array
                        items:
                          type: object
                          properties:
                            billingProviderId:
                              type: [string, 'null']
                            renderingProviderId:
                              type: [string, 'null']
                              description: Saved rendering provider ID; inline-only providers may have no saved ID.
                            renderingProviderNpi:
                              type: [string, 'null']
                              description: Bill snapshot NPI, falling back to the saved rendering provider.
                            renderingProviderName:
                              type: [string, 'null']
                      totalBills:
                        type: number
                      totalLines:
                        type: number
                      totalBilled:
                        type: number
                required:
                - data
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
  /claims-administrators/{id}:
    get:
      tags:
        - Directories
      operationId: getClaimsAdministrator
      summary: Get a claims administrator
      description: 'Directory detail and payer metadata, wrapped in data. Unknown identifiers return 404. Server scope:
        payers:read. Browser permission: payers:read. Browser requests require the exact allowed Origin. Use the directory
        ID, not a clearinghouse payer ID. Routing and authorization contacts have separate purposes.
        California authorizationStatus distinguishes published fax, email, handling-office and unavailable routes.
        Select the correct handling office explicitly. Unverified, adjuster-specific and unpublished profiles have no
        usable published destination. Telephone numbers are for questions, not fax delivery. Email requires a separate
        delivery workflow. authorizationSource records when and where the directory information was observed.'
      security:
        - bearerAuth: []
        - browserSessionAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: Resource identifier.
          schema:
            type: string
            maxLength: 200
        - name: injuryState
          in: query
          required: false
          description: Default CA.
          schema:
            type: string
            pattern: ^[A-Z]{2}$
            default: CA
      responses:
        '200':
          description: Get a claims administrator.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      id:
                        type: string
                      name:
                        type: string
                      telephoneNumbers:
                        type: array
                        items:
                          type: string
                      emailAddresses:
                        type: array
                        items:
                          type: string
                      webPortals:
                        type: array
                        items:
                          type: string
                      payers:
                        type: array
                        items:
                          type: object
                          properties: {}
                      authorizationStatus:
                        type: string
                        enum: [central_fax, central_email, claim_handling_location_routes, adjuster_specific_required, daisybill_unverified, profile_not_published]
                      authorizationNotice:
                        type: string
                      authorizationSource:
                        type: object
                        properties:
                          url:
                            type: string
                            format: uri
                          observedAt:
                            type: string
                            format: date-time
                        required: [url, observedAt]
                      authorization:
                        type: array
                        items:
                          type: object
                          properties:
                            name:
                              type: string
                            method:
                              type: string
                              enum: [fax, email]
                            location:
                              type: string
                            fax:
                              type: string
                            email:
                              type: string
                              format: email
                            phone:
                              type: string
                required:
                  - data
          headers:
            Cache-Control:
              schema:
                type: string
                const: no-store
        default:
          $ref: '#/components/responses/Problem'
        '404':
          $ref: '#/components/responses/Problem'
        '400':
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: payers:read
        browserPermission: payers:read
  /diagnosis-codes:
    get:
      tags:
      - Directories
      operationId: searchDiagnosisCodes
      summary: Search diagnosis codes
      description: 'Search ICD-10-CM codes. total is the full catalog size; matched is the query match count. Catalog
        unavailable currently returns HTTP 200 with results [], total 0, error, and no matched. Server scope: payers:read.
        Browser permission: payers:read. Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: q
        in: query
        required: false
        description: ''
        schema:
          type: string
      - name: limit
        in: query
        required: false
        description: Default 30, clamped to 1–100.
        schema:
          type: integer
      - name: offset
        in: query
        required: false
        description: Zero-based, default 0.
        schema:
          type: integer
      responses:
        '200':
          description: Search diagnosis codes.
          content:
            application/json:
              schema:
                type: object
                properties:
                  results:
                    type: array
                    items:
                      type: object
                      properties:
                        code:
                          type: string
                        description:
                          type: string
                  total:
                    type: integer
                  matched:
                    type: integer
                  error:
                    type: string
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: payers:read
        browserPermission: payers:read
  /postal-codes:
    get:
      tags:
      - Directories
      operationId: lookupPostalCode
      summary: Look up a postal code
      description: 'Trim input and resolve the first five characters as a US ZIP code. Invalid input returns 400;
        unknown ZIP returns 404. Server scope: payers:read. Browser permission: payers:read. Browser requests require
        the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: postalCode
        in: query
        required: true
        description: ZIP or ZIP+4.
        schema:
          type: string
      responses:
        '200':
          description: Look up a postal code.
          content:
            application/json:
              schema:
                type: object
                properties:
                  postalCode:
                    type: string
                  city:
                    type: string
                  state:
                    type: string
        default:
          $ref: '#/components/responses/Problem'
        '400':
          description: Invalid request or unavailable resource. This handler returns a top-level error string.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  detail:
                    type: string
        '404':
          description: Invalid request or unavailable resource. This handler returns a top-level error string.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  detail:
                    type: string
      x-mindbill-access:
        serverScope: payers:read
        browserPermission: payers:read
  /delivery-preview:
    get:
      tags:
      - Directories
      operationId: getDeliveryPreview
      summary: Preview bill delivery
      description: 'Advisory delivery choices before a bill exists. This does not submit a bill or guarantee delivery.
        Server scope: payers:read. Browser permission: payers:read. Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: claimsAdministratorId
        in: query
        required: true
        description: Directory identifier.
        schema:
          type: string
      - name: payerId
        in: query
        required: false
        description: Payer-choice key from directory search.
        schema:
          type: string
      - name: injuryState
        in: query
        required: false
        description: Default CA.
        schema:
          type: string
      responses:
        '200':
          description: Preview bill delivery.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeliveryOptions'
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: payers:read
        browserPermission: payers:read
  /organization/team:
    get:
      tags:
      - Platform
      operationId: listOrganizationTeam
      summary: List organization team
      description: Lists existing MindBill login accounts and assignable roles, not host-application identities. Account
        creation and invitations are not supported. Organization-wide access is required; bill- and customer-scoped
        sessions are forbidden.
      x-mindbill-access:
        serverScope: orgs:team:read
        browserPermission: team:manage
      responses:
        '200':
          description: List organization team.
          content:
            application/json:
              schema:
                type: object
                required:
                - data
                properties:
                  data:
                    $ref: '#/components/schemas/OrganizationTeam'
        default:
          $ref: '#/components/responses/Problem'
  /organization/team/{id}:
    parameters:
    - name: id
      in: path
      required: true
      schema:
        type: string
    patch:
      tags:
      - Platform
      operationId: updateOrganizationTeamMember
      summary: Update an organization team member
      description: Changes role or active status for an existing MindBill account. Protected accounts return 403;
        removing the last active administrator returns 409. Organization-wide access is required; bill- and customer-scoped
        sessions are forbidden.
      x-mindbill-access:
        serverScope: orgs:team:write
        browserPermission: team:manage
      responses:
        '200':
          description: Update an organization team member.
          content:
            application/json:
              schema:
                type: object
                required:
                - data
                properties:
                  data:
                    $ref: '#/components/schemas/OrganizationTeamMember'
        default:
          $ref: '#/components/responses/Problem'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OrganizationTeamMemberPatch'
  /organization/claims-administrators:
    get:
      tags:
      - Platform
      operationId: listOrganizationClaimsAdministrators
      summary: List custom claims administrators
      description: Returns active custom contacts saved by this organization. Organization-wide access is required;
        bill- and customer-scoped sessions are forbidden.
      x-mindbill-access:
        serverScope: orgs:read
        browserPermission: organization:manage
      responses:
        '200':
          description: List custom claims administrators.
          content:
            application/json:
              schema:
                type: object
                required:
                - data
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/CustomClaimsAdministrator'
        default:
          $ref: '#/components/responses/Problem'
    post:
      tags:
      - Platform
      operationId: createOrganizationClaimsAdministrator
      summary: Create a custom claims administrator
      description: Requires a name and at least one contact channel. Submission method is inferred in fax, email,
        then mail order. Duplicate active names return 409. Organization-wide access is required; bill- and customer-scoped
        sessions are forbidden.
      x-mindbill-access:
        serverScope: orgs:write
        browserPermission: organization:manage
      responses:
        '201':
          description: Create a custom claims administrator.
          content:
            application/json:
              schema:
                type: object
                required:
                - data
                properties:
                  data:
                    $ref: '#/components/schemas/CustomClaimsAdministrator'
        default:
          $ref: '#/components/responses/Problem'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CustomClaimsAdministratorWrite'
  /organization/claims-administrators/{id}:
    parameters:
    - name: id
      in: path
      required: true
      schema:
        type: string
    patch:
      tags:
      - Platform
      operationId: updateOrganizationClaimsAdministrator
      summary: Replace custom claims administrator details
      description: Supply the full editable shape, including name and at least one contact channel. Omitted nullable
        contact and notes fields are cleared. Missing contacts return 404; duplicate active names return 409. Organization-wide
        access is required; bill- and customer-scoped sessions are forbidden.
      x-mindbill-access:
        serverScope: orgs:write
        browserPermission: organization:manage
      responses:
        '200':
          description: Replace custom claims administrator details.
          content:
            application/json:
              schema:
                type: object
                required:
                - data
                properties:
                  data:
                    $ref: '#/components/schemas/CustomClaimsAdministrator'
        default:
          $ref: '#/components/responses/Problem'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CustomClaimsAdministratorWrite'
    delete:
      tags:
      - Platform
      operationId: deleteOrganizationClaimsAdministrator
      summary: Delete a custom claims administrator
      description: Soft-deletes this contact from future choices; existing bill snapshots remain intact. Missing contacts
        return 404. Organization-wide access is required; bill- and customer-scoped sessions are forbidden.
      x-mindbill-access:
        serverScope: orgs:write
        browserPermission: organization:manage
      responses:
        '200':
          description: Delete a custom claims administrator.
          content:
            application/json:
              schema:
                type: object
                required:
                - data
                properties:
                  data:
                    type: object
                    required:
                    - id
                    - deleted
                    properties:
                      id:
                        type: string
                      deleted:
                        type: boolean
                        const: true
        default:
          $ref: '#/components/responses/Problem'
  /organization:
    get:
      tags:
      - Platform
      operationId: getCurrentOrganization
      summary: Get the current organization
      description: 'Read the composed profile for the authenticated organization. Server scope: orgs:read. Browser
        permission: organization:manage. Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      responses:
        '200':
          description: Get the current organization.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/OrganizationProfile'
                required:
                - data
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: orgs:read
        browserPermission: organization:manage
  /organization/billing-profile:
    get:
      tags:
      - Platform
      operationId: getCurrentBillingProfile
      summary: Get bill-entry profile choices
      description: 'Read masked provider and location choices for bill creation. Browser session must be organization-wide.
        Server scope: orgs:read. Browser permission: bills:create. Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      responses:
        '200':
          description: Get bill-entry profile choices.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/OrganizationProfile'
                required:
                - data
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: orgs:read
        browserPermission: bills:create
    put:
      tags:
      - Platform
      operationId: saveCurrentBillingProfile
      summary: Save current organization billing profile
      description: 'Save profile settings. Provider/location writes upsert by id, then externalId; existing records
        are not deleted. W-9 replaces the current PDF. Stored SSNs are masked on reads; omit taxId to preserve it.
        Do not send response-only taxIdConfigured or taxIdLast4. Server scope: orgs:write. Browser permission: organization:manage.
        Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BillingProfileWrite'
      responses:
        '200':
          description: Save current organization billing profile.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/OrganizationProfile'
                required:
                - data
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: orgs:write
        browserPermission: organization:manage
  /organizations/{id}:
    get:
      tags:
      - Platform
      operationId: getOrganization
      summary: Get an organization
      description: 'Read the composed profile. The explicit organization id must match the authenticated organization.
        Server scope: orgs:read. Browser permission: organization:manage. Browser requests require the exact allowed
        Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: id
        in: path
        required: true
        description: Resource identifier.
        schema:
          type: string
      responses:
        '200':
          description: Get an organization.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/OrganizationProfile'
                required:
                - data
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: orgs:read
        browserPermission: organization:manage
  /organization/locations:
    put:
      tags:
      - Platform
      operationId: saveCurrentLocations
      summary: Save current organization locations
      description: 'Save profile settings. Provider/location writes upsert by id, then externalId; existing records
        are not deleted. W-9 replaces the current PDF. Stored SSNs are masked on reads; omit taxId to preserve it.
        Do not send response-only taxIdConfigured or taxIdLast4. Server scope: orgs:write. Browser permission: organization:manage.
        Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/LocationsWrite'
      responses:
        '200':
          description: Save current organization locations.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/OrganizationProfile'
                required:
                - data
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: orgs:write
        browserPermission: organization:manage
  /organization/w9:
    put:
      tags:
      - Platform
      operationId: saveCurrentW9
      summary: Save current organization W-9
      description: 'Save profile settings. Provider/location writes upsert by id, then externalId; existing records
        are not deleted. W-9 replaces the current PDF. Stored SSNs are masked on reads; omit taxId to preserve it.
        Do not send response-only taxIdConfigured or taxIdLast4. Server scope: orgs:write. Browser permission: organization:manage.
        Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/W9Write'
      responses:
        '200':
          description: Save current organization W-9.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/OrganizationProfile'
                required:
                - data
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: orgs:write
        browserPermission: organization:manage
  /organizations/{id}/billing-profile:
    put:
      tags:
      - Platform
      operationId: saveOrganizationBillingProfile
      summary: Save organization billing profile
      description: 'Save profile settings. Provider/location writes upsert by id, then externalId; existing records
        are not deleted. W-9 replaces the current PDF. Stored SSNs are masked on reads; omit taxId to preserve it.
        Do not send response-only taxIdConfigured or taxIdLast4. Server scope: orgs:write. Browser permission: organization:manage.
        Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: id
        in: path
        required: true
        description: Resource identifier.
        schema:
          type: string
      - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BillingProfileWrite'
      responses:
        '200':
          description: Save organization billing profile.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/OrganizationProfile'
                required:
                - data
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: orgs:write
        browserPermission: organization:manage
  /organizations/{id}/locations:
    put:
      tags:
      - Platform
      operationId: saveOrganizationLocations
      summary: Save organization locations
      description: 'Save profile settings. Provider/location writes upsert by id, then externalId; existing records
        are not deleted. W-9 replaces the current PDF. Stored SSNs are masked on reads; omit taxId to preserve it.
        Do not send response-only taxIdConfigured or taxIdLast4. Server scope: orgs:write. Browser permission: organization:manage.
        Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: id
        in: path
        required: true
        description: Resource identifier.
        schema:
          type: string
      - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/LocationsWrite'
      responses:
        '200':
          description: Save organization locations.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/SavedLocation'
                required:
                - data
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: orgs:write
        browserPermission: organization:manage
    get:
      tags:
      - Platform
      operationId: listOrganizationLocations
      summary: List organization locations
      description: 'Read saved locations. The explicit organization id must match the authenticated organization.
        Server scope: orgs:read. Browser permission: organization:manage. Browser requests require the exact allowed
        Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: id
        in: path
        required: true
        description: Resource identifier.
        schema:
          type: string
      responses:
        '200':
          description: List organization locations.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/SavedLocation'
                required:
                - data
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: orgs:read
        browserPermission: organization:manage
  /organizations/{id}/w9:
    put:
      tags:
      - Platform
      operationId: saveOrganizationW9
      summary: Save organization W-9
      description: 'Save profile settings. Provider/location writes upsert by id, then externalId; existing records
        are not deleted. W-9 replaces the current PDF. Stored SSNs are masked on reads; omit taxId to preserve it.
        Do not send response-only taxIdConfigured or taxIdLast4. Server scope: orgs:write. Browser permission: organization:manage.
        Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: id
        in: path
        required: true
        description: Resource identifier.
        schema:
          type: string
      - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/W9Write'
      responses:
        '200':
          description: Save organization W-9.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/OrganizationProfile'
                required:
                - data
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: orgs:write
        browserPermission: organization:manage
  /organizations:
    post:
      tags:
      - Platform
      operationId: provisionOrganization
      summary: Provision a billing practice
      description: 'Create or find a managed billing practice using your stable externalId. Requires a workspace/account-scoped
        credential with orgs:write; a credential restricted to one practice is rejected. A workspace can provision
        multiple practices. Returns 201 when created, 200 when found. Save the returned organizationId in your backend
        as that practice''s routing ID; it is not the developer workspace ID. Server API key only.'
      security:
      - bearerAuth: []
      parameters:
      - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProvisionOrganizationRequest'
      responses:
        '201':
          description: Provision an organization.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProvisionOrganizationResponse'
        default:
          $ref: '#/components/responses/Problem'
        '200':
          description: Provision an organization.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProvisionOrganizationResponse'
      x-mindbill-access:
        serverScope: orgs:write
        browserPermission: null
  /management-sessions:
    post:
      tags:
      - Platform
      operationId: createManagementSession
      summary: Create a management session
      description: 'Create a short-lived single-use hosted sign-in URL. Requires the operator-granted management:write
        scope. Server scope: management:write. Server API key only.'
      security:
      - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ManagementSessionRequest'
      responses:
        '201':
          description: Create a management session.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ManagementSessionResponse'
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: management:write
        browserPermission: null
  /bills/{billId}/courtesy-forward:
    post:
      tags:
      - Lifecycle
      operationId: courtesyForwardBill
      summary: Preview or send a courtesy copy
      description: 'Preview the exact PDF, recipients, and message before sending. mode=send requires Idempotency-Key
        and the preview packetHash. A changed packet returns 409. Sandbox sends are simulated. This is not a payer
        submission. Server scope: bills:write. Browser permission: bills:act. Browser requests require the exact allowed
        Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: billId
        in: path
        required: true
        description: Resource identifier.
        schema:
          type: string
      - name: Idempotency-Key
        in: header
        required: false
        description: Required only for mode=send; reuse only for retries of the same logical send.
        schema:
          type: string
          minLength: 8
          maxLength: 128
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CourtesyForwardRequest'
      responses:
        '200':
          description: Preview or send a courtesy copy.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CourtesyForwardResponse'
        default:
          $ref: '#/components/responses/Problem'
        '409':
          description: Invalid request or unavailable resource. This handler returns a top-level error string.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  detail:
                    type: string
        '502':
          description: Invalid request or unavailable resource. This handler returns a top-level error string.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  detail:
                    type: string
      x-mindbill-access:
        serverScope: bills:write
        browserPermission: bills:act
  /bills/{billId}/delivery-options:
    get:
      tags:
      - Lifecycle
      operationId: getBillDeliveryOptions
      summary: Get bill delivery options
      description: 'Read delivery choices for an existing bill. Returns the top-level delivery object; 404 when unavailable.
        Server scope: bills:read. Browser permission: bills:read. Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: billId
        in: path
        required: true
        description: Resource identifier.
        schema:
          type: string
      responses:
        '200':
          description: Get bill delivery options.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeliveryOptions'
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
  /bills/{billId}/eors/{docId}:
    get:
      tags:
      - Lifecycle
      operationId: downloadBillEorDocument
      summary: Download an EOR document
      description: 'Download an original EOR PDF by its document identifier. Server scope: bills:read. Browser permission:
        eors:read. Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: docId
        in: path
        required: true
        description: Resource identifier.
        schema:
          type: string
      - name: billId
        in: path
        required: true
        description: Resource identifier.
        schema:
          type: string
      responses:
        '200':
          description: Download an EOR document.
          content:
            application/pdf:
              schema:
                type: string
                format: binary
        default:
          $ref: '#/components/responses/Problem'
        '404':
          description: Invalid request or unavailable resource. This handler returns a top-level error string.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  detail:
                    type: string
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: eors:read
  /bills/{billId}/submissions/{attemptId}/artifacts/{artifactId}:
    get:
      tags: [Lifecycle]
      operationId: downloadSubmissionArtifact
      summary: Download an original submission artifact
      description: 'Download the exact retained attachment or EDI bytes for a historical submission. Use opaque attempt and artifact identifiers returned by the bill lifecycle. Historical files are never reconstructed from current bill data. Returns 404 when the original artifact is unavailable or outside the authorized bill chain. Server scope: bills:read. Browser permission: bills:read. Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: billId
        in: path
        required: true
        schema: { type: string }
      - name: attemptId
        in: path
        required: true
        schema: { type: string }
      - name: artifactId
        in: path
        required: true
        schema: { type: string }
      responses:
        '200':
          description: Exact retained file bytes with attachment disposition and no-store caching.
          content:
            application/octet-stream:
              schema: { type: string, format: binary }
        '404':
          description: Artifact unavailable for this bill and submission.
        default: { $ref: '#/components/responses/Problem' }
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
  /bills/{billId}/ibr-packet:
    get:
      tags:
      - Lifecycle
      operationId: downloadBillIbrPacket
      summary: Download an IBR packet
      description: 'Download the prepared Independent Bill Review packet. Returns 409 when unavailable. This download
        does not file or pay for a review. Server scope: bills:read. Browser permission: bills:read. Browser requests
        require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: billId
        in: path
        required: true
        description: Resource identifier.
        schema:
          type: string
      responses:
        '200':
          description: Download an IBR packet.
          content:
            application/pdf:
              schema:
                type: string
                format: binary
        default:
          $ref: '#/components/responses/Problem'
        '404':
          description: Invalid request or unavailable resource. This handler returns a top-level error string.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  detail:
                    type: string
        '409':
          description: Invalid request or unavailable resource. This handler returns a top-level error string.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  detail:
                    type: string
      x-mindbill-access:
        serverScope: bills:read
        browserPermission: bills:read
  /bills/{billId}/submissions:
    post:
      tags:
      - Lifecycle
      operationId: rejectRepeatBillSubmission
      summary: Legacy repeat submission
      description: 'Compatibility endpoint. Bills are submitted atomically by POST /bills; this endpoint always returns
        409 bill_already_submitted for an authorized existing bill. Use lifecycle actions for allowed follow-up work.
        Server scope: bills:write. Browser permission: bills:read. Browser requests require the exact allowed Origin.'
      security:
      - bearerAuth: []
      - browserSessionAuth: []
      parameters:
      - name: billId
        in: path
        required: true
        description: Resource identifier.
        schema:
          type: string
      deprecated: true
      responses:
        '409':
          description: Legacy repeat submission.
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        default:
          $ref: '#/components/responses/Problem'
      x-mindbill-access:
        serverScope: bills:write
        browserPermission: bills:read
components:
  securitySchemes:
    browserSessionAuth:
      type: http
      scheme: bearer
      bearerFormat: Short-lived browser session
      description: Use the token returned by POST /browser-sessions and the exact allowed Origin header. Never expose an API key to browser code.
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: Partner API key
  parameters:
    DentalDraftId: { name: id, in: path, required: true, description: Scoped dental draft ID., schema: { type: string, minLength: 1, maxLength: 255 } }
    RfaTransmissionId: { name: transmissionId, in: path, required: true, description: Original uncertain RFA transmission ID., schema: { type: string } }
    BrowserOrigin:
      name: Origin
      in: header
      required: true
      description: Exact allowedOrigin bound to this browser session. Use the scoped browser token, never the server API key.
      schema: { type: string, format: uri }
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: Stable UUID for one logical write. Reuse it only when retrying the identical request.
      schema: { type: string, minLength: 8, maxLength: 128 }
    BillId: { name: billId, in: path, required: true, description: MindBill bill ID., schema: { type: string } }
    DocumentId: { name: documentId, in: path, required: true, description: MindBill document ID., schema: { type: string } }
    ReviewId: { name: reviewId, in: path, required: true, description: MindBill review ID., schema: { type: string } }
    RfaId: { name: rfaId, in: path, required: true, description: MindBill RFA ID., schema: { type: string } }
    RfaDocumentId: { name: documentId, in: path, required: true, description: MindBill RFA document ID., schema: { type: string } }
    RfaInformationRequestId: { name: requestId, in: path, required: true, description: MindBill RFA information-request ID., schema: { type: string } }
    NotificationExternalUserId:
      name: externalUserId
      in: path
      required: true
      description: Opaque stable user ID from your authenticated application; never an email or patient identifier.
      schema: { type: string, pattern: '^[A-Za-z0-9_-]{1,128}$' }
    NotificationOrganization:
      name: X-MindBill-Org-Id
      in: header
      description: Optional legacy organization routing override. Omit for automatic workspace billing. The API validates any explicit ID against the key and environment; restricted keys and browser sessions cannot widen their scope.
      schema: { type: string }
  responses:
    Problem:
      description: Request failed.
      content:
        application/problem+json:
          schema: { $ref: '#/components/schemas/Problem' }
  schemas:
    CaCopyServiceQuoteInput: {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "dateOfService": {
          "type": "string",
          "format": "date",
          "description": "Actual calendar date in YYYY-MM-DD format."
        },
        "service": {
          "type": "string",
          "enum": [
            "initial",
            "initial_addon",
            "cancellation",
            "cnr",
            "additional_set",
            "edd",
            "wcirb",
            "requested"
          ]
        },
        "paperPages": {
          "type": "integer",
          "minimum": 0,
          "maximum": 1000000,
          "description": "For initial_addon, cumulative paper pages for the original custodian/job, including pages on previous invoices."
        },
        "priorBilledExcessPaperPages": {
          "type": "integer",
          "minimum": 0,
          "maximum": 1000000,
          "description": "Required with paperPages on initial_addon, including explicit zero. Cannot exceed cumulative paper pages above 500."
        },
        "electronicPages": {
          "type": "integer",
          "minimum": 0,
          "maximum": 1000000,
          "description": "Electronic pages never receive the excess-paper-page supplement in either edition."
        },
        "xraySheets": {
          "type": "integer",
          "minimum": 0,
          "maximum": 1000000,
          "description": "On initial_addon, only sheets not billed previously."
        },
        "mediaCount": {
          "type": "integer",
          "minimum": 0,
          "maximum": 1000000,
          "description": "X-ray/scan storage media, not ordinary electronic document delivery. On initial_addon, only previously unbilled media."
        },
        "mediaKind": {
          "type": "string",
          "enum": [
            "cd",
            "other_electronic"
          ]
        },
        "additionalSetCount": {
          "type": "integer",
          "minimum": 1,
          "maximum": 1000000
        },
        "additionalSetFormat": {
          "type": "string",
          "enum": [
            "paper",
            "electronic"
          ]
        },
        "additionalSetOrderDate": {
          "type": "string",
          "format": "date",
          "description": "Actual calendar date in YYYY-MM-DD format."
        },
        "subpoenaDate": {
          "type": "string",
          "format": "date",
          "description": "Actual calendar date in YYYY-MM-DD format."
        },
        "retainedByRegisteredPhotocopier": {
          "type": "boolean"
        },
        "initialSetReference": {
          "type": "string",
          "minLength": 1,
          "maxLength": 200,
          "description": "Original initial-set reference; required for initial_addon."
        },
        "requestedBy": {
          "type": "string",
          "enum": [
            "injured_worker",
            "other"
          ]
        },
        "priorWorkerAdditionalSets": {
          "type": "integer",
          "minimum": 0,
          "maximum": 1000000,
          "description": "Prior worker-requested additional sets for this original set, across invoices and providers. Unknown history is not zero."
        },
        "priorClaimCnrCount": {
          "type": "integer",
          "minimum": 0,
          "maximum": 1000000,
          "description": "Prior claim-wide certificates with service dates on/after 2022-07-15, across all invoices and providers."
        },
        "priorHistoricalClaimCnrCount": {
          "type": "integer",
          "minimum": 0,
          "maximum": 1000000,
          "description": "Earlier certificates with service dates before 2022-07-15; excluded from the post-2022 four-certificate cap."
        },
        "submittedChargeCents": {
          "type": "integer",
          "minimum": 0,
          "maximum": 100000000,
          "description": "USD cents, never decimal dollars."
        },
        "taxCents": {
          "type": "integer",
          "minimum": 0,
          "maximum": 100000000,
          "description": "Supplied applicable tax; this endpoint does not determine a tax rate."
        },
        "pricing": {
          "type": "object",
          "additionalProperties": false,
          "properties": {
            "kind": {
              "type": "string",
              "const": "contract"
            },
            "amountCents": {
              "type": "integer",
              "minimum": 0,
              "maximum": 100000000,
              "description": "USD cents, never decimal dollars."
            },
            "reference": {
              "type": "string",
              "minLength": 1,
              "maxLength": 200
            }
          },
          "required": [
            "kind",
            "amountCents",
            "reference"
          ],
          "description": "Contract between employer or claims administrator and provider under section 9980(d). Outside the schedule under section 9982(a); agreed amount remains separate."
        },
        "findings": {
          "type": "object",
          "additionalProperties": false,
          "properties": {
            "registration": {
              "type": "string",
              "enum": [
                "registered",
                "statutorily_exempt",
                "unregistered",
                "unresolved"
              ],
              "description": "Provider entity registration, not individual employee registration. An unregistered provider receives no scheduled payment under section 9982(d)(2), including one asserting only a registration exemption."
            },
            "registrationExemptionReference": {
              "type": "string",
              "minLength": 1,
              "maxLength": 200
            },
            "employerRecordsRequestDate": {
              "type": "string",
              "format": "date",
              "description": "Actual calendar date in YYYY-MM-DD format."
            },
            "historicalGoodCauseDeclaration": {
              "type": "string",
              "enum": [
                "established",
                "absent",
                "unresolved"
              ]
            },
            "cancellationDocumentation": {
              "type": "string",
              "enum": [
                "present",
                "missing",
                "unresolved"
              ]
            },
            "cnrDocumentation": {
              "type": "string",
              "enum": [
                "present",
                "missing",
                "unresolved"
              ]
            },
            "employerRecordsInPossession": {
              "type": "boolean"
            },
            "duplicatePreviouslyObtainedAndServed": {
              "type": "boolean"
            },
            "medicalProviderWhenProfessionalCopierEmployed": {
              "type": "boolean"
            },
            "summariesOrIndexingOnly": {
              "type": "boolean"
            },
            "eddWcirbSubpoenaAvailableCheaper": {
              "type": "boolean"
            },
            "imroRecordsAlreadyPossessedOrDuplicated": {
              "type": "boolean"
            },
            "quashedSubpoenaForEmployerHeldRecords": {
              "type": "boolean"
            },
            "cancellationAfterIssuance": {
              "type": "boolean",
              "description": "Whether cancellation followed issuance of the subpoena or authorization request. Both date editions require true, together with cancellationBeforeProduction, for the $75 item. Omission yields missing_information; documents alone do not establish the sequence."
            },
            "cancellationBeforeProduction": {
              "type": "boolean"
            }
          },
          "description": "Specific known case findings. Omission is not independent verification or an attestation."
        },
        "latePayment": {
          "type": "object",
          "additionalProperties": false,
          "properties": {
            "receivedDate": {
              "type": "string",
              "format": "date",
              "description": "Actual calendar date in YYYY-MM-DD format."
            },
            "assessmentDate": {
              "type": "string",
              "format": "date",
              "description": "Actual calendar date in YYYY-MM-DD format."
            },
            "payments": {
              "type": "array",
              "maxItems": 1000,
              "description": "Complete payment history through assessment, excluding the surcharge. Include advance payments applied to this billed principal. Payment dates cannot follow assessment; their total cannot exceed billed principal.",
              "items": {
                "type": "object",
                "additionalProperties": false,
                "properties": {
                  "date": {
                    "type": "string",
                    "format": "date",
                    "description": "Actual calendar date in YYYY-MM-DD format."
                  },
                  "amountCents": {
                    "type": "integer",
                    "minimum": 0,
                    "maximum": 100000000,
                    "description": "USD cents, never decimal dollars."
                  },
                  "claimsAdministratorAmountCents": {
                    "type": "integer",
                    "minimum": 0,
                    "maximum": 100000000,
                    "description": "Administrator portion of this payment, including explicit zero. Requires administrator-billed principal; cannot exceed this payment, and party payment totals cannot exceed their respective billed principal."
                  }
                },
                "required": [
                  "date",
                  "amountCents"
                ]
              }
            },
            "claimsAdministratorBilledPrincipalCents": {
              "type": "integer",
              "minimum": 0,
              "maximum": 100000000,
              "description": "Actual administrator share of submittedChargeCents, required for mixed-party invoices. Cannot exceed total billed principal; enter every payment allocation when supplied."
            }
          },
          "required": [
            "receivedDate",
            "assessmentDate",
            "payments"
          ]
        }
      },
      "required": [
        "dateOfService",
        "service"
      ],
      "description": "Service-specific fields and chronology are validated. Production add-ons belong only to initial/initial_addon; additional-set fields only to additional_set; CNR history only to cnr. Dates before 2015-07-01 return unsupported_date. Known services without a published rate and contracts return not_scheduled. Missing transaction facts return missing_information or documentation_required. Late-payment estimates require submittedChargeCents, receipt no earlier than service, and assessment no earlier than receipt. The post-2022 surcharge applies only to administrator principal; mixed-party invoices require billed-principal and payment allocation. Source-monitor holds retain requires_review."
    }
    CaCopyServiceQuoteResult: {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "status": {
          "type": "string",
          "enum": [
            "calculated",
            "unsupported_date",
            "not_scheduled",
            "missing_information",
            "requires_review",
            "documentation_required",
            "not_admin_liability"
          ]
        },
        "edition": {
          "type": "string",
          "enum": [
            "before_2015_schedule",
            "2015-07-01",
            "2022-07-15"
          ]
        },
        "scheduleMaximumCents": {
          "type": [
            "integer",
            "null"
          ],
          "minimum": 0,
          "description": "Published schedule amount excluding tax and surcharge. Null means unavailable, not zero."
        },
        "administratorAmountCents": {
          "type": [
            "integer",
            "null"
          ],
          "minimum": 0,
          "description": "Amount attributed to the administrator under supplied facts; not independent proof of liability."
        },
        "orderingPartyAmountCents": {
          "type": [
            "integer",
            "null"
          ],
          "minimum": 0
        },
        "contractAmountCents": {
          "type": [
            "integer",
            "null"
          ],
          "minimum": 0
        },
        "submittedChargeCents": {
          "type": [
            "integer",
            "null"
          ],
          "minimum": 0
        },
        "taxCents": {
          "type": "integer",
          "minimum": 0
        },
        "surchargeCents": {
          "type": [
            "integer",
            "null"
          ],
          "minimum": 0,
          "description": "Separate late-payment estimate on billed principal; not included in schedule allowance."
        },
        "components": {
          "type": "array",
          "items": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
              "code": {
                "type": "string"
              },
              "label": {
                "type": "string"
              },
              "quantity": {
                "type": "integer",
                "minimum": 0,
                "maximum": 1000000
              },
              "unitCents": {
                "type": "integer",
                "minimum": 0
              },
              "amountCents": {
                "type": "integer",
                "minimum": 0
              },
              "sourceUrl": {
                "type": "string",
                "format": "uri"
              }
            },
            "required": [
              "code",
              "label",
              "quantity",
              "unitCents",
              "amountCents",
              "sourceUrl"
            ]
          }
        },
        "reasons": {
          "type": "array",
          "items": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
              "code": {
                "type": "string"
              },
              "message": {
                "type": "string"
              },
              "sourceUrl": {
                "type": "string",
                "format": "uri"
              }
            },
            "required": [
              "code",
              "message",
              "sourceUrl"
            ]
          }
        },
        "notes": {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "citations": {
          "type": "array",
          "items": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
              "label": {
                "type": "string"
              },
              "url": {
                "type": "string",
                "format": "uri"
              }
            },
            "required": [
              "label",
              "url"
            ]
          }
        }
      },
      "required": [
        "status",
        "edition",
        "scheduleMaximumCents",
        "administratorAmountCents",
        "orderingPartyAmountCents",
        "contractAmountCents",
        "submittedChargeCents",
        "taxCents",
        "surchargeCents",
        "components",
        "reasons",
        "notes",
        "citations"
      ]
    }
    SimulateDentalSandboxReceipt:
      oneOf:
      - type: object
        properties:
          provider:
            type: string
            const: simulated
          receiptId:
            type: string
            pattern: ^[A-Za-z0-9_-]{1,255}$
          outcome:
            type: string
            const: accepted
        required:
        - provider
        - receiptId
        - outcome
        additionalProperties: false
      - type: object
        properties:
          provider:
            type: string
            const: simulated
          receiptId:
            type: string
            pattern: ^[A-Za-z0-9_-]{1,255}$
          outcome:
            type: string
            const: rejected
          reason:
            type: string
            enum:
            - invalid_claim
            - missing_information
        required:
        - provider
        - receiptId
        - outcome
        - reason
        additionalProperties: false
      - type: object
        properties:
          provider:
            type: string
            const: simulated
          receiptId:
            type: string
            pattern: ^[A-Za-z0-9_-]{1,255}$
          outcome:
            type: string
            const: payment
          linePayments:
            type: array
            minItems: 1
            maxItems: 100
            items:
              type: object
              properties:
                lineId:
                  type: string
                  pattern: ^[A-Za-z0-9_-]{1,255}$
                paidCents:
                  type: integer
                  minimum: 1
                  maximum: 1000000000
              required:
              - lineId
              - paidCents
              additionalProperties: false
        required:
        - provider
        - receiptId
        - outcome
        - linePayments
        additionalProperties: false
      discriminator:
        propertyName: outcome
    DentalSandboxReceipt:
      oneOf:
      - type: object
        properties:
          provider:
            type: string
            const: simulated
          receiptId:
            type: string
            pattern: ^[A-Za-z0-9_-]{1,255}$
          outcome:
            type: string
            const: accepted
          id:
            type: string
            pattern: ^[A-Za-z0-9_-]{1,255}$
          simulated:
            type: boolean
            const: true
          status:
            type: string
            enum:
            - submitted
            - accepted
            - rejected
            - partially_paid
            - paid
          receivedAt:
            type: string
            format: date-time
        required:
        - provider
        - receiptId
        - outcome
        - id
        - simulated
        - status
        - receivedAt
        additionalProperties: false
      - type: object
        properties:
          provider:
            type: string
            const: simulated
          receiptId:
            type: string
            pattern: ^[A-Za-z0-9_-]{1,255}$
          outcome:
            type: string
            const: rejected
          reason:
            type: string
            enum:
            - invalid_claim
            - missing_information
          id:
            type: string
            pattern: ^[A-Za-z0-9_-]{1,255}$
          simulated:
            type: boolean
            const: true
          status:
            type: string
            enum:
            - submitted
            - accepted
            - rejected
            - partially_paid
            - paid
          receivedAt:
            type: string
            format: date-time
        required:
        - provider
        - receiptId
        - outcome
        - reason
        - id
        - simulated
        - status
        - receivedAt
        additionalProperties: false
      - type: object
        properties:
          provider:
            type: string
            const: simulated
          receiptId:
            type: string
            pattern: ^[A-Za-z0-9_-]{1,255}$
          outcome:
            type: string
            const: payment
          linePayments:
            type: array
            minItems: 1
            maxItems: 100
            items:
              type: object
              properties:
                lineId:
                  type: string
                  pattern: ^[A-Za-z0-9_-]{1,255}$
                paidCents:
                  type: integer
                  minimum: 1
                  maximum: 1000000000
              required:
              - lineId
              - paidCents
              additionalProperties: false
          id:
            type: string
            pattern: ^[A-Za-z0-9_-]{1,255}$
          simulated:
            type: boolean
            const: true
          status:
            type: string
            enum:
            - submitted
            - accepted
            - rejected
            - partially_paid
            - paid
          receivedAt:
            type: string
            format: date-time
        required:
        - provider
        - receiptId
        - outcome
        - linePayments
        - id
        - simulated
        - status
        - receivedAt
        additionalProperties: false
      discriminator:
        propertyName: outcome
    DentalPaperFormReadiness:
      type: object
      additionalProperties: false
      required:
      - clinicalStatus
      - missingFields
      - templateStatus
      - liveUseBlocked
      properties:
        clinicalStatus:
          type: string
          enum:
          - complete
          - requires_completion
        missingFields:
          type: array
          items:
            type: string
            enum:
            - adaForm.patientConsent
            - adaForm.directPaymentAuthorization
            - adaForm.providerCertification
            - adaForm.treatingLicenseNumber
            - adaForm.treatmentLocation
            - adaForm.treatingPhone
        templateStatus:
          type: string
          const: sample_only
        liveUseBlocked:
          type: boolean
          const: true
    ChargeScheduleInput:
      type: object
      additionalProperties: false
      required:
      - name
      - billingProviderId
      - effectiveFrom
      - effectiveThrough
      - jurisdictions
      - entries
      properties:
        name:
          type: string
          minLength: 1
          maxLength: 120
        billingProviderId:
          type: string
          minLength: 1
          maxLength: 120
        kind:
          type: string
          enum:
          - practice_charge
          - contracted_rate
          default: practice_charge
        payerId:
          type: string
          minLength: 1
          maxLength: 120
          description: Required for contracted_rate.
        effectiveFrom:
          type: string
          format: date
        effectiveThrough:
          type: string
          format: date
          description: Inclusive end date on or after effectiveFrom.
        jurisdictions:
          type: array
          minItems: 1
          maxItems: 3
          items:
            type: string
            enum:
            - CA
            - NY
            - OWCP
        placesOfService:
          type: array
          maxItems: 100
          default: []
          items:
            type: string
            pattern: ^[0-9]{2}$
        entries:
          type: array
          minItems: 1
          maxItems: 25000
          items:
            type: object
            additionalProperties: false
            required:
            - code
            oneOf:
            - required:
              - unitChargeCents
              not:
                required:
                - percentBasisPoints
            - required:
              - percentBasisPoints
              not:
                required:
                - unitChargeCents
            properties:
              code:
                type: string
                pattern: ^[A-Za-z0-9]{5}$
              modifiers:
                type: array
                maxItems: 4
                default: []
                items:
                  type: string
                  pattern: ^[A-Za-z0-9]{2}$
              ndcNumber:
                type: string
                pattern: ^[0-9]{11}$
              unitChargeCents:
                type: integer
                minimum: 1
                maximum: 100000000
              percentBasisPoints:
                type: integer
                minimum: 1
                maximum: 100000
                description: 10000 means 100 percent of the official unit maximum.
    DentalTestEnvelope:
      type: object
      additionalProperties: false
      properties:
        senderQualifier:
          type: string
          enum:
          - ZZ
          - '30'
        senderId:
          type: string
          minLength: 1
          maxLength: 15
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
        receiverQualifier:
          type: string
          enum:
          - ZZ
          - '30'
        receiverId:
          type: string
          minLength: 1
          maxLength: 15
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
        applicationSenderId:
          type: string
          minLength: 1
          maxLength: 15
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
        applicationReceiverId:
          type: string
          minLength: 1
          maxLength: 15
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
        submitterName:
          type: string
          minLength: 1
          maxLength: 60
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
        submitterId:
          type: string
          minLength: 1
          maxLength: 80
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
        contactName:
          type: string
          minLength: 1
          maxLength: 60
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
        contactPhone:
          type: string
          pattern: ^\d{10}$
        receiverName:
          type: string
          minLength: 1
          maxLength: 60
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
        receiverSubmitterId:
          type: string
          minLength: 1
          maxLength: 80
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
        interchangeControl:
          type: string
          pattern: ^\d{9}$
          description: Additional runtime validation applies; see Dental preparation description.
        groupControl:
          type: string
          pattern: ^\d{1,9}$
          description: Additional runtime validation applies; see Dental preparation description.
        transactionControl:
          type: string
          pattern: ^[A-Z0-9]{4,9}$
        referenceId:
          type: string
          minLength: 1
          maxLength: 50
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
        date:
          type: string
          format: date
        time:
          type: string
          pattern: ^([01]\d|2[0-3])[0-5]\d$
        acknowledgementRequested:
          type: string
          enum:
          - '0'
          - '1'
      required:
      - senderQualifier
      - senderId
      - receiverQualifier
      - receiverId
      - applicationSenderId
      - applicationReceiverId
      - submitterName
      - submitterId
      - contactName
      - contactPhone
      - receiverName
      - receiverSubmitterId
      - interchangeControl
      - groupControl
      - transactionControl
      - referenceId
      - date
      - time
      - acknowledgementRequested
    DentalProsthesis:
      oneOf:
      - type: object
        additionalProperties: false
        properties:
          placement:
            const: I
        required:
        - placement
      - type: object
        additionalProperties: false
        properties:
          placement:
            const: R
          priorPlacementDate:
            type: string
            format: date
        required:
        - placement
        - priorPlacementDate
      discriminator:
        propertyName: placement
    DentalPreparationRequest:
      type: object
      additionalProperties: false
      required:
      - expectedRevision
      - jurisdiction
      - claim
      properties:
        expectedRevision:
          type: integer
          minimum: 1
        jurisdiction:
          enum:
          - CA
          - NY
          - OWCP
        claim:
          $ref: '#/components/schemas/DentalTestClaim'
    DentalOrthodontics:
      type: object
      additionalProperties: false
      properties:
        appliancePlacementDate:
          type: string
          format: date
        totalMonths:
          type: integer
          exclusiveMinimum: 0
          maximum: 999
        remainingMonths:
          type: integer
          minimum: 0
          maximum: 999
      required:
      - appliancePlacementDate
      - totalMonths
      - remainingMonths
      description: Additional runtime validation applies; see Dental preparation description.
    DentalPreparationResponse:
      type: object
      required:
        - data
      properties:
        data:
          type: object
          required:
            - id
            - draftId
            - draftRevision
            - status
            - transmissionStatus
            - pricingStatus
            - pricing
            - totalChargeCents
            - ediSha256
            - pdfSha256
            - artifacts
            - paperForm
          properties:
            id:
              type: string
            draftId:
              type: string
            draftRevision:
              type: integer
            status:
              const: sandbox_prepared
            transmissionStatus:
              const: not_transmitted
            pricingStatus:
              enum:
                - requires_review
                - matched_schedules
            pricing:
              type: array
              items:
                type: object
                required:
                  - line
                  - chargeCents
                  - chargeBasis
                  - practice
                  - statutory
                  - statutoryLineMaximumCents
                  - priorAuthorizationRequired
                  - reviewRequired
                properties:
                  line:
                    type: integer
                  chargeCents:
                    type: integer
                  chargeBasis:
                    enum:
                      - practice_schedule
                      - documented_manual_charge
                  practice:
                    type: object
                    description: PracticeChargeResult with matched, unmatched or requires_review
                      status and provenance.
                  statutory:
                    type: object
                    description: "DentalRateResult: matched unitMaximumCents and provenance,
                      otherwise unmatched/requires_review and reason."
                  statutoryLineMaximumCents:
                    type:
                      - integer
                      - "null"
                  priorAuthorizationRequired:
                    type:
                      - boolean
                      - "null"
                  reviewRequired:
                    type: boolean
            totalChargeCents:
              type: integer
            ediSha256:
              type:
                - string
                - "null"
              pattern: ^[a-f0-9]{64}$
            pdfSha256:
              type: string
              pattern: ^[a-f0-9]{64}$
            artifacts:
              type: object
              properties:
                edi:
                  type:
                    - string
                    - "null"
                pdf:
                  type: string
              required:
                - edi
                - pdf
            paperForm:
              oneOf:
                - $ref: "#/components/schemas/DentalPaperFormReadiness"
                - $ref: "#/components/schemas/NyDentalPaperFormReadiness"
            documentType:
              type: string
              enum:
                - ada_837d
                - ny_cms1500
    DentalTestClaim:
      type: object
      additionalProperties: false
      properties:
        envelope:
          type: object
          additionalProperties: false
          properties:
            senderQualifier:
              type: string
              enum:
              - ZZ
              - '30'
            senderId:
              type: string
              minLength: 1
              maxLength: 15
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            receiverQualifier:
              type: string
              enum:
              - ZZ
              - '30'
            receiverId:
              type: string
              minLength: 1
              maxLength: 15
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            applicationSenderId:
              type: string
              minLength: 1
              maxLength: 15
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            applicationReceiverId:
              type: string
              minLength: 1
              maxLength: 15
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            submitterName:
              type: string
              minLength: 1
              maxLength: 60
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            submitterId:
              type: string
              minLength: 1
              maxLength: 80
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            contactName:
              type: string
              minLength: 1
              maxLength: 60
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            contactPhone:
              type: string
              pattern: ^\d{10}$
            receiverName:
              type: string
              minLength: 1
              maxLength: 60
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            receiverSubmitterId:
              type: string
              minLength: 1
              maxLength: 80
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            interchangeControl:
              type: string
              pattern: ^\d{9}$
              description: Additional runtime validation applies; see Dental preparation description.
            groupControl:
              type: string
              pattern: ^\d{1,9}$
              description: Additional runtime validation applies; see Dental preparation description.
            transactionControl:
              type: string
              pattern: ^[A-Z0-9]{4,9}$
            referenceId:
              type: string
              minLength: 1
              maxLength: 50
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            date:
              type: string
              format: date
            time:
              type: string
              pattern: ^([01]\d|2[0-3])[0-5]\d$
            acknowledgementRequested:
              type: string
              enum:
              - '0'
              - '1'
          required:
          - senderQualifier
          - senderId
          - receiverQualifier
          - receiverId
          - applicationSenderId
          - applicationReceiverId
          - submitterName
          - submitterId
          - contactName
          - contactPhone
          - receiverName
          - receiverSubmitterId
          - interchangeControl
          - groupControl
          - transactionControl
          - referenceId
          - date
          - time
          - acknowledgementRequested
        attestations:
          type: object
          additionalProperties: false
          properties:
            providerSignatureOnFile:
              type: boolean
            providerAcceptAssignment:
              type: string
              enum:
              - A
              - B
              - C
            benefitsAssignment:
              type: string
              enum:
              - Y
              - N
              - W
            releaseOfInformation:
              type: string
              enum:
              - I
              - Y
            evidenceReference:
              type: string
              minLength: 1
              maxLength: 255
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
          required:
          - providerSignatureOnFile
          - providerAcceptAssignment
          - benefitsAssignment
          - releaseOfInformation
          - evidenceReference
        authorizationNumber:
          type: string
          minLength: 1
          maxLength: 50
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
        orthodontics:
          type: object
          additionalProperties: false
          properties:
            appliancePlacementDate:
              type: string
              format: date
            totalMonths:
              type: integer
              exclusiveMinimum: 0
              maximum: 999
            remainingMonths:
              type: integer
              minimum: 0
              maximum: 999
          required:
          - appliancePlacementDate
          - totalMonths
          - remainingMonths
          description: Additional runtime validation applies; see Dental preparation description.
        missingTeeth:
          type: array
          items:
            type: string
            pattern: ^(?:[1-9]|[12]\d|3[0-2]|[A-T])$
          maxItems: 32
          description: Additional runtime validation applies; see Dental preparation description.
          default: []
        billingProvider:
          type: object
          additionalProperties: false
          properties:
            name:
              type: string
              minLength: 1
              maxLength: 60
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            npi:
              type: string
              pattern: ^\d{10}$
              description: Additional runtime validation applies; see Dental preparation description.
            taxId:
              type: string
              pattern: ^\d{9}$
            address:
              type: object
              additionalProperties: false
              properties:
                line1:
                  type: string
                  minLength: 1
                  maxLength: 55
                  pattern: ^[\x20-\x7e]+$
                  description: Additional runtime validation applies; see Dental preparation description.
                city:
                  type: string
                  minLength: 1
                  maxLength: 30
                  pattern: ^[\x20-\x7e]+$
                  description: Additional runtime validation applies; see Dental preparation description.
                state:
                  type: string
                  pattern: ^[A-Z]{2}$
                postalCode:
                  type: string
                  pattern: ^\d{5}(\d{4})?$
              required:
              - line1
              - city
              - state
              - postalCode
            phone:
              type: string
              pattern: ^\d{10}$
          required:
          - name
          - npi
          - taxId
          - address
          - phone
        renderingProvider:
          type: object
          additionalProperties: false
          properties:
            firstName:
              type: string
              minLength: 1
              maxLength: 35
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            lastName:
              type: string
              minLength: 1
              maxLength: 60
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            npi:
              type: string
              pattern: ^\d{10}$
              description: Additional runtime validation applies; see Dental preparation description.
            taxonomy:
              type: string
              pattern: ^1223[A-Z0-9]{5}X$
          required:
          - firstName
          - lastName
          - npi
          - taxonomy
        employer:
          type: object
          additionalProperties: false
          properties:
            name:
              type: string
              minLength: 1
              maxLength: 60
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            address:
              type: object
              additionalProperties: false
              properties:
                line1:
                  type: string
                  minLength: 1
                  maxLength: 55
                  pattern: ^[\x20-\x7e]+$
                  description: Additional runtime validation applies; see Dental preparation description.
                city:
                  type: string
                  minLength: 1
                  maxLength: 30
                  pattern: ^[\x20-\x7e]+$
                  description: Additional runtime validation applies; see Dental preparation description.
                state:
                  type: string
                  pattern: ^[A-Z]{2}$
                postalCode:
                  type: string
                  pattern: ^\d{5}(\d{4})?$
              required:
              - line1
              - city
              - state
              - postalCode
          required:
          - name
          - address
        patient:
          type: object
          additionalProperties: false
          properties:
            firstName:
              type: string
              minLength: 1
              maxLength: 35
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            lastName:
              type: string
              minLength: 1
              maxLength: 60
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            address:
              type: object
              additionalProperties: false
              properties:
                line1:
                  type: string
                  minLength: 1
                  maxLength: 55
                  pattern: ^[\x20-\x7e]+$
                  description: Additional runtime validation applies; see Dental preparation description.
                city:
                  type: string
                  minLength: 1
                  maxLength: 30
                  pattern: ^[\x20-\x7e]+$
                  description: Additional runtime validation applies; see Dental preparation description.
                state:
                  type: string
                  pattern: ^[A-Z]{2}$
                postalCode:
                  type: string
                  pattern: ^\d{5}(\d{4})?$
              required:
              - line1
              - city
              - state
              - postalCode
            birthDate:
              type: string
              format: date
            gender:
              type: string
              enum:
              - M
              - F
              - U
            ssn:
              type: string
              pattern: ^\d{9}$
          required:
          - firstName
          - lastName
          - address
          - birthDate
          - gender
          - ssn
        payer:
          type: object
          additionalProperties: false
          properties:
            name:
              type: string
              minLength: 1
              maxLength: 60
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            id:
              type: string
              minLength: 1
              maxLength: 80
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            address:
              type: object
              additionalProperties: false
              properties:
                line1:
                  type: string
                  minLength: 1
                  maxLength: 55
                  pattern: ^[\x20-\x7e]+$
                  description: Additional runtime validation applies; see Dental preparation description.
                city:
                  type: string
                  minLength: 1
                  maxLength: 30
                  pattern: ^[\x20-\x7e]+$
                  description: Additional runtime validation applies; see Dental preparation description.
                state:
                  type: string
                  pattern: ^[A-Z]{2}$
                postalCode:
                  type: string
                  pattern: ^\d{5}(\d{4})?$
              required:
              - line1
              - city
              - state
              - postalCode
          required:
          - name
          - id
          - address
        claimId:
          type: string
          minLength: 1
          maxLength: 20
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
        workersCompClaimNumber:
          type: string
          minLength: 1
          maxLength: 50
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
        injuryDate:
          type: string
          format: date
        placeOfService:
          type: string
          pattern: ^\d{2}$
        diagnosisCodes:
          type: array
          items:
            type: string
            pattern: ^[A-Z][A-Z0-9]{2,6}$
          maxItems: 4
          description: Additional runtime validation applies; see Dental preparation description.
          default: []
        lines:
          type: array
          items:
            type: object
            additionalProperties: false
            properties:
              code:
                type: string
                pattern: ^D\d{4}$
              serviceDate:
                type: string
                format: date
              prosthesis:
                oneOf:
                - type: object
                  additionalProperties: false
                  properties:
                    placement:
                      const: I
                  required:
                  - placement
                - type: object
                  additionalProperties: false
                  properties:
                    placement:
                      const: R
                    priorPlacementDate:
                      type: string
                      format: date
                  required:
                  - placement
                  - priorPlacementDate
                discriminator:
                  propertyName: placement
              chargeCents:
                type: integer
                exclusiveMinimum: 0
                maximum: 1000000000
              quantity:
                type: integer
                exclusiveMinimum: 0
                maximum: 9999
              oralCavity:
                type: string
                enum:
                - '00'
                - '01'
                - '02'
                - '10'
                - '20'
                - '30'
                - '40'
              teeth:
                type: array
                items:
                  type: object
                  additionalProperties: false
                  properties:
                    number:
                      type: string
                      pattern: ^(?:[1-9]|[12]\d|3[0-2]|[A-T])$
                    surfaces:
                      type: array
                      items:
                        type: string
                        enum:
                        - B
                        - D
                        - F
                        - I
                        - L
                        - M
                        - O
                      maxItems: 5
                      description: Additional runtime validation applies; see Dental preparation description.
                      default: []
                  required:
                  - number
                maxItems: 32
                default: []
              diagnosisPointers:
                type: array
                items:
                  type: integer
                  minimum: 1
                  maximum: 4
                maxItems: 4
                description: Additional runtime validation applies; see Dental preparation description.
                default: []
            required:
            - code
            - serviceDate
            - chargeCents
            description: Additional runtime validation applies; see Dental preparation description.
          minItems: 1
          maxItems: 50
        adaForm:
          $ref: '#/components/schemas/DentalAdaForm'
      required:
      - envelope
      - attestations
      - billingProvider
      - renderingProvider
      - employer
      - patient
      - payer
      - claimId
      - workersCompClaimNumber
      - injuryDate
      - placeOfService
      - lines
      description: Additional runtime validation applies; see Dental preparation description.
    DentalSandboxLine:
      type: object
      properties:
        id:
          type: string
          pattern: ^[A-Za-z0-9_-]{1,255}$
        lineNumber:
          type: integer
          minimum: 1
        code:
          type: string
          pattern: ^D[0-9]{4}$
        serviceDate:
          type: string
          format: date
        chargeCents:
          type: integer
          minimum: 0
        paidCents:
          type: integer
          minimum: 0
        quantity:
          type: integer
          minimum: 1
        teeth:
          type: array
          items:
            type: string
        surfaces:
          type: array
          items:
            type: string
        diagnosisPointers:
          type: array
          items:
            type: integer
            minimum: 1
            maximum: 4
          maxItems: 4
          uniqueItems: true
      required:
      - id
      - lineNumber
      - code
      - serviceDate
      - chargeCents
      - paidCents
      - quantity
      - teeth
      - surfaces
      - diagnosisPointers
    ChargeSchedule:
      description: Saved schedule with the ChargeScheduleInput fields plus immutable identity and lifecycle metadata.
      type: object
      required:
      - id
      - name
      - billingProviderId
      - kind
      - effectiveFrom
      - effectiveThrough
      - jurisdictions
      - placesOfService
      - entries
      - active
      - createdAt
      properties:
        id:
          type: string
        name:
          type: string
        billingProviderId:
          type: string
        kind:
          type: string
          enum:
          - practice_charge
          - contracted_rate
        payerId:
          type: string
        effectiveFrom:
          type: string
          format: date
        effectiveThrough:
          type: string
          format: date
        jurisdictions:
          type: array
          items:
            type: string
            enum:
            - CA
            - NY
            - OWCP
        placesOfService:
          type: array
          items:
            type: string
        entries:
          type: array
          items:
            type: object
        active:
          type: boolean
        createdAt:
          type: string
          format: date-time
    DentalSandboxBillResponse:
      type: object
      properties:
        data:
          $ref: '#/components/schemas/DentalSandboxBill'
      required:
      - data
      additionalProperties: false
    CreateDentalSandboxBill:
      type: object
      properties:
        preparationId:
          type: string
          pattern: ^[A-Za-z0-9_-]{1,255}$
        provider:
          type: string
          const: simulated
      required:
      - preparationId
      - provider
      additionalProperties: false
    BilledDrug:
      type: object
      additionalProperties: false
      required: [ndcNumber, metricQuantity, unitOfMeasure]
      description: Explicit billed drug facts, retained with the service line. Metric quantity is independent of procedure units.
      properties:
        ndcNumber: {type: string, pattern: '^[0-9]{11}$'}
        metricQuantity:
          type: string
          pattern: '^(?:0|[1-9][0-9]{0,4})(?:\.[0-9]{1,3})?$'
          description: Positive total metric quantity up to 10000, with at most three decimal places. Never package count.
        unitOfMeasure: {type: string, enum: [UN, ML, GR]}
    PharmacyBillingContext:
      type: object
      additionalProperties: false
      required: [dispenser, productKind, usualCustomaryCents, noSubstitution, codingRequirementsSatisfied]
      description: Explicit California dispensing facts. Only simple dispensed S5000/S5001 lines with verified coding context are supported. Compound, repackaged and administered drugs require review. Pharmacy NPI must match the actual billing provider when dispenser is pharmacy. Bill date, billed amount and drug identity come from the service line.
      properties:
        dispenser: {type: string, enum: [physician, pharmacy]}
        productKind: {type: string, enum: [simple, repackaged, compound, physician_administered]}
        usualCustomaryCents: {type: integer, minimum: 0, maximum: 100000000}
        pharmacyNpi: {type: string, pattern: '^[0-9]{10}$'}
        noSubstitution: {type: boolean}
        noSubstitutionRequirementsSatisfied: {type: boolean}
        physicianDispensingRequirementsSatisfied: {type: boolean}
        physicianPaidForDrug: {type: boolean}
        documentedPaidCostCents: {type: integer, minimum: 0, maximum: 100000000}
        acquisitionDocumentationIncluded: {type: boolean}
        codingRequirementsSatisfied:
          type: boolean
          description: Attests that the procedure and submitted NDC metric quantity and unit of measure are correct for the dispensed drug. The official PFS cost file does not provide a metric unit; MindBill does not infer package conversions or verify the submitted unit against that file.
    CaDmeposContext:
      type: object
      additionalProperties: false
      properties:
        residenceZip:
          type: string
          pattern: ^(?!00000)[0-9]{5}(-?[0-9]{4})?$
        supplierType:
          type: string
          enum:
          - physician
          - other
          description: Required for calculation although optional in request validation. Physician-supplied equipment
            requires documented cost-limit review.
        rentalMonth:
          type: integer
          minimum: 1
          maximum: 1000
          description: Continuous rental month. PEN rentals must match paidRentalMonths plus one. Omit for repair and
            oxygen maintenance.
        priorPaymentsCents:
          type: integer
          minimum: 0
          maximum: 9007199254740991
          description: Cumulative prior payments for applicable equipment caps. Omit for PEN pumps, which use prior
            allowed rental amounts, and for repair or oxygen maintenance.
        oxygenMaintenance:
          $ref: '#/components/schemas/CaOxygenMaintenanceFacts'
        repairContext:
          $ref: '#/components/schemas/CaDmeRepairContext'
        penPump:
          $ref: '#/components/schemas/CaPenPumpContext'
      required:
      - residenceZip
      description: California equipment pricing uses the injured worker residence ZIP, not the service location. Supplier
        type is required to calculate a fee. Select the applicable rental, repair, PEN pump or oxygen maintenance context;
        incompatible combinations require review. Ordinary oxygen rentals, dialysis bundles and unsupported histories
        require review. These facts support a fee calculation, not a coverage or treatment authorization decision.
    CaDmeRepairContext:
      type: object
      additionalProperties: false
      properties:
        equipmentType:
          type: string
          enum:
          - cpap
          - hospital_bed
          - manual_wheelchair
          - power_wheelchair
          - patient_lift
          - seat_lift
          - orthosis
          - prosthesis
        equipmentDeliveredOn:
          type: string
          pattern: ^\d{4}-\d{2}-\d{2}$
          format: date
        serviceType:
          type: string
          enum:
          - repair
          - adjustment
          - routine_maintenance
        ownership:
          type: string
          enum:
          - owned
          - rented
        warrantyCoversRepair:
          type: boolean
        equipmentPaymentClass:
          type: string
          enum:
          - ordinary
          - oxygen
          - frequent_servicing
          - capped_rental_early_transfer
        laborMinutes:
          type: integer
          exclusiveMinimum: 0
          maximum: 1440
        repairNeedDocumented:
          type: boolean
        continuedMedicalNeedDocumented:
          type: boolean
        repairNarrativeDocumented:
          type: boolean
        excludesBundledProfessionalServices:
          type: boolean
        task:
          type: string
          enum:
          - cpap_blower
          - bed_pendant
          - bed_headboard_or_footboard
          - wheelchair_anti_tip
          - lift_hydraulic_pump
          - wheelchair_one_wheel_or_tire
          - wheelchair_one_armrest_or_pad
          - power_wheelchair_one_motor
          - power_wheelchair_motor_pair
          - power_wheelchair_shroud
          - power_wheelchair_joystick
          - power_wheelchair_charger
          - power_wheelchair_batteries
          - seat_lift_scissors
          - seat_lift_hand_control
          description: Required for supported K0739 equipment tasks. Orthosis and prosthesis labor uses documented actual
            time instead.
        partsBilling:
          type: string
          enum:
          - none
          - L4210
          - L7510
          - specific_hcpcs
          description: L7520 includes minor parts and labor. Separately coded major components must be documented without
            duplicate payment.
        paymentContext:
          $ref: '#/components/schemas/CaDmeRepairPaymentContext'
      required:
      - equipmentType
      - equipmentDeliveredOn
      - serviceType
      - ownership
      - warrantyCoversRepair
      - equipmentPaymentClass
      - laborMinutes
      - repairNeedDocumented
      - continuedMedicalNeedDocumented
      - repairNarrativeDocumented
      - excludesBundledProfessionalServices
      - partsBilling
      description: Documented repair facts for K0739, L4205 or L7520. Supported task-specific units, actual time, bundling
        and repair-versus-replacement cost limits are validated; units multiplied by a labor rate alone are insufficient.
        paymentContext is optional in request validation but required for a calculated repair fee.
    CaPenPumpContext:
      type: object
      additionalProperties: false
      properties:
        historyStatus:
          type: string
          enum:
          - complete_all_suppliers
          - incomplete
        medicalNeedPeriodStatus:
          type: string
          enum:
          - continuous
          - restart_or_prescription_change
          - uncertain
        paidRentalMonths:
          type: integer
          minimum: 0
          maximum: 9007199254740991
        priorRentalAllowanceCents:
          type: integer
          minimum: 0
          maximum: 9007199254740991
          description: Total allowed rental amount across all suppliers, irrespective of cash paid. Explicit zero is
            required when there were no prior rentals.
        previouslyPurchased:
          type: boolean
        pumpCount:
          type: integer
          exclusiveMinimum: 0
          maximum: 10000
        rentalMonthStatus:
          type: string
          enum:
          - full_month
          - partial_or_institutional
          - voluntary_nonbilling
          - unknown
          description: full_month is required for calculated RR rentals; partial, institutional, voluntary nonbilling
            and unknown periods require review.
        purchaseAuthorization:
          type: string
          enum:
          - written
          - missing
          description: written authorization is required for NU or UE purchase pricing. NU after rentals requires review.
        currentRentalPeriodAlreadyBilled:
          type: boolean
          description: An explicit false is required for RR. Omission requires rental-period history; true identifies
            duplicate billing and requires review.
      required:
      - historyStatus
      - medicalNeedPeriodStatus
      - paidRentalMonths
      - priorRentalAllowanceCents
      - previouslyPurchased
      - pumpCount
      description: B9002, B9004 and B9006 pump facts for January 2024 through March 2026. Complete history across all
        suppliers in the same medical-need period is required. Fifteen paid rental months exhaust the rental allowance;
        used purchase after rentals subtracts prior allowed rental amounts, not cash payments. Exhausted or ambiguous
        histories require review.
    CaOxygenMaintenanceVisitTiming:
      description: Visit-specific evidence for replaying the patient's maintenance sequence. When any timing is supplied
        or any delay/reset occurred, timing is required for the current visit and every prior paid/pending visit.
        A documented unavoidable delay beyond the first month resets subsequent eligibility to six months after
        the actual inspection. Delayed inspections on days 29 through 31 require boundary review.
      oneOf:
      - type: object
        additionalProperties: false
        properties:
          kind:
            type: string
            enum: [ordinary]
          scheduledPeriodStart:
            type: string
            format: date
            pattern: ^\d{4}-\d{2}-\d{2}$
          firstInHomeInspectionConfirmed:
            type: boolean
        required: [kind, scheduledPeriodStart, firstInHomeInspectionConfirmed]
      - type: object
        additionalProperties: false
        properties:
          kind:
            type: string
            enum: [unavoidable_delay]
          scheduledPeriodStart:
            type: string
            format: date
            pattern: ^\d{4}-\d{2}-\d{2}$
          firstInHomeInspectionConfirmed:
            type: boolean
          reason:
            type: string
            enum: [hospitalization, out_of_service_area, other_unavoidable]
          reasonDocumented:
            type: boolean
        required: [kind, scheduledPeriodStart, firstInHomeInspectionConfirmed, reason, reasonDocumented]
    CaOxygenMaintenanceFacts:
      type: object
      additionalProperties: false
      properties:
        equipment:
          type: array
          items:
            type: object
            additionalProperties: false
            properties:
              code:
                type: string
                enum:
                - E1390
                - E1391
                - E0433
                - K0738
                - E1392
              ownership:
                type: string
                enum:
                - supplier
                - patient
              rentalCapEndedOn:
                anyOf:
                - type: string
                  pattern: ^\d{4}-\d{2}-\d{2}$
                  format: date
                - type: 'null'
            required:
            - code
            - ownership
            - rentalCapEndedOn
          minItems: 1
          maxItems: 10
          description: Complete equipment inventory. E1392 is context only and is never a separate maintenance payment.
            Supplier-owned equipment requires its verified rental-cap end date; patient-owned equipment uses null.
        equipmentInventoryComplete:
          type: boolean
        warrantyEndedOn:
          anyOf:
          - type: string
            pattern: ^\d{4}-\d{2}-\d{2}$
            format: date
          - type: 'null'
          description: End of the routine-maintenance labor warranty. Null means verified absence of a warranty, not
            unknown history.
        warrantyHistoryComplete:
          type: boolean
        continuedNeedDocumented:
          type: boolean
        withinReasonableUsefulLifetime:
          type: boolean
        supplierFurnished36thRentalMonth:
          type: boolean
        replacementRentalStarted:
          type: boolean
        firstInHomeInspectionOn:
          type: string
          pattern: ^\d{4}-\d{2}-\d{2}$
          description: Actual documented first in-home inspection date; must match the billed date of service.
          format: date
        inspectionDocumented:
          type: boolean
        currentVisitTiming:
          $ref: '#/components/schemas/CaOxygenMaintenanceVisitTiming'
        priorMaintenance:
          type: array
          items:
            type: object
            additionalProperties: false
            properties:
              code:
                type: string
                enum:
                - E1390
                - E1391
                - E0433
                - K0738
              dateOfService:
                type: string
                pattern: ^\d{4}-\d{2}-\d{2}$
                format: date
              visitTiming:
                $ref: '#/components/schemas/CaOxygenMaintenanceVisitTiming'
            required:
            - code
            - dateOfService
          maxItems: 1000
          description: All prior paid and pending maintenance claims across codes and suppliers. An empty array attests
            there are none when historyComplete is true. A prior claim in the same patient period requires review.
        historyComplete:
          type: boolean
        delayedVisitOrPeriodResetEverOccurred:
          type: boolean
          description: True requires complete per-visit timing evidence for the current and every prior visit. False
            attests that complete history confirms no delayed visit or reset; do not use false for unknown history.
        maintenanceLinesInCurrentClaim:
          type: integer
          minimum: 1
          maximum: 10000
          description: Actual count across the current claim or batch. A calculated fee requires exactly one maintenance
            line.
      required:
      - equipment
      - equipmentInventoryComplete
      - warrantyEndedOn
      - warrantyHistoryComplete
      - continuedNeedDocumented
      - withinReasonableUsefulLifetime
      - supplierFurnished36thRentalMonth
      - replacementRentalStarted
      - firstInHomeInspectionOn
      - inspectionDocumented
      - priorMaintenance
      - historyComplete
      - delayedVisitOrPeriodResetEverOccurred
      - maintenanceLinesInCurrentClaim
      description: Post-cap maintenance with one MS unit of E1390, E1391, E0433 or K0738, January 2024 through September
        2026. Requires complete inventory, warranty and all-supplier paid/pending maintenance history. Supported ordinary
        first-month periods and documented unavoidable delays with complete timing histories are calculated. Missing
        timing, ambiguous month-end delays and inconsistent histories require review. Do not combine
        with rental, repair, PEN or prior-payment context.
    CaDmeRepairPaymentContext:
      type: object
      additionalProperties: false
      properties:
        bundlingStatus:
          type: string
          enum:
          - owned_out_of_warranty
          - rental_or_warranty_included
          - unresolved
        singleLaborLineForRepair:
          type: boolean
        noDuplicateLaborBilling:
          type: boolean
        excludesTravelPickupDelivery:
          type: boolean
        otherRepairCostsCents:
          type: integer
          minimum: 0
          maximum: 9007199254740991
          description: All documented repair costs other than the labor amount being calculated; include separately
            payable parts without counting included parts or the same labor twice.
        otherRepairCostsComplete:
          type: boolean
        replacementPurchaseCostCents:
          type: integer
          exclusiveMinimum: 0
          maximum: 9007199254740991
        replacementComparisonDocumented:
          type: boolean
        replacementRental:
          oneOf:
          - type: object
            additionalProperties: false
            properties:
              status:
                type: string
                const: available
              costForRemainingNeedCents:
                type: integer
                exclusiveMinimum: 0
                maximum: 9007199254740991
            required:
            - status
            - costForRemainingNeedCents
          - type: object
            additionalProperties: false
            properties:
              status:
                type: string
                const: not_available
              unavailabilityDocumented:
                type: boolean
            required:
            - status
            - unavailabilityDocumented
          description: Provide the total replacement rental cost for the remaining medical need, or explicitly document
            that rental is unavailable. Missing or unresolved comparison facts require review when applicable.
      required:
      - bundlingStatus
      - singleLaborLineForRepair
      - noDuplicateLaborBilling
      - excludesTravelPickupDelivery
      - otherRepairCostsCents
      - otherRepairCostsComplete
      - replacementPurchaseCostCents
      - replacementComparisonDocumented
      description: Complete repair cost and payment facts. Calculated repairs require owned_out_of_warranty status and
        affirmative documentation, single-line, duplicate and excluded-travel confirmations. Total repair cost is calculated
        labor plus otherRepairCostsCents and is compared with documented replacement purchase and, where available,
        rental cost for the remaining period of need.
    CaHistoricalTelephoneContext:
      type: object
      additionalProperties: false
      properties:
        medicalDiscussionMinutes:
          type: integer
          minimum: 1
          maximum: 1440
        cpt2020CodeSelectionConfirmed:
          type: boolean
        californiaPatientClassification:
          type: string
          enum:
          - new
          - established
        californiaPatientClassificationConfirmed:
          type: boolean
        completeSameDayServicesConfirmed:
          type: boolean
        soleServiceForPatientProviderGroupDate:
          type: boolean
        personallyPerformedByPhysician:
          type: boolean
        noRelatedEvaluationManagementPreviousSevenDays:
          type: boolean
        noResultingEvaluationManagementNext24HoursOrSoonestAppointment:
          type: boolean
        noOverlappingBundledManagement:
          type: boolean
      required:
      - medicalDiscussionMinutes
      - cpt2020CodeSelectionConfirmed
      - californiaPatientClassification
      - californiaPatientClassificationConfirmed
      - completeSameDayServicesConfirmed
      - soleServiceForPatientProviderGroupDate
      - personallyPerformedByPhysician
      - noRelatedEvaluationManagementPreviousSevenDays
      - noResultingEvaluationManagementNext24HoursOrSoonestAppointment
      - noOverlappingBundledManagement
      description: Calculator-only context for March 1–31, 2020 physician audio-only 99441–99443, POS 11 with modifier
        95, established patients, and the sole service in the complete patient/provider-group/date encounter. Runtime
        verifies CPT time bands (5–10, 11–20 and 21–30 minutes respectively), required confirmations and related-service
        exclusions. Unsupported dates, time bands, new patients or incomplete encounters require review. This context
        is not accepted in persisted service-line fee context.
    OwcpBillContext:
      type: object
      additionalProperties: false
      required: [jurisdiction, program, category, completeSameDayServices, otherSameDayServices, codingRequirementsSatisfied, paymentAdjustmentsApply]
      description: >-
        Explicit federal jurisdiction and program for a treatment bill. Every line must use the same program.
        Injury state remains geographic information. Only a single actual service per date is supported;
        incomplete same-day services, bundling, payment adjustments and unresolved coding require review.
        Physician pricing requires one unit, providerKind physician, globalPeriodApplies false and hpsaBonusEligible false.
        Equipment rentals and non-NU equipment adjustments require review. Coverage and authorization are not determined.
        Saved claim jurisdiction and federal program cannot be changed by creating or editing another bill.
      properties:
        jurisdiction: {type: string, const: OWCP}
        program: {type: string, enum: [FECA, ENERGY, BLACK_LUNG]}
        category: {type: string, enum: [physician, clinical_lab, dmepos, padb]}
        completeSameDayServices: {type: boolean}
        otherSameDayServices: {type: boolean}
        codingRequirementsSatisfied: {type: boolean}
        paymentAdjustmentsApply: {type: boolean}
        providerKind: {type: string, enum: [physician, other]}
        globalPeriodApplies: {type: boolean}
        hpsaBonusEligible: {type: boolean}
    ServiceLineFeeContext:
      type: object
      additionalProperties: false
      description: Clinical context for a server-verified California or explicitly selected OWCP treatment fee. Identity, code, date, units, charge and location
        come from the bill. All prolonged-service lines must share the same time context and enumerate the actual same-day lines.
        Unpriceable context rejects creation with bill_fee_requires_review; omitted context preserves explicit manual charges except drug lines and S5000/S5001, which require verified pharmacy pricing.
      properties:
        owcpContext:
          $ref: '#/components/schemas/OwcpBillContext'
        pharmacyContext:
          $ref: '#/components/schemas/PharmacyBillingContext'
        dmeposContext:
          $ref: '#/components/schemas/CaDmeposContext'
        pages:
          type: integer
          minimum: 1
          maximum: 10000
        reportKind:
          type: string
          enum:
          - progress
          - permanent_stationary_pr3
          - permanent_stationary_pr4
        reportQualification:
          description: Explicit report/request context for WC005, WC007, WC008 and WC009. Pages are required for these quotes.
            Unknown or nonqualifying context requires review; this does not establish coding eligibility.
          oneOf:
          - type: object
            additionalProperties: false
            required:
            - kind
            - requestedBy
            - medicalLegalEvaluation
            - reportPayableUnderMedicalLegalSchedule
            properties:
              kind:
                type: string
                const: psychiatric_report
              requestedBy:
                type: string
                enum:
                - wcab
                - administrative_director
              medicalLegalEvaluation:
                type: boolean
                description: Whether this report is part of a medical-legal evaluation. This context is separate from whether
                  the report is payable under the medical-legal fee schedule. WC005 requires modifier 32.
              reportPayableUnderMedicalLegalSchedule:
                type: boolean
                description: Whether this report is payable under the medical-legal fee schedule. A priced WC005 quote requires
                  false.
          - type: object
            additionalProperties: false
            required:
            - kind
            - requestedBy
            - medicalLegalEvaluation
            - reportPayableUnderMedicalLegalSchedule
            properties:
              kind:
                type: string
                const: consultation_report
              requestedBy:
                type: string
                enum:
                - wcab
                - administrative_director
                - qme
                - ame
              medicalLegalEvaluation:
                type: boolean
                description: Whether this report is part of a medical-legal evaluation. QME/AME requests require true and modifier
                  30; WCAB/Administrative Director requests require modifier 32.
              reportPayableUnderMedicalLegalSchedule:
                type: boolean
                description: Whether this report is payable under the medical-legal fee schedule. A priced WC007 quote requires
                  false regardless of evaluation context.
          - type: object
            additionalProperties: false
            required:
            - kind
            - requestedBy
            - writtenRequest
            properties:
              kind:
                type: string
                const: chart_notes
              requestedBy:
                type: string
                const: claims_administrator
              writtenRequest:
                type: boolean
                description: Whether the claims administrator requested the chart notes in writing. A priced quote requires true
                  and no modifiers.
          - type: object
            additionalProperties: false
            required:
            - kind
            - requestedBy
            - writtenRequest
            - relatedToBilling
            - initialRequiredCopy
            properties:
              kind:
                type: string
                const: duplicate_report
              requestedBy:
                type: string
                const: claims_administrator
              writtenRequest:
                type: boolean
              relatedToBilling:
                type: boolean
              initialRequiredCopy:
                type: boolean
                description: Whether this is the initial required copy. A priced WC009 quote requires false; writtenRequest and
                  relatedToBilling must be true, with no modifiers.
        hasFeeAgreement:
          type: boolean
        therapyContext:
          type: object
          additionalProperties: false
          description: Actual calculation facts for bounded office PT estimates. Initial evaluations 97161-97163
            support one untimed unit as the sole same-day service during July-September 2026, with
            priorInitialEvaluationInEpisode=false. Minutes are required only for supported timed procedures.
            Missing applicable facts return requires_review. Empty modifiers or GP and hasFeeAgreement=false
            are required. See docs/partner-platform/therapy-fee-estimates.md for coverage and limitations.
          properties:
            providerKind:
              type: string
              enum:
              - physical_therapist
              - other
            personallyPerformed:
              type: boolean
            placeOfService:
              type: string
              pattern: ^\d{2}$
            hospitalPatient:
              type: boolean
            incidentToPhysicianService:
              type: boolean
            assistantInvolved:
              type: boolean
            priorInitialEvaluationInEpisode:
              type: boolean
              description: Whether an initial PT evaluation was already furnished in this episode of care.
                Initial evaluations 97161-97163 require false; unknown must stay omitted.
            directOneOnOneMinutes:
              type: integer
              minimum: 0
              maximum: 1440
            totalVisitMinutes:
              type: integer
              minimum: 0
              maximum: 1440
            visitsOnDate:
              type: integer
              minimum: 0
              maximum: 100
            completeSameDayServices:
              type: boolean
              description: Includes all disciplines and previously billed or pending services in the practice/group.
            otherSameDayServices:
              type: boolean
            globalPeriodApplies:
              type: boolean
            hpsaBonusEligible:
              type: boolean
        physicianContext:
          type: object
          additionalProperties: false
          required:
          - providerKind
          - placeOfService
          - standaloneService
          - globalPeriodApplies
          - hpsaBonusEligible
          properties:
            providerKind:
              type: string
              enum:
              - physician
              - physician_assistant
              - nurse_practitioner
              - clinical_nurse_specialist
              - other
            incidentToPhysicianService:
              type: boolean
              description: For a supported physician assistant, nurse practitioner, or clinical nurse specialist quote, explicitly
                attest false for independently billed services. True or omitted requires review; physician incident-to services
                also require review.
            placeOfService:
              type: string
              pattern: ^\d{2}$
            standaloneService:
              type: boolean
            globalPeriodApplies:
              type: boolean
            hpsaBonusEligible:
              type: boolean
        ndcNumber:
          type: string
          pattern: ^[0-9]{11}$
        catalogContext:
          type: object
          additionalProperties: false
          required:
          - codingRequirementsSatisfied
          properties:
            codingRequirementsSatisfied:
              type: boolean
            statusIAlternative:
              type: string
              enum:
              - none
              - cpt
              - drug
            completeSurgicalPackage:
              type: boolean
        prolongedServiceContext:
          type: object
          additionalProperties: false
          required:
          - totalMinutes
          - relatedEvaluationDate
          - ongoingPatientManagement
          - personallyPerformed
          - timeCountedInOtherServices
          - completeSameDayServices
          - sameDayServices
          properties:
            totalMinutes:
              type: integer
              minimum: 0
              maximum: 1440
            relatedEvaluationDate:
              type: string
              format: date
            ongoingPatientManagement:
              type: boolean
            personallyPerformed:
              type: boolean
            timeCountedInOtherServices:
              type: boolean
            completeSameDayServices:
              type: boolean
            sameDayServices:
              type: array
              minItems: 1
              maxItems: 2
              items:
                type: object
                additionalProperties: false
                required:
                - code
                - units
                properties:
                  code:
                    type: string
                    enum:
                    - '99358'
                    - '99359'
                  units:
                    type: integer
                    minimum: 1
                    maximum: 100
    DentalAttestations:
      type: object
      additionalProperties: false
      properties:
        providerSignatureOnFile:
          type: boolean
        providerAcceptAssignment:
          type: string
          enum:
          - A
          - B
          - C
        benefitsAssignment:
          type: string
          enum:
          - Y
          - N
          - W
        releaseOfInformation:
          type: string
          enum:
          - I
          - Y
        evidenceReference:
          type: string
          minLength: 1
          maxLength: 255
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
      required:
      - providerSignatureOnFile
      - providerAcceptAssignment
      - benefitsAssignment
      - releaseOfInformation
      - evidenceReference
    DentalAdaForm:
      type: object
      additionalProperties: false
      properties:
        patientConsent:
          type: object
          additionalProperties: false
          properties:
            mode:
              const: signature_on_file
            signerName:
              type: string
              minLength: 1
              maxLength: 95
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            signedDate:
              type: string
              format: date
            evidenceReference:
              type: string
              minLength: 1
              maxLength: 255
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
          required:
          - mode
          - signerName
          - signedDate
          - evidenceReference
        directPaymentAuthorization:
          type: object
          additionalProperties: false
          properties:
            mode:
              const: signature_on_file
            signerName:
              type: string
              minLength: 1
              maxLength: 95
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            signedDate:
              type: string
              format: date
            evidenceReference:
              type: string
              minLength: 1
              maxLength: 255
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
          required:
          - mode
          - signerName
          - signedDate
          - evidenceReference
        providerCertification:
          type: object
          additionalProperties: false
          properties:
            printedName:
              type: string
              minLength: 1
              maxLength: 96
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            signedDate:
              type: string
              format: date
            evidenceReference:
              type: string
              minLength: 1
              maxLength: 255
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
          required:
          - printedName
          - signedDate
          - evidenceReference
        treatingLicenseNumber:
          type: string
          minLength: 1
          maxLength: 30
          pattern: ^[\x20-\x7e]+$
          description: Additional runtime validation applies; see Dental preparation description.
        treatmentLocation:
          type: object
          additionalProperties: false
          properties:
            line1:
              type: string
              minLength: 1
              maxLength: 55
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            city:
              type: string
              minLength: 1
              maxLength: 30
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation description.
            state:
              type: string
              pattern: ^[A-Z]{2}$
            postalCode:
              type: string
              pattern: ^\d{5}(\d{4})?$
          required:
          - line1
          - city
          - state
          - postalCode
          description: Additional runtime validation applies; see Dental preparation description.
        treatingPhone:
          type: string
          pattern: ^\d{10}$
      required: []
      description: Recorded ADA form details, optional for sandbox preparation. Omitted consent, certification, license, physical
        address or treating phone is reported in paperForm.missingFields. Consent/certification references identify existing source
        records; supplying a string does not independently verify the record. Consent dates must be between patient birth and
        envelope date. Direct-payment consent requires benefitsAssignment Y; provider certification must name the rendering dentist
        exactly, follow all service dates and require providerSignatureOnFile true. Physical address must not be a PO Box and
        must equal the billing address in the CA/OWCP EDI profile. Draft and claim ADA details must agree. Organizational billing
        provider license box50 stays blank.
    DentalSandboxBill:
      type: object
      properties:
        nyCms1500:
          $ref: "#/components/schemas/NyDentalCms1500"
        id:
          type: string
          pattern: ^[A-Za-z0-9_-]{1,255}$
        preparationId:
          type: string
          pattern: ^[A-Za-z0-9_-]{1,255}$
        draftId:
          type: string
          pattern: ^[A-Za-z0-9_-]{1,255}$
        claimId:
          type: string
          pattern: ^[A-Za-z0-9_-]{1,255}$
        patientId:
          type: string
          pattern: ^[A-Za-z0-9_-]{1,255}$
        environment:
          type: string
          const: sandbox
        provider:
          type: string
          const: simulated
        transmissionStatus:
          type: string
          const: not_transmitted
        accounting:
          type: string
          const: sandbox_only
        liveSubmissionAvailable:
          type: boolean
          const: false
        status:
          type: string
          enum:
            - submitted
            - accepted
            - rejected
            - partially_paid
            - paid
        jurisdiction:
          type: string
          enum:
            - CA
            - OWCP
            - NY
        lines:
          type: array
          items:
            $ref: "#/components/schemas/DentalSandboxLine"
        totalChargeCents:
          type: integer
          minimum: 0
        paidCents:
          type: integer
          minimum: 0
        outstandingCents:
          type: integer
          minimum: 0
        pricingStatus:
          type: string
          enum:
            - requires_review
            - matched_schedules
        paperForm:
          oneOf:
            - $ref: "#/components/schemas/DentalPaperFormReadiness"
            - $ref: "#/components/schemas/NyDentalPaperFormReadiness"
        ediSha256:
          type:
            - string
            - "null"
          pattern: ^[a-f0-9]{64}$
        pdfSha256:
          type: string
          pattern: ^[a-f0-9]{64}$
        receipts:
          type: array
          items:
            $ref: "#/components/schemas/DentalSandboxReceipt"
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
        documentType:
          type: string
          enum:
            - ada_837d
            - ny_cms1500
      required:
        - id
        - preparationId
        - draftId
        - claimId
        - patientId
        - environment
        - provider
        - transmissionStatus
        - accounting
        - liveSubmissionAvailable
        - status
        - jurisdiction
        - lines
        - totalChargeCents
        - paidCents
        - outstandingCents
        - pricingStatus
        - paperForm
        - ediSha256
        - pdfSha256
        - receipts
        - createdAt
        - updatedAt
      additionalProperties: false
    RfaFaxReconciliation:
      type: object
      additionalProperties: false
      required: [providerMessageId, expectedContentRevision, expectedUpdatedAt]
      properties:
        providerMessageId: { type: string, format: uuid, description: Candidate Telnyx message ID to verify with the provider. }
        expectedContentRevision: { type: integer, minimum: 1 }
        expectedUpdatedAt: { type: string, format: date-time }
    RfaFaxReconciliationEnvelope:
      type: object
      required: [data]
      properties:
        data:
          type: object
          required: [transmissionId, providerMessageId, reconciled]
          properties:
            transmissionId: { type: string }
            providerMessageId: { type: string, format: uuid }
            reconciled: { const: true }
    DentalDraftLine:
      type: object
      additionalProperties: false
      properties:
        code:
          anyOf:
          - type: string
            pattern: ^D\d{4}$
          - type: 'null'
          default: null
        description:
          anyOf:
          - type: string
            minLength: 1
            maxLength: 1000
          - type: 'null'
          default: null
        editionYear:
          anyOf:
          - type: integer
            minimum: 1900
            maximum: 2200
          - type: 'null'
          default: null
        serviceDate:
          anyOf:
          - type: string
            format: date
          - type: 'null'
          default: null
        quantity:
          type: integer
          exclusiveMinimum: 0
          maximum: 100000
          default: 1
        chargeCents:
          anyOf:
          - type: integer
            exclusiveMinimum: 0
            maximum: 1000000000
          - type: 'null'
          default: null
        chargeReference:
          anyOf:
          - type: string
            minLength: 1
            maxLength: 1000
          - type: 'null'
          default: null
        teeth:
          type: array
          items:
            type: string
            minLength: 1
            maxLength: 20
          maxItems: 32
          default: []
        surfaces:
          type: array
          items:
            type: string
            minLength: 1
            maxLength: 20
          maxItems: 10
          default: []
        oralCavity:
          anyOf:
          - type: string
            minLength: 1
            maxLength: 100
          - type: 'null'
          default: null
        prosthesisNotes:
          anyOf:
          - type: string
            minLength: 1
            maxLength: 2000
          - type: 'null'
          default: null
        prosthesis:
          oneOf:
          - type: object
            additionalProperties: false
            properties:
              placement:
                const: I
            required:
            - placement
          - type: object
            additionalProperties: false
            properties:
              placement:
                const: R
              priorPlacementDate:
                type: string
                format: date
            required:
            - placement
            - priorPlacementDate
          discriminator:
            propertyName: placement
        diagnosisPointers:
          type: array
          items:
            type: integer
            minimum: 1
            maximum: 4
          maxItems: 4
          description: Additional runtime validation applies; see Dental preparation description.
          default: []
      required: []
    NyDentalCms1500:
      type: object
      additionalProperties: false
      properties:
        narrative:
          type: object
          additionalProperties: false
          properties:
            history:
              type: string
              minLength: 1
              maxLength: 10000
            examination:
              type: string
              minLength: 1
              maxLength: 10000
            assessment:
              type: string
              minLength: 1
              maxLength: 10000
            plan:
              type: string
              minLength: 1
              maxLength: 10000
          required:
            - history
            - examination
            - assessment
            - plan
        wcbClaimNumber:
          type: string
          pattern: ^[ADF-HJ-NP-Z0-9][A-HJ-NP-Z0-9][0-9]{6}$
        providerWcbAuthorization:
          type: string
          minLength: 1
          maxLength: 10
        autoAccident:
          type: boolean
        autoAccidentState:
          type: string
          pattern: ^[A-Z]{2}$
        otherAccident:
          type: boolean
        serviceFacility:
          type: object
          additionalProperties: false
          properties:
            name:
              type: string
              minLength: 1
              maxLength: 60
            npi:
              type: string
              pattern: ^\d{10}$
            stateLicenseNumber:
              type: string
              minLength: 1
              maxLength: 15
          required:
            - name
        otherBenefitPlan:
          type: boolean
        authorizations:
          type: array
          maxItems: 100
          default: []
          items: &a1
            type: object
            additionalProperties: false
            properties:
              line:
                type: integer
                minimum: 1
                maximum: 100
              status:
                type: string
                enum:
                  - approved
                  - emergency
                  - not_required
                  - pending
              authorizationNumber:
                type: string
                minLength: 1
                maxLength: 50
              evidenceReference:
                type: string
                minLength: 1
                maxLength: 1000
              medicalNecessity:
                type: string
                minLength: 1
                maxLength: 10000
            required:
              - line
              - status
              - evidenceReference
          description: One entry per service line. Approved status requires an
            authorization number to clear review. D9999 requires medicalNecessity.
      required:
        - narrative
      description: New York dental CMS-1500 and SOAP review-packet facts. Does not
        enable live XML delivery or infer consent, certification, authorization, or
        statutory fees.
    NyDentalPaperFormReadiness:
      type: object
      additionalProperties: false
      properties:
        clinicalStatus:
          type: string
          enum:
            - complete
            - requires_completion
        missingFields:
          type: array
          items:
            type: string
        templateStatus:
          const: cms1500
        reviewStatus:
          const: requires_review
        liveUseBlocked:
          const: true
        deliveryRoute:
          const: ny_wcb_approved_xml_partner
        deliveryStatus:
          const: not_implemented
        authorizationReview:
          type: array
          items:
            type: object
            additionalProperties: false
            properties:
              line:
                type: integer
              required:
                type:
                  - boolean
                  - "null"
              status:
                type: string
                enum:
                  - unassessed
                  - approved
                  - emergency
                  - not_required
                  - pending
              reviewRequired:
                type: boolean
              evidence:
                anyOf:
                  - *a1
                  - type: "null"
            required:
              - line
              - required
              - status
              - reviewRequired
              - evidence
      required:
        - clinicalStatus
        - missingFields
        - templateStatus
        - reviewStatus
        - liveUseBlocked
        - deliveryRoute
        - deliveryStatus
        - authorizationReview
    DentalDraftContent:
      type: object
      additionalProperties: false
      properties:
        renderingProviderId:
          type: string
          minLength: 1
          maxLength: 255
        attestations:
          type: object
          additionalProperties: false
          properties:
            providerSignatureOnFile:
              type: boolean
            providerAcceptAssignment:
              type: string
              enum:
                - A
                - B
                - C
            benefitsAssignment:
              type: string
              enum:
                - Y
                - N
                - W
            releaseOfInformation:
              type: string
              enum:
                - I
                - Y
            evidenceReference:
              type: string
              minLength: 1
              maxLength: 255
              pattern: ^[\x20-\x7e]+$
              description: Additional runtime validation applies; see Dental preparation
                description.
          required:
            - providerSignatureOnFile
            - providerAcceptAssignment
            - benefitsAssignment
            - releaseOfInformation
            - evidenceReference
        authorizationNumber:
          type: string
          minLength: 1
          maxLength: 50
        orthodontics:
          type: object
          additionalProperties: false
          properties:
            appliancePlacementDate:
              type: string
              format: date
            totalMonths:
              type: integer
              exclusiveMinimum: 0
              maximum: 999
            remainingMonths:
              type: integer
              minimum: 0
              maximum: 999
          required:
            - appliancePlacementDate
            - totalMonths
            - remainingMonths
          description: Additional runtime validation applies; see Dental preparation
            description.
        missingTeeth:
          type: array
          items:
            type: string
            pattern: ^(?:[1-9]|[12]\d|3[0-2]|[A-T])$
          maxItems: 32
        billingProviderId:
          anyOf:
            - type: string
              minLength: 1
              maxLength: 255
            - type: "null"
          default: null
        diagnosisCodes:
          type: array
          items:
            type: string
            minLength: 1
            maxLength: 20
          maxItems: 12
          default: []
        notes:
          anyOf:
            - type: string
              minLength: 1
              maxLength: 5000
            - type: "null"
          default: null
        lines:
          type: array
          items:
            type: object
            additionalProperties: false
            properties:
              code:
                anyOf:
                  - type: string
                    pattern: ^D\d{4}$
                  - type: "null"
                default: null
              description:
                anyOf:
                  - type: string
                    minLength: 1
                    maxLength: 1000
                  - type: "null"
                default: null
              editionYear:
                anyOf:
                  - type: integer
                    minimum: 1900
                    maximum: 2200
                  - type: "null"
                default: null
              serviceDate:
                anyOf:
                  - type: string
                    format: date
                  - type: "null"
                default: null
              quantity:
                type: integer
                exclusiveMinimum: 0
                maximum: 100000
                default: 1
              chargeCents:
                anyOf:
                  - type: integer
                    exclusiveMinimum: 0
                    maximum: 1000000000
                  - type: "null"
                default: null
              chargeReference:
                anyOf:
                  - type: string
                    minLength: 1
                    maxLength: 1000
                  - type: "null"
                default: null
              teeth:
                type: array
                items:
                  type: string
                  minLength: 1
                  maxLength: 20
                maxItems: 32
                default: []
              surfaces:
                type: array
                items:
                  type: string
                  minLength: 1
                  maxLength: 20
                maxItems: 10
                default: []
              oralCavity:
                anyOf:
                  - type: string
                    minLength: 1
                    maxLength: 100
                  - type: "null"
                default: null
              prosthesisNotes:
                anyOf:
                  - type: string
                    minLength: 1
                    maxLength: 2000
                  - type: "null"
                default: null
              prosthesis:
                oneOf:
                  - type: object
                    additionalProperties: false
                    properties:
                      placement:
                        const: I
                    required:
                      - placement
                  - type: object
                    additionalProperties: false
                    properties:
                      placement:
                        const: R
                      priorPlacementDate:
                        type: string
                        format: date
                    required:
                      - placement
                      - priorPlacementDate
                discriminator:
                  propertyName: placement
              diagnosisPointers:
                type: array
                items:
                  type: integer
                  minimum: 1
                  maximum: 4
                maxItems: 4
                description: Additional runtime validation applies; see Dental preparation
                  description.
                default: []
            required: []
          maxItems: 100
          default: []
        adaForm:
          $ref: "#/components/schemas/DentalAdaForm"
        nyCms1500:
          $ref: "#/components/schemas/NyDentalCms1500"
      required:
        - renderingProviderId
    CreateDentalDraft:
      type: object
      additionalProperties: false
      required: [claimId, patientId, content]
      properties:
        externalId: { type: string, minLength: 1, maxLength: 255 }
        claimId: { type: string, minLength: 1, maxLength: 255 }
        patientId: { type: string, minLength: 1, maxLength: 255 }
        content: { $ref: '#/components/schemas/DentalDraftContent' }
    UpdateDentalDraft:
      type: object
      additionalProperties: false
      required: [expectedRevision, content]
      properties:
        expectedRevision: { type: integer, minimum: 1, maximum: 2000000000 }
        content: { $ref: '#/components/schemas/DentalDraftContent' }
    ArchiveDentalDraft:
      type: object
      additionalProperties: false
      required: [expectedRevision]
      properties:
        expectedRevision: { type: integer, minimum: 1, maximum: 2000000000 }
    DentalDraftReview:
      type: object
      required: [codingStatus, pricingStatus, transmissionAvailable, entrySource, knownChargeCents, totalChargeCents, issues, reviewRequirements]
      description: Completeness feedback only. A complete draft remains unverified and cannot be transmitted.
      properties:
        codingStatus: { const: unverified }
        pricingStatus: { const: unverified }
        transmissionAvailable: { const: false }
        entrySource: { const: manual }
        knownChargeCents: { type: integer, minimum: 0, description: Sum of entered extended line charges only; not a complete bill amount. }
        totalChargeCents: { type: [integer, 'null'], minimum: 1, description: Sum only when at least one line exists and every charge is known; otherwise null. Not a verified allowance. }
        issues:
          type: array
          items:
            type: object
            required: [code, path]
            properties:
              code: { type: string }
              path: { type: string }
        reviewRequirements:
          type: array
          items: { type: string, enum: [cdt_edition_and_coding_review, dental_anatomy_review, practice_charges_and_contract_review, dental_transmission_not_available] }
    DentalDraft:
      type: object
      required: [id, externalId, claimId, patientId, status, revision, content, review, createdAt, updatedAt, archivedAt]
      properties:
        id: { type: string }
        externalId: { type: [string, 'null'] }
        claimId: { type: string }
        patientId: { type: string }
        status: { type: string, enum: [draft, archived] }
        revision: { type: integer, minimum: 1 }
        content: { $ref: '#/components/schemas/DentalDraftContent' }
        review: { $ref: '#/components/schemas/DentalDraftReview' }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
        archivedAt: { type: [string, 'null'], format: date-time }
    DentalDraftEnvelope:
      type: object
      required: [data]
      properties:
        data: { $ref: '#/components/schemas/DentalDraft' }
    DentalDraftPage:
      type: object
      required: [data, nextCursor]
      properties:
        data: { type: array, items: { $ref: '#/components/schemas/DentalDraft' } }
        nextCursor: { type: [string, 'null'], description: Use as afterId with unchanged filters; null ends pagination. }
    DisputeAllowanceLine:
      type: object
      additionalProperties: false
      required: [ itemId, allowance, source, reference ]
      properties:
        itemId: { type: string, minLength: 1 }
        allowance: { type: number, minimum: 0, maximum: 99999999.99, multipleOf: 0.01 }
        source: { type: string, enum: [ published_fee_schedule, contract, other_documented_basis ] }
        reference: { type: string, minLength: 1, maxLength: 2000 }
    DisputeAllowanceAudit:
      type: object
      required: [ id, reviewedAt, reviewerId, reviewerName, lines ]
      properties:
        id: { type: string }
        reviewedAt: { type: string, format: date-time }
        reviewerId: { type: string }
        reviewerName: { type: string }
        lines: { type: array, items: { $ref: '#/components/schemas/DisputeAllowanceLine' } }
    Problem:
      type: object
      required: [ type, title, status, code ]
      properties:
        type: { type: string, format: uri, description: Stable problem type URI. }
        title: { type: string, description: Short error summary. }
        status: { type: integer, description: HTTP status. }
        code: { type: string, description: Stable machine-readable error code. }
        detail: { type: string, description: Human-readable context. }
        errors: { type: array, items: { type: object, additionalProperties: true }, description: Field-level validation details. }
        lineIndex: { type: integer, minimum: 0, maximum: 99, description: Zero-based service-line index for invalid_med_legal_context errors; omitted when no specific line is identified. }
    BillState:
      type: string
      enum: [ submission_unconfirmed, submitted, accepted, processed, rejected, denied, partially_paid, paid, second_review, lien, ibr, closed, written_off ]
    BillingMode:
      type: string
      enum: [ med_legal, professional ]
      default: med_legal
      description: Med-legal lines use fee-schedule pricing; professional treatment lines require explicit charges.
    Address:
      type: object
      additionalProperties: false
      required: [ line1, city, state, postalCode ]
      properties:
        line1: { type: string, description: Street address as printed on the claim. }
        line2: { type: string, description: Optional suite, unit, or secondary address line. }
        city: { type: string, description: City. }
        state: { type: string, pattern: '^[A-Z]{2}$', description: Two-letter state code. }
        postalCode: { type: string, description: ZIP or postal code. }
    ClaimProvisionResult:
      type: object
      additionalProperties: false
      required: [ patientId, claimId, patientExternalId, claimExternalId, created ]
      properties:
        patientId: { type: string }
        claimId: { type: string }
        patientExternalId: { type: string }
        claimExternalId: { type: string }
        created:
          type: object
          required: [ patient, claim ]
          properties: { patient: { type: boolean }, claim: { type: boolean } }
    PatientInput:
      type: object
      additionalProperties: false
      required: [ firstName, lastName, dateOfBirth, address ]
      properties:
        id: { type: string, description: Optional MindBill patient ID. Do not send with externalId. }
        externalId: { type: string, description: Your stable patient ID. Do not send with id. }
        firstName: { type: string, description: Patient first name. }
        middleName: { type: string, description: Patient middle name. }
        lastName: { type: string, description: Patient last name. }
        dateOfBirth: { type: string, format: date, description: Patient date of birth. }
        ssn: { type: string, description: SSN when required for the claim. }
        gender: { type: string, enum: [ M, F, X ], description: Claim-form gender code. }
        phone: { type: string, description: Patient phone. }
        address: { $ref: '#/components/schemas/Address' }
    ClaimsAdministrator:
      type: object
      additionalProperties: false
      required: [ id, name ]
      properties:
        id: { type: string, description: MindBill payer-directory ID. }
        name: { type: string, description: Carrier or claims-administrator name for directory matching. }
        payerId:
          type: string
          minLength: 1
          maxLength: 200
          description: Optional selected directory child key from payers[].key (for example ca3:381:325), not a clearinghouse routing ID. Must belong to this claims administrator. When reusing an existing claim, an explicit selection must match its saved payer. Returned on bill reads when a payer is selected.
    MedicalProviderNetwork:
      type: object
      required: [ id, name, applicantName, applicantType, status, approvalDate, website ]
      properties:
        id: { type: string, pattern: '^[0-9]{4}$', description: Four-character DWC MPN ID; preserve leading zeroes. }
        name: { type: string }
        applicantName: { type: string }
        applicantType: { type: string }
        status: { type: string, const: Approved }
        approvalDate: { type: [ string, 'null' ], format: date }
        website: { type: [ string, 'null' ], description: Website from the imported directory when available. }
    ClaimInput:
      type: object
      additionalProperties: false
      required: [ claimNumber, employer, dateOfInjury, claimsAdministrator ]
      properties:
        id: { type: string, description: Optional MindBill claim ID. Do not send with externalId. }
        externalId: { type: string, description: Your stable claim or injury ID. Do not send with id. }
        claimNumber: { type: string, description: Payer claim number. }
        adjNumber: { type: string, pattern: '^ADJ[0-9]{7,}$', description: California EAMS ADJ number when present. }
        medicalProviderNetworkId:
          type: [ string, 'null' ]
          pattern: '^[0-9]{4}$'
          description: |
            Optional California DWC medical provider network ID from GET /medical-provider-networks;
            preserve leading zeroes. On a new claim, omission or null means no selection.
            New selections must be Approved; an invalid or inactive new selection returns
            422 invalid_medical_provider_network. When reusing an existing claim, a supplied
            value must match the saved selection or returns 409 claim_snapshot_conflict;
            omission preserves it. Compatibility bill updates preserve an omitted field
            and clear it on explicit null. An unchanged historical inactive selection is
            retained. Returned on bill reads and retained in the submission snapshot.
        employer: { type: string, description: Employer name. }
        dateOfInjury: { type: string, format: date, description: Date of injury or cumulative-trauma end date. }
        injuryState: { type: string, pattern: '^[A-Z]{2}$', description: Two-letter injury state. }
        description: { type: string, description: Injury description. }
        claimsAdministrator: { $ref: '#/components/schemas/ClaimsAdministrator' }
    ServiceInput:
      type: object
      additionalProperties: false
      required: [ date ]
      properties:
        date: { type: string, format: date, description: Date of service frozen on the submitted bill. }
        endDate: { type: [ string, 'null' ], format: date, description: Optional service-period end date for a genuinely ranged service. }
        authorizationNumber: { type: [ string, 'null' ], description: Optional prior authorization number. }
    BillingProviderInput:
      type: object
      additionalProperties: false
      required:
      - name
      - taxId
      - npi
      - phone
      - address
      properties:
        id:
          type: string
          minLength: 1
          maxLength: 120
          description: Optional saved billing provider ID; ownership and NPI are verified.
        name:
          type: string
          description: Payee or practice name.
        taxId:
          type: string
          description: Billing tax ID.
        npi:
          type: string
          description: Billing NPI. For a solo practice this may equal the clinician NPI.
        phone:
          type: string
          description: Billing phone.
        taxonomy:
          type: string
          pattern: ^[A-Za-z0-9]{10}$
          description: Optional actual billing-provider taxonomy; omitted when unknown.
        address:
          $ref: '#/components/schemas/Address'
    RenderingProviderInput:
      type: object
      additionalProperties: false
      required: [ name, npi, taxonomy ]
      properties:
        name: { type: string, description: Rendering clinician name. }
        specialty: { type: string, description: Clinician specialty. }
        npi: { type: string, description: Individual rendering NPI. }
        taxonomy: { type: string, pattern: '^[A-Za-z0-9]{10}$', description: Ten-character rendering-provider taxonomy code sent with qualifier ZZ on California workers-comp claims. }
        licenseNumber: { type: string, description: Professional license number. }
        licenseState: { type: string, pattern: '^[A-Z]{2}$', description: Two-letter license state. }
        isQme: { type: boolean, description: Qualified Medical Evaluator flag used by med-legal fee logic. }
        isAme: { type: boolean, description: Agreed Medical Evaluator flag used by med-legal fee logic. }
    ReferringProviderInput:
      type: object
      additionalProperties: false
      required: [ name, npi ]
      properties:
        name: { type: string, description: Referring provider name for CMS-1500 box 17 and 837P loop 2310A. }
        npi: { type: string, pattern: '^[0-9]{10}$', description: Referring provider NPI. }
    ServiceLocationInput:
      type: object
      additionalProperties: false
      required: [ address, placeOfServiceCode ]
      properties:
        name: { type: string, description: Service facility name; required when facility NPI or phone is provided. }
        npi: { type: string, pattern: '^[0-9]{10}$', description: Optional service facility NPI for this address. }
        phone: { type: string, description: Optional service facility phone. }
        address: { $ref: '#/components/schemas/Address' }
        placeOfServiceCode: { type: string, pattern: '^[0-9]{2}$', description: CMS place-of-service code. }
    ClaimForm:
      type: string
      enum:
        - cms1500
        - ub04
        - ada
        - ncpdp
      default: cms1500
      description: Immutable billing form. Specialty forms require professional billingMode and an enabled
        specialty-billing organization. Inline billing providers inherit this family; saved or source
        providers must match. Paper and electronic routing use this captured form.
    BillFormData:
      type: object
      properties:
        institutional:
          type: object
          properties:
            typeOfBill:
              type: string
            statementFrom:
              type: string
            statementTo:
              type: string
            medicalRecordNumber:
              type: string
            admissionDate:
              type: string
            admissionHour:
              type: string
            admissionType:
              type: string
            admissionSource:
              type: string
            facilityMedicareId:
              type: string
            facilityLicenseNumber:
              type: string
            patientReasonForVisit:
              type: array
              items:
                type: string
            ppsCode:
              type: string
            externalCauseOfInjury:
              type: array
              items:
                type: string
            otherProviders:
              type: array
              items:
                type: object
                properties:
                  firstName:
                    type: string
                  lastName:
                    type: string
                  npi:
                    type: string
            creationDate:
              type: string
            employerDivision:
              type: string
            employerWorkAddress:
              type: string
            attachmentCodes:
              type: array
              items:
                type: string
            dischargeHour:
              type: string
            patientStatus:
              type: string
            attendingProvider:
              type: object
              properties:
                firstName:
                  type: string
                lastName:
                  type: string
                npi:
                  type: string
            operatingProvider:
              type: object
              properties:
                firstName:
                  type: string
                lastName:
                  type: string
                npi:
                  type: string
            principalDiagnosis:
              type: object
              properties:
                code:
                  type: string
                presentOnAdmission:
                  type: string
            admittingDiagnosis:
              type: string
            otherDiagnoses:
              type: array
              items:
                type: object
                properties:
                  code:
                    type: string
                  presentOnAdmission:
                    type: string
            conditionCodes:
              type: array
              items:
                type: string
            occurrenceCodes:
              type: array
              items:
                type: object
                properties:
                  code:
                    type: string
                  date:
                    type: string
            occurrenceSpans:
              type: array
              items:
                type: object
                properties:
                  code:
                    type: string
                  from:
                    type: string
                  to:
                    type: string
            valueCodes:
              type: array
              items:
                type: object
                properties:
                  code:
                    type: string
                  amount:
                    type: number
            procedures:
              type: array
              items:
                type: object
                properties:
                  code:
                    type: string
                  date:
                    type: string
                  principal:
                    type: boolean
        dental:
          type: object
          properties:
            diagnosisCodes:
              type: array
              items:
                type: string
            treatmentStartDate:
              type: string
            treatmentCompletionDate:
              type: string
            orthodontic:
              type: boolean
            appliancePlacementDate:
              type: string
            monthsOfTreatment:
              type: number
            remainingTreatmentMonths:
              type: number
            replacementProsthesis:
              type: boolean
            priorProsthesisDate:
              type: string
            missingTeeth:
              type: array
              items:
                type: string
            employerStreet:
              type: string
            employerCity:
              type: string
            employerState:
              type: string
            employerZip:
              type: string
            employerPhone:
              type: string
            providerSignatureDate:
              type: string
        pharmacy:
          type: object
          properties:
            prescriber:
              type: object
              properties:
                firstName:
                  type: string
                lastName:
                  type: string
                npi:
                  type: string
                street:
                  type: string
                city:
                  type: string
                state:
                  type: string
                zip:
                  type: string
                phone:
                  type: string
            pharmacyServiceType:
              type: string
            providerSignatureDate:
              type: string
            creationDate:
              type: string
            priorAuthorizationType:
              type: string
            otherCoverageCode:
              type: string
            paperPricing:
              type: object
              properties:
                ingredientCost:
                  type: number
                dispensingFee:
                  type: number
                otherAmount:
                  type: number
                salesTax:
                  type: number
                patientPaid:
                  type: number
                otherPayerPaid:
                  type: number
                otherPayerPatientResponsibility:
                  type: number
            paperDetails:
              type: object
              properties:
                employerPhone:
                  type: string
                employerContactName:
                  type: string
                originalManufacturerNdc:
                  type: string
                submissionClarificationCode:
                  type: string
                prescriptionOriginCode:
                  type: string
                productStrength:
                  type: string
                delayReasonCode:
                  type: string
                otherPayerId:
                  type: string
                otherPayerIdQualifier:
                  type: string
                otherPayerDate:
                  type: string
                otherPayerRejectCodes:
                  type: array
                  items:
                    type: string
                reasonForServiceCode:
                  type: string
                professionalServiceCode:
                  type: string
                resultOfServiceCode:
                  type: string
                levelOfEffort:
                  type: string
            employerStreet:
              type: string
            employerCity:
              type: string
            employerState:
              type: string
            employerZip:
              type: string
      description: "Claim fields for the selected form only: institutional for ub04, dental for ada,
        pharmacy for ncpdp. Dates use YYYY-MM-DD. Required clinical and claim fields are validated
        before persistence and transmission. Omitted formData on an update preserves saved fields."
    BillItemFormData:
      type: object
      properties:
        institutional:
          type: object
          properties:
            dawCode:
              type: string
            revenueCode:
              type: string
            unitCode:
              type: string
            nonCoveredCharge:
              type: number
        dental:
          type: object
          properties:
            diagnosisCodes:
              type: array
              items:
                type: string
            oralCavity:
              type: string
            toothNumber:
              type: string
            toothSurfaces:
              type: array
              items:
                type: string
            prosthesis:
              type: string
        pharmacy:
          type: object
          properties:
            prescriptionNumber:
              type: string
            fillNumber:
              type: number
            daysSupply:
              type: number
            fillsRemaining:
              type: number
            dispensedDate:
              type: string
            writtenDate:
              type: string
            dawCode:
              type: string
            compoundCode:
              type: string
            usualAndCustomaryCharge:
              type: number
            basisOfCostDetermination:
              type: string
            compound:
              type: object
              properties:
                name:
                  type: string
                dosageFormCode:
                  type: string
                dispensingUnitCode:
                  type: string
                routeOfAdministration:
                  type: string
                metricQuantity:
                  type: string
                unitOfMeasure:
                  type: string
                ingredients:
                  type: array
                  items:
                    type: object
                    properties:
                      name:
                        type: string
                      ndcNumber:
                        type: string
                      metricQuantity:
                        type: string
                      ingredientCost:
                        type: string
                      basisOfCostDetermination:
                        type: string
      description: Service-line fields for the selected form only. Omitted formData on an update preserves
        saved fields for the matching line ID. Compound quantities and costs are decimal strings with up
        to three fractional digits.
    MedLegalContext:
      type: object
      additionalProperties: false
      description: |
        Optional medical-legal calculation facts. Allowed only with med_legal billingMode.
        Supply {} to opt into ML201 date-aware pricing. ML200 requires missedAppointmentEligibility. Code, modifiers, units,
        charge and serviceDate belong on the service line, never inside this object.
        ML202 requires followUpEligibility; ML203 requires supplementalRequestDate and
        supplementalEligibility. Unknown eligibility facts require review, never an assumed allowance.
        ML205 and MLPRR require associatedReportCode
        and associatedReportDate; the associated report need not appear on the same bill.
        MLPRR also requires the associated ML200/ML202/ML203 eligibility facts above.
        MLPRR with ML200 requires recordReviewReportDate within 30 days after the missed appointment.
        ML205 does not inherit the associated report eligibility checks.
        ML204/ML205 require minutes and usualHourlyCharge; ML204 also requires testimonyKind.
        Only a positive calculated allowance with matching line units can be saved.
        Dates before April 1, 2021 and unresolved rules require review, not current rates.
        Service eligibility and record declarations are not fully audited by this calculation.
      properties:
        supplementalRequestDate:
          type: string
          format: date
          description: ML203 supplemental-report request date; selects the schedule instead of the original examination date.
        missedAppointmentEligibility:
          type: object
          additionalProperties: false
          description: ML200 eligibility under 8 CCR 9795. Unknown facts require review. Cancellations require review of the six-business-day notice rule and exceptions; they are not automatically priced.
          properties:
            appointmentKind:
              type: string
              enum: [ comprehensive, follow_up, other, unknown ]
              description: Scheduled examination type; only comprehensive or follow-up evaluations qualify.
            missedReason:
              type: string
              enum: [ worker_absent, interpreter_absent, worker_left, worker_late, canceled, other, unknown ]
            workerDepartureCircumstance:
              type: string
              enum: [ unprotected_worker_departure, not_seen_within_one_hour, good_cause_termination, disputed_termination, physician_terminated, unknown ]
              description: Required for worker_left. Only unprotected_worker_departure can calculate. A worker termination under the one-hour waiting protection or established good cause excludes payment under 8 CCR 41(f)-(g). Unknown, disputed, or physician-terminated circumstances require review under 41(f)-(i).
            minutesLate:
              type: number
              minimum: 0
              description: Required for worker_late; arrival must be more than 30 minutes late.
            unableToProceed:
              type: boolean
              description: Required for worker_late or interpreter_absent; the physician must be unable to proceed with the examination.
        followUpEligibility:
          type: object
          additionalProperties: false
          description: ML202 eligibility under 8 CCR 9793(g) and 9795. Missing facts require review. The interval runs from the comprehensive examination, never an intervening follow-up.
          properties:
            priorEvaluationKind:
              type: string
              enum: [ comprehensive, follow_up, supplemental, unknown ]
              description: Type of prior evaluation used as the interval anchor; only comprehensive qualifies.
            priorComprehensiveExamDate:
              type: string
              format: date
              description: Prior comprehensive examination date, which may predate April 2021. The current follow-up must be within 18 calendar months.
            samePhysician:
              type: boolean
              description: Whether the same individual physician performed the prior comprehensive evaluation; the same group alone is insufficient.
            sameInjuries:
              type: boolean
              description: Whether the follow-up concerns the same injuries as the comprehensive evaluation.
        supplementalEligibility:
          type: object
          additionalProperties: false
          description: ML203 eligibility under 8 CCR 9793(m) and 9795. Missing facts require review. An ineligible supplemental report does not produce a payable allowance.
          properties:
            priorComprehensiveCompleted:
              type: boolean
              description: Whether the evaluator previously completed a comprehensive medical-legal report.
            samePhysician:
              type: boolean
              description: Whether this is the same physician who performed the comprehensive evaluation.
            patientExamined:
              type: boolean
              description: Whether the patient was examined for this report; a supplemental report excludes an examination.
            basis:
              type: string
              enum: [ new_information, factual_correction_4061d, unknown ]
              description: New medical information or a factual correction under Labor Code 4061(d).
            informationPreviouslyAvailable:
              type: boolean
              description: Whether the information was already available in the physician office or provided for an earlier report.
            issuePreviouslyRequested:
              type: boolean
              description: Whether the report addresses an issue previously requested in an earlier report.
            subRosaReceivedBeforePendingReport:
              type: boolean
              description: Whether this supplemental report concerns sub rosa recordings received before a pending report was issued; no separate supplemental fee is payable for those recordings.
        associatedReportCode:
          type: string
          enum: [ ML200, ML201, ML202, ML203 ]
          description: Associated report type for ML205 or MLPRR. ML205 associated only with ML200 requires review.
        associatedReportDate:
          type: string
          format: date
          description: Associated examination, missed-appointment or supplemental-request date selecting the ML205 or MLPRR schedule.
        recordReviewReportDate:
          type: string
          format: date
          description: Required for MLPRR associated with ML200. Actual report production date, on or within 30 calendar days after the missed appointment; never inferred from the invoice or service date.
        excessPages:
          type: integer
          minimum: 0
          maximum: 1000000
          description: MLPRR already-eligible excess pages after included pages and exclusions. Must equal line units and yield a positive allowance; this field does not audit records or declarations.
        minutes:
          type: number
          minimum: 0
          maximum: 60000
          description: Itemized ML204 or ML205 time in minutes, rounded to the nearest quarter hour before applicable minimums. Line units are quarter hours; deposition minimum is 8 units.
        usualHourlyCharge:
          type: number
          exclusiveMinimum: 0
          maximum: 1000000
          multipleOf: 0.01
          description: Physician usual hourly charge in dollars and cents, required for saved ML204/ML205 calculations. The lower of this rate and the statutory hourly ceiling determines the allowance.
        testimonyKind:
          type: string
          enum: [ testimony, deposition, canceled_deposition ]
          description: Required for ML204. Deposition has an 8-unit minimum; a qualifying canceled deposition has a 4-unit minimum.
        cancellationDate:
          type: string
          format: date
          description: Required for canceled_deposition. Cancellation fewer than eight calendar days before the scheduled deposition can qualify; other cancellations require review.
    ServiceLinePricing:
      type: object
      required: [ status, basis, expectedAmount, scheduleMaximumAmount, statutoryMaximumAmount, reimbursementBasis, provenance, notes, warnings ]
      description: Server-calculated reimbursement evidence, separately from the billed charge. A calculated result establishes arithmetic from supplied facts, not every service eligibility requirement. Legacy lines without context are not retroactively repriced.
      properties:
        status:
          type: string
          enum: [ calculated, manual_charge, requires_review ]
          description: Whether an allowance is calculated, manually charged or requires correction/review.
        basis: { type: string, description: Calculation basis such as med_legal_schedule or a California treatment schedule. }
        expectedAmount: { type: [ number, 'null' ], description: Calculated allowance in dollars; null when unverified. }
        scheduleMaximumAmount: { type: [ number, 'null' ], description: Applicable schedule ceiling in dollars before a billed-charge cap; contextual ML204/ML205 retain the statutory hourly ceiling separately from a lower usual charge. }
        statutoryMaximumAmount: { type: [ number, 'null' ], description: Statutory maximum in dollars, separately preserved when a payer contract applies. }
        reimbursementBasis:
          type: [ string, 'null' ]
          enum: [ statutory_schedule, payer_contract, null ]
          description: Statutory or contract basis, or null when unverified.
        provenance:
          type: array
          description: Effective-dated treatment source references; medical-legal regulation links are in citations.
          items:
            type: object
            required: [ id, url, effectiveFrom, effectiveThrough ]
            properties:
              id: { type: string, description: Source identifier. }
              url: { type: string, format: uri, description: Source URL. }
              sha256: { type: string, description: Optional source content digest. }
              effectiveFrom: { type: string, format: date, description: First applicable service date. }
              effectiveThrough: { type: string, format: date, description: Last applicable service date. }
        notes: { type: array, items: { type: string }, description: Calculation explanations and limitations. }
        citations:
          type: array
          description: Links to authority for the calculation.
          items:
            type: object
            required: [ label, url ]
            properties:
              label: { type: string, description: Authority title. }
              url: { type: string, format: uri, description: Authority URL. }
        breakdown:
          type: object
          description: Server-provided display text; do not use these strings to price a bill.
          required: [ method, inputs, steps, notes ]
          properties:
            method: { type: string, description: Calculation method. }
            inputs:
              type: array
              description: Inputs used for the calculation, including the controlling date where applicable.
              items: { $ref: '#/components/schemas/PricingDisplayValue' }
            steps:
              type: array
              description: Calculation steps in display order.
              items: { $ref: '#/components/schemas/PricingDisplayValue' }
            notes: { type: array, items: { type: string }, description: Explanations accompanying the breakdown. }
        warnings:
          type: array
          description: Structured issues requiring attention; an above-maximum charge is not silently changed.
          items:
            type: object
            required: [ code, message ]
            properties:
              code:
                type: string
                enum: [ fee_context_required, saved_fee_quote_mismatch, charge_exceeds_schedule_maximum, invalid_med_legal_modifiers ]
                description: Stable warning code.
              message: { type: string, description: Human-readable correction or warning. }
    PricingDisplayValue:
      type: object
      required: [ label, value ]
      properties:
        label: { type: string, description: Display label. }
        value: { type: string, description: Formatted display value. }
    ServiceLineInput:
      type: object
      additionalProperties: false
      required:
      - code
      properties:
        id:
          type: string
          description: Existing line ID when editing.
        code:
          type: string
          description: Procedure code such as ML201 or D0120. Send an empty string for an institutional revenue-only line or a pharmacy line without a procedure code.
        drug:
          $ref: '#/components/schemas/BilledDrug'
        formData:
          $ref: '#/components/schemas/BillItemFormData'
        feeContext:
          $ref: '#/components/schemas/ServiceLineFeeContext'
        medLegalContext:
          $ref: '#/components/schemas/MedLegalContext'
        modifiers:
          type: array
          maxItems: 8
          items:
            type: string
            maxLength: 4
          default: []
          description: Procedure modifiers without hyphens.
        units:
          type: number
          exclusiveMinimum: 0
          maximum: 10000
          default: 1
          description: Billable units. CMS-1500 requires whole units; specialty forms allow fractional quantities up to 9999. Contextual ML204/ML205 units are quarter hours after rounding and minimums, MLPRR units are eligible excess pages, and ML200–ML203 use one unit. Units must match the contextual calculation.
        charge:
          type: number
          minimum: 0
          description: Extended total billed charge in dollars, not a per-unit rate. Required for professional treatment bills. For contextual medical-legal lines an omitted charge defaults to the calculated allowance; an explicit charge is preserved separately from that allowance.
        serviceDate:
          type: string
          format: date
          description: Line date of service; defaults to service.date. For contextual ML200–ML202 and ML204 this is the scheduled appointment, examination or testimony date. ML203, ML205 and MLPRR select the schedule using their context dates.
        serviceDateEnd:
          type: string
          format: date
          description: Optional inclusive end date; must be on or after serviceDate. A contextual medical-legal line must have a single service date, so its end date must be omitted or equal the effective service date.
        diagnosisPointers:
          type: array
          maxItems: 4
          uniqueItems: true
          items:
            type: integer
            minimum: 1
            maximum: 12
          description: Up to four distinct one-based indices into the bill diagnoses array. Professional claims with multiple
            diagnoses require explicit pointers on every service line; a single diagnosis is selected automatically when pointers
            are omitted.
        rfaItemId:
          type: string
          description: Optional approved or modified California workers-comp RFA item for this treatment line.
    BillCreate:
      type: object
      additionalProperties: false
      required: [ patient, claim, service, billingProvider, renderingProvider, serviceLocation, diagnoses, serviceLines ]
      properties:
        externalId: { type: string, description: Your stable bill or work-item ID. }
        billingMode: { $ref: '#/components/schemas/BillingMode' }
        claimForm: { $ref: '#/components/schemas/ClaimForm' }
        formData: { $ref: '#/components/schemas/BillFormData' }
        patient: { $ref: '#/components/schemas/PatientInput' }
        claim: { $ref: '#/components/schemas/ClaimInput' }
        service: { $ref: '#/components/schemas/ServiceInput' }
        billingProvider: { $ref: '#/components/schemas/BillingProviderInput' }
        renderingProvider: { $ref: '#/components/schemas/RenderingProviderInput' }
        referringProvider: { $ref: '#/components/schemas/ReferringProviderInput' }
        serviceLocation: { $ref: '#/components/schemas/ServiceLocationInput' }
        diagnoses: { type: array, minItems: 1, maxItems: 50, items: { type: string }, description: ICD-10 diagnosis codes frozen on submission. CMS-1500 claims require one to twelve nonblank codes; their service line pointers must reference this exact order. }
        serviceLines: { type: array, minItems: 1, maxItems: 50, items: { $ref: '#/components/schemas/ServiceLineInput' }, description: Complete service lines frozen on submission. }
    SubmissionDestination:
      type: object
      additionalProperties: false
      properties:
        faxNumber: { type: string }
        email: { type: string, format: email }
        mailingAddress: { type: string }
    SubmissionInput:
      type: object
      additionalProperties: false
      properties:
        route: { $ref: '#/components/schemas/DeliveryRoute' }
        destination: { $ref: '#/components/schemas/SubmissionDestination' }
        attention: { type: string }
        subject: { type: string }
        note: { type: string }
    SubmissionDocumentInput:
      type: object
      additionalProperties: false
      required: [ filename, documentType, contentBase64 ]
      properties:
        externalId: { type: string, description: Your stable document ID. }
        filename: { type: string, description: PDF filename. }
        description: { type: string, description: Optional user-facing label. }
        documentType: { $ref: '#/components/schemas/DocumentType' }
        reportTypeCode: { type: string, maxLength: 16, description: Optional PWK01 report-type code. Med-legal submissions default to OZ:J4; professional submissions default to OZ when omitted. }
        contentBase64: { type: string, contentEncoding: base64, contentMediaType: application/pdf, description: Base64 PDF bytes, up to 25 MB decoded. }
    BillSubmissionCreate:
      type: object
      additionalProperties: false
      required: [ bill ]
      properties:
        customerExternalId: { type: string, minLength: 1, maxLength: 255, description: "Host-owned customer ID for server submissions. Customer browser sessions stamp this automatically and reject a different supplied value." }
        bill: { $ref: '#/components/schemas/BillCreate' }
        submission: { $ref: '#/components/schemas/SubmissionInput' }
        documents:
          type: array
          maxItems: 25
          default: []
          items: { $ref: '#/components/schemas/SubmissionDocumentInput' }
          description: Explicit payer-packet PDFs frozen with this bill. Customer-scoped submissions must include their own w9 document; a workspace W-9 is never substituted. Medical records are never attached unless you include them. This payer billing packet is separate from any attorney report-service packet.
    Patient:
      allOf:
        - $ref: '#/components/schemas/PatientInput'
    Claim:
      allOf:
        - $ref: '#/components/schemas/ClaimInput'
        - type: object
          properties:
            diagnoses: { type: array, items: { type: string }, description: ICD-10 codes frozen on this bill. }
    BillingProvider:
      type: [ object, 'null' ]
      additionalProperties: false
      required: [ name, taxId, npi, phone, address ]
      properties:
        name: { type: string }
        taxId: { type: string }
        npi: { type: string }
        phone: { type: string }
        taxonomy: { type: [ string, 'null' ] }
        address: { $ref: '#/components/schemas/Address' }
    RenderingProvider:
      type: [ object, 'null' ]
      additionalProperties: false
      required: [ name, npi, taxonomy ]
      properties:
        name: { type: string }
        specialty: { type: string }
        npi: { type: string }
        taxonomy: { type: string }
        licenseNumber: { type: string }
        licenseState: { type: string }
        isQme: { type: boolean }
        isAme: { type: boolean }
    ReferringProvider:
      type: [ object, 'null' ]
      additionalProperties: false
      required: [ name, npi ]
      properties:
        name: { type: string }
        npi: { type: string }
    ServiceLocation:
      type: [ object, 'null' ]
      additionalProperties: false
      required: [ address, placeOfServiceCode ]
      properties:
        name: { type: string }
        npi: { type: [ string, 'null' ] }
        phone: { type: [ string, 'null' ] }
        address: { $ref: '#/components/schemas/Address' }
        placeOfServiceCode: { type: string }
    ServiceLine:
      type: object
      required: [ id, code, modifiers, units, charge, feeSchedule ]
      properties:
        id: { type: string }
        code: { type: string }
        modifiers: { type: array, items: { type: string } }
        units: { type: number }
        drug: { $ref: '#/components/schemas/BilledDrug' }
        formData: { $ref: '#/components/schemas/BillItemFormData' }
        medLegalContext: { $ref: '#/components/schemas/MedLegalContext' }
        pricing: { $ref: '#/components/schemas/ServiceLinePricing' }
        charge: { type: number, description: Current line charge in dollars. }
        feeSchedule: { type: number, description: Saved fee-schedule field in dollars. Contextual medical-legal lines contain the calculated allowance; legacy manual treatment lines may contain a charge. Use pricing.status and pricing.expectedAmount to identify verified reimbursement. }
        serviceDate: { type: [ string, 'null' ], format: date }
        serviceDateEnd: { type: [ string, 'null' ], format: date }
        diagnosisPointers: { type: array, items: { type: integer } }
        rfaItemId: { type: [ string, 'null' ] }
    DocumentType:
      type: string
      enum: [ final_report, letter_of_attestation, proof_of_service, form_122, return_to_work_voucher, w9, medical_records, appeal, other ]
    Document:
      type: object
      required: [ id, filename, documentType, source, addedAt, contentUrl ]
      properties:
        id: { type: string }
        externalId: { type: [ string, 'null' ] }
        filename: { type: string }
        description: { type: [ string, 'null' ] }
        documentType: { $ref: '#/components/schemas/DocumentType' }
        reportType: { type: [ string, 'null' ] }
        reportTypeCode: { type: [ string, 'null' ] }
        source: { type: string }
        addedAt: { type: string, format: date-time }
        contentUrl: { type: string, format: uri }
    DocumentEnvelope:
      type: object
      required: [ data ]
      properties:
        data: { $ref: '#/components/schemas/Document' }
    Amounts:
      type: object
      required: [ charged, paid, balance ]
      properties:
        charged: { type: number, description: Total charged in dollars. }
        paid: { type: number, description: Total posted payments in dollars. }
        balance: { type: number, description: Current balance in dollars. }
    BillTiming:
      type: object
      required: [ submittedAt, agingDays, updatedAt ]
      properties:
        submittedAt: { type: [ string, 'null' ], format: date-time }
        agingDays: { type: [ integer, 'null' ], minimum: 0 }
        updatedAt: { type: [ string, 'null' ], format: date-time }
    SubmissionReconciliationProblem:
      allOf:
        - $ref: '#/components/schemas/Problem'
        - type: object
          required: [ billId, reconciliationRequired ]
          properties:
            billId: { type: string }
            reconciliationRequired: { type: boolean, const: true }
    Bill:
      type: object
      required: [ id, state, billingMode, patient, claim, service, billingProvider, renderingProvider, serviceLocation, serviceLines, documents, amounts, timing ]
      properties:
        id: { type: string, description: Stable MindBill bill ID. }
        customerExternalId: { type: [ string, 'null' ], description: Immutable host customer ownership. Null means legacy or unassigned; customer-scoped sessions cannot access those bills. }
        externalId: { type: [ string, 'null' ], description: Your stable bill or work-item ID. }
        reconciliationRequired: { type: boolean, description: True when retained transmission evidence needs reconciliation before any further submission. }
        state: { $ref: '#/components/schemas/BillState' }
        billingMode: { $ref: '#/components/schemas/BillingMode' }
        claimForm: { $ref: '#/components/schemas/ClaimForm' }
        formData: { $ref: '#/components/schemas/BillFormData' }
        billNumber: { type: [ integer, 'null' ] }
        claimEdits:
          type: object
          description: Live public California practitioner PTP/MUE screening for this bill. A saved bill never attests complete same-day services. Findings require review and do not modify stored charges or allowances. Historical submission snapshots do not get a new live screen.
          properties:
            status: { type: string, enum: [evaluated, requires_review, source_unavailable, not_applicable] }
            scope: { type: string, enum: [submitted_practitioner_lines, saved_bill_lines] }
            completeDateOfServiceContext: { type: boolean }
            reason: { type: string }
            findings: { type: array, items: { type: object } }
            limitations: { type: array, items: { type: string } }
            provenance: { type: object }
            supportedDateRange: { type: object }
        patient: { $ref: '#/components/schemas/Patient' }
        claim: { $ref: '#/components/schemas/Claim' }
        service: { $ref: '#/components/schemas/ServiceInput' }
        billingProvider: { $ref: '#/components/schemas/BillingProvider' }
        renderingProvider: { $ref: '#/components/schemas/RenderingProvider' }
        referringProvider: { $ref: '#/components/schemas/ReferringProvider' }
        serviceLocation: { $ref: '#/components/schemas/ServiceLocation' }
        serviceLines: { type: array, items: { $ref: '#/components/schemas/ServiceLine' } }
        documents: { type: array, items: { $ref: '#/components/schemas/Document' } }
        amounts: { $ref: '#/components/schemas/Amounts' }
        timing: { $ref: '#/components/schemas/BillTiming' }
        attempts:
          type: array
          description: Immutable delivery attempts in this logical bill chain, oldest first. Every successful transmission, including Second Review, is a separate row even when it reuses the same bill record. The top-level bill id remains the stable root id across corrections.
          items: { $ref: '#/components/schemas/BillAttempt' }
        history:
          type: array
          description: One chronological, partner-safe timeline spanning every submission attempt in the logical bill chain.
          items: { $ref: '#/components/schemas/BillHistoryEntry' }
    BillAttempt:
      type: object
      required: [ id, label, isCurrent ]
      properties:
        id: { type: string, description: Immutable MindBill bill-record id for this correction-chain member. It can repeat when one record has multiple transmissions. }
        submissionId: { type: string, description: Immutable transmission id. Absent only for an unsent draft attempt. }
        billNumber: { type: integer }
        label: { type: string, description: "Display label such as Original Bill, Corrected Bill (-1), or Second Review." }
        deliveryLabel: { type: string, description: Delivery route used by this transmission. }
        sentAt: { type: string, format: date-time }
        ackLabel: { type: string, description: "Latest payer or clearinghouse acknowledgement, such as 277 Reject." }
        ackAt: { type: string, format: date-time }
        complianceLabel: { type: string, description: Human-readable payment or compliance deadline label for this transmission. }
        complianceAt: { type: string, format: date-time }
        status: { type: string, description: Native status of the bill record that owns this transmission. }
        isCurrent: { type: boolean, description: Whether this is the latest transmission or draft on the current writable bill record. Exactly one row is current. }
    BillHistoryDetails:
      type: object
      properties:
        rows:
          type: array
          items:
            type: object
            required: [ label, value ]
            properties:
              label: { type: string }
              value: { type: string }
        documents:
          type: array
          items:
            type: object
            required: [ id, filename ]
            properties:
              id: { type: string }
              filename: { type: string }
        complianceDueDates:
          type: array
          items:
            type: object
            required: [ date, text ]
            properties:
              date: { type: string, format: date-time }
              text: { type: string }
        codes:
          type: array
          items:
            type: object
            required: [ code, text ]
            properties:
              code: { type: string }
              text: { type: string }
        text: { type: string }
    BillHistoryEntry:
      type: object
      required: [ id, attemptId, date, action, kind, actor, summary, tone ]
      properties:
        id: { type: string, description: Stable event id unique within the combined logical-bill timeline. }
        attemptId: { type: string, description: Immutable bill-record id for the correction-chain member that produced this event. }
        date: { type: string, format: date-time }
        action: { type: string, description: Short display action such as Original Bill, 277 Reject, Payment, or Note. }
        kind: { type: string, enum: [ created, submission, ack, eor, payment, review, close, reopen, note, portal, task, system ] }
        actor: { type: [ string, 'null' ] }
        summary: { type: string }
        tone: { type: string, enum: [ submission, note, neutral, problem, success ] }
        amount: { type: number }
        internal: { type: boolean }
        details: { $ref: '#/components/schemas/BillHistoryDetails' }
    BillPage:
      type: object
      required: [ data ]
      properties:
        data: { type: array, items: { $ref: '#/components/schemas/Bill' } }
        nextCursor: { type: [ string, 'null' ] }
    DeliveryRoute:
      type: string
      enum: [ ebill, fax, mail, email ]
      default: ebill
    SubmissionResult:
      type: object
      required: [ ok, sandbox, livemode, billId, controlNumber, state, status ]
      properties:
        ok: { const: true }
        sandbox: { const: true }
        livemode: { const: false }
        billId: { type: string }
        controlNumber: { type: string }
        state: { const: submitted }
        status: { const: submitted }
    BillStatus:
      type: object
      required: [ billId, state, totalCharge, totalPaid, balanceDue, submittedAt, agingDays, updatedAt ]
      properties:
        billId: { type: string }
        externalId: { type: [ string, 'null' ] }
        state: { $ref: '#/components/schemas/BillState' }
        nativeStatus: { type: [ string, 'null' ] }
        totalCharge: { type: number }
        totalPaid: { type: number }
        balanceDue: { type: number }
        lastEventId: { type: [ string, 'null' ] }
        submittedAt: { type: [ string, 'null' ], format: date-time }
        agingDays: { type: [ integer, 'null' ], minimum: 0 }
        updatedAt: { type: [ string, 'null' ], format: date-time }
    BillLifecycle:
      type: object
      required: [ state, actions ]
      properties:
        state: { $ref: '#/components/schemas/BillState' }
        nativeStatus: { type: [ string, 'null' ], description: Internal source status retained for diagnostics. Prefer state in partner UI. }
        submittedAt: { type: [ string, 'null' ], format: date-time }
        agingDays: { type: [ integer, 'null' ], minimum: 0 }
        updatedAt: { type: [ string, 'null' ], format: date-time }
        actions:
          type: array
          description: State-appropriate actions suitable for an action sheet.
          items:
            type: object
            required: [ id, label ]
            properties:
              id: { type: string, enum: [ second_review, independent_bill_review, view_eor, post_payment, close, reopen ] }
              label: { type: string }
              description: { type: string }
              tone: { type: string, enum: [ default, primary, destructive ] }
    BillActivity:
      type: object
      required: [ id, type, createdAt, title, description ]
      properties:
        id: { type: string }
        type: { type: string, description: Stable machine-readable event type. }
        createdAt: { type: string, format: date-time }
        title: { type: string, description: Plain-language event title for end users. }
        description: { type: string, description: Plain-language supporting detail. }
        actor: { type: [ string, 'null' ] }
        delivery: { type: [ object, 'null' ], additionalProperties: true }
        amount: { type: [ number, 'null' ] }
        accepted: { type: [ boolean, 'null' ] }
        stcCategory: { type: [ string, 'null' ] }
    BillPayment:
      type: object
      required: [ id, amount, method, source, postedAt ]
      additionalProperties: true
      properties:
        id: { type: string }
        amount: { type: number }
        method: { type: string }
        source: { type: string }
        postedAt: { type: string, format: date-time }
    BillLifecycleEnvelope:
      type: object
      required: [ data ]
      properties:
        data:
          type: object
          required: [ environment, bill, patient, injury, lifecycle, eors, attempts, history, activity, payments, remittance, delivery ]
          properties:
            environment: { type: string, enum: [ sandbox, live ], description: Credential environment used to load this lifecycle. }
            bill: { type: object, additionalProperties: true, description: The same immutable submitted bill snapshot returned by the bill-review surface. }
            patient: { type: object, additionalProperties: true }
            injury:
              type: object
              additionalProperties: true
              properties:
                medicalProviderNetworkId:
                  type: [ string, 'null' ]
                  pattern: '^[0-9]{4}$'
                  description: Optional saved MPN ID, including historical inactive selections; null when no network was selected.
            options: { type: object, additionalProperties: true, description: Display metadata retained for compatible embedded components. }
            lifecycle: { $ref: '#/components/schemas/BillLifecycle' }
            eors: { type: array, items: { type: object, additionalProperties: true } }
            attempts:
              type: array
              description: Immutable delivery attempts in the logical bill chain, oldest first. Every successful transmission, including Second Review, is a separate row even when it reuses the same bill record.
              items: { $ref: '#/components/schemas/BillAttempt' }
            history:
              type: array
              description: One chronological timeline spanning every delivery attempt. Each row identifies its correction-chain member bill record via attemptId.
              items: { $ref: '#/components/schemas/BillHistoryEntry' }
            activity: { type: array, items: { $ref: '#/components/schemas/BillActivity' } }
            payments: { type: array, items: { $ref: '#/components/schemas/BillPayment' } }
            remittance:
              type: object
              required: [ payerReportedPaid, totalPaid, balanceDue, denialReason, expectedAmount, balanceBasis, payerAllowedAmount ]
              properties:
                expectedAmount:
                  type: [ number, 'null' ]
                  description: Verified schedule amount, or null when only an entered treatment charge is available. An entered charge does not establish reimbursement entitlement.
                balanceBasis: { type: string, enum: [ manual_charge, med_legal_schedule ] }
                payerAllowedAmount:
                  type: [ number, 'null' ]
                  description: Actual payer allowance summed only when present for every service line. Unknown is null; a reported zero remains zero.
                payerReportedPaid: { type: [ number, 'null' ] }
                totalPaid: { type: number }
                balanceDue: { type: number }
                denialReason: { type: [ string, 'null' ] }
            delivery:
              type: object
              required: [ payerName, contacts ]
              properties:
                payerName: { type: string }
                contacts: { type: object, additionalProperties: true }
    CloseAction:
      type: object
      additionalProperties: false
      required: [ action, reason ]
      properties:
        action: { const: close }
        reason: { type: string, minLength: 1 }
    PostPaymentAction:
      type: object
      additionalProperties: false
      required: [ action, amount, method, depositDate ]
      properties:
        action: { const: post_payment }
        amount: { type: number, exclusiveMinimum: 0, description: Payment amount in dollars. }
        method: { type: string, enum: [ check, eft ] }
        checkNumber: { type: string, default: '' }
        depositDate: { type: string, format: date }
        note: { type: string }
    SecondReviewAction:
      type: object
      additionalProperties: false
      required: [ action, reason, payerClaimControlNumber ]
      properties:
        action: { const: second_review }
        reason: { type: string, minLength: 1 }
        payerClaimControlNumber: { type: string, minLength: 1 }
        disputedAmount: { type: number, minimum: 0 }
        attachmentIds: { type: array, items: { type: string }, default: [] }
        route: { $ref: '#/components/schemas/DeliveryRoute' }
    ReopenAction:
      type: object
      additionalProperties: false
      required: [ action, reason ]
      properties:
        action: { const: reopen }
        reason: { type: string, minLength: 1, description: Plain-language reason recorded in bill history. }
    ResubmitAction:
      type: object
      additionalProperties: false
      required: [ action, bill ]
      properties:
        action: { const: resubmit }
        reason: { type: string, description: Optional plain-language correction note recorded in bill history. }
        bill:
          allOf:
            - $ref: '#/components/schemas/BillCreate'
          description: Complete corrected bill snapshot. The prior submission remains immutable and this creates the next submission attempt under the same public bill resource.
        documents:
          type: array
          maxItems: 25
          default: []
          items: { $ref: '#/components/schemas/SubmissionDocumentInput' }
          description: Complete PDF packet for the corrected submission. Existing documents must be downloaded and included again when they should accompany the new attempt.
    SandboxSimulationInput:
      type: object
      additionalProperties: false
      required: [ scenario ]
      properties:
        scenario: { type: string, enum: [ accepted, processed, rejected, denied, partial_payment, paid ], description: Deterministic synthetic response to apply. }
        amount: { type: number, exclusiveMinimum: 0, description: Optional payer-reported amount used by partial-payment scenarios. }
        reasonCode: { type: string, description: Optional synthetic adjustment or rejection reason code. }
    SandboxSimulationEnvelope:
      type: object
      required: [ data ]
      properties:
        data: { type: object, additionalProperties: true, description: Synthetic simulation result and updated bill state. }
    BillReviewCreate:
      type: object
      additionalProperties: false
      required: [ type, reason ]
      properties:
        type: { type: string, enum: [ second_review, independent_bill_review ] }
        externalId: { type: string, description: Your stable review ID. }
        reason: { type: string, minLength: 1 }
        disputedAmount: { type: number, minimum: 0 }
        payerClaimControlNumber: { type: string }
        attachmentIds: { type: array, items: { type: string }, default: [] }
    BillReview:
      type: object
      required: [ id, billId, originalBillId, type, state, reason, attachmentIds, createdAt, updatedAt ]
      properties:
        id: { type: string }
        billId: { type: string }
        originalBillId: { type: string }
        externalId: { type: [ string, 'null' ] }
        type: { type: string, enum: [ second_review, independent_bill_review ] }
        state: { type: string, enum: [ draft, submitted ] }
        reason: { type: string }
        disputedAmount: { type: [ number, 'null' ] }
        payerClaimControlNumber: { type: [ string, 'null' ] }
        attachmentIds: { type: array, items: { type: string } }
        submittedAt: { type: [ string, 'null' ], format: date-time }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
    BillReviewEnvelope:
      type: object
      required: [ data ]
      properties:
        data: { $ref: '#/components/schemas/BillReview' }
    EorEnvelope:
      type: object
      required: [ data ]
      properties:
        data:
          type: object
          required: [ billId, reportedPaid, totalPaid, balanceDue, payments, lineItems, documents ]
          properties:
            billId: { type: string }
            reportedPaid: { type: number }
            totalPaid: { type: number }
            balanceDue: { type: number }
            payment: { type: [ object, 'null' ], additionalProperties: true }
            payments: { type: array, items: { type: object, additionalProperties: true } }
            lineItems:
              type: array
              items:
                type: object
                required: [ id, code, paid, allowedAmount, adjustmentAmount, patientResponsibility, reasonCodes ]
                properties:
                  id: { type: string }
                  code: { type: string }
                  paid: { type: number }
                  allowedAmount: { type: number }
                  adjustmentAmount: { type: number }
                  patientResponsibility: { type: number }
                  reasonCodes: { type: array, items: { type: string } }
            documents:
              type: array
              items:
                type: object
                required: [ id, filename, addedAt, contentUrl ]
                properties:
                  id: { type: string }
                  filename: { type: string }
                  description: { type: [ string, 'null' ] }
                  addedAt: { type: string, format: date-time }
                  contentUrl: { type: string, format: uri }
    RfaRequestType:
      type: string
      enum: [ new, resubmission_material_change, oral_authorization_confirmation ]
    RfaReviewType:
      type: string
      enum: [ prospective, concurrent, retrospective ]
    RfaInboundFax:
      type: object
      required: [ id, receivedAt, fromName, fromFax, pages, ocrStatus, matchedRfaId, documentId, previewUrl, suggestedRfaIds ]
      properties:
        id: { type: string }
        receivedAt: { type: string }
        fromName: { type: string }
        fromFax: { type: string }
        pages: { type: number }
        ocrStatus: { type: [ string, 'null' ] }
        matchedRfaId: { type: [ string, 'null' ] }
        documentId: { type: [ string, 'null' ] }
        previewUrl: { type: string, description: Relative authenticated PDF endpoint; fetch with the authorized session rather than opening an unauthenticated URL. }
        suggestedRfaIds: { type: array, items: { type: string }, description: Scoped OCR matching suggestions only; an operator must review and confirm the association. }
    RfaFollowUp:
      type: object
      required: [ id, rfaId, claimId, kind, status, dueAt, createdAt, updatedAt ]
      properties:
        id: { type: string }
        rfaId: { type: string }
        claimId: { type: string }
        responseDocumentId: { type: [ string, 'null' ], description: Source UR response document for post_ur_decision tasks; null for other task kinds. }
        responseFilename: { type: [ string, 'null' ], description: Filename of the source UR response document; null for other task kinds or a missing document. }
        kind: { type: string, enum: [ send_rfa, no_response, transmission_failed, transmission_unconfirmed, information_requested, clock_review, schedule_treatment, post_ur_decision, document_required ] }
        status: { type: string, enum: [ open, resolved ] }
        dueAt: { type: string, format: date-time }
        assigneeReference: { type: [ string, 'null' ] }
        snoozedUntil: { type: [ string, 'null' ], format: date-time }
        lastOutcome: { type: [ string, 'null' ] }
        lastNote: { type: [ string, 'null' ] }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
        resolvedAt: { type: [ string, 'null' ], format: date-time }
    UpdateRfaFollowUp:
      type: object
      additionalProperties: false
      minProperties: 1
      properties:
        assigneeReference: { type: [ string, 'null' ], minLength: 1, maxLength: 120 }
        snoozedUntil: { type: [ string, 'null' ], format: date-time, description: Future timestamp within 90 days; null clears the reminder. }
        outcome: { type: string, enum: [ message_left, decision_pending, decision_issued, not_on_file, reviewed ] }
        note: { type: string, minLength: 1, maxLength: 2000 }
        responseReview:
          description: Only for an open post_ur_decision task. Explicitly completes review of this response PDF and resolves only its reminder. Recording individual service decisions does not close the reminder. Use decisions_recorded after recording every decision in this PDF; at least one recorded decision must reference this document. A partial payer response may be completed while other RFA services remain pending. Use no_new_decision for a duplicate or response with no new or corrected decision. Requires a note and cannot accompany outcome or snoozedUntil. Never changes authorization.
          oneOf:
            - type: object
              additionalProperties: false
              required: [ disposition, noNewDecisionConfirmed ]
              properties:
                disposition: { type: string, const: no_new_decision }
                noNewDecisionConfirmed: { type: boolean, const: true }
            - type: object
              additionalProperties: false
              required: [ disposition, allDecisionsRecordedConfirmed ]
              properties:
                disposition: { type: string, const: decisions_recorded }
                allDecisionsRecordedConfirmed: { type: boolean, const: true }
      dependentRequired:
        outcome: [ note, snoozedUntil ]
        responseReview: [ note ]
      allOf:
        - if: { required: [ responseReview ] }
          then:
            not:
              anyOf:
                - required: [ outcome ]
                - required: [ snoozedUntil ]
    RfaTemplateItem:
      type: object
      additionalProperties: false
      required: [ externalId, serviceDescription ]
      properties:
        externalId: { type: string, minLength: 1, maxLength: 255, description: Stable and unique within the template. Generate fresh service IDs when creating each RFA. }
        serviceDescription: { type: string, minLength: 1, maxLength: 1000 }
        diagnosisCode: { type: string, maxLength: 16 }
        procedureCode: { type: string, minLength: 1, maxLength: 16 }
        quantity: { type: number, exclusiveMinimum: 0, maximum: 100000 }
        units: { type: integer, minimum: 1, maximum: 100000 }
        frequency: { type: string, minLength: 1, maxLength: 200 }
        duration: { type: string, minLength: 1, maxLength: 200 }
    SaveRfaTemplate:
      type: object
      additionalProperties: false
      required: [ name, billingProviderId, items ]
      properties:
        name: { type: string, minLength: 1, maxLength: 200 }
        billingProviderId: { type: string, minLength: 1, maxLength: 255 }
        renderingProviderId: { type: [ string, 'null' ], minLength: 1, maxLength: 255, default: null }
        active: { type: boolean, default: true }
        items: { type: array, minItems: 1, maxItems: 100, items: { $ref: '#/components/schemas/RfaTemplateItem' } }
    RfaTemplate:
      type: object
      required: [ id, name, billingProviderId, renderingProviderId, active, items, createdAt, updatedAt ]
      properties:
        id: { type: string }
        name: { type: string }
        billingProviderId: { type: string }
        renderingProviderId: { type: [ string, 'null' ] }
        active: { type: boolean }
        items: { type: array, items: { $ref: '#/components/schemas/RfaTemplateItem' } }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
    RfaStatus:
      type: string
      enum: [ draft, ready, submitted, received, incomplete, under_review, information_requested, deferred, approved, modified, denied, mixed, canceled, closed ]
    RfaLifecycleStatus:
      type: string
      readOnly: true
      enum: [ incomplete, sent, failed, received, closed, canceled ]
      description: Derived delivery lifecycle. Draft/ready requests are incomplete until submitted. The latest outbound submission determines sent or failed until receipt evidence for that attempt is recorded; forwards and receipts from earlier attempts do not change it. Requests with final per-treatment outcomes or explicit closure are closed; canceled remains separate. Clinical outcomes and exception details remain in status and items. Closed does not imply approved treatment or completed scheduling.
    RfaItemOutcome:
      type: string
      enum: [ pending, approved, modified, denied ]
    RfaDocumentType:
      type: string
      enum: [ rfa_form, clinical_report, supporting_record, ur_response, imr_form, fax_cover, other ]
    RfaContact:
      type: [ object, 'null' ]
      additionalProperties: false
      description: Request-specific contact snapshot included in the physician-reviewed form. An omitted snapshot keeps existing values; null clears it. Authorization contacts must be verified for RFA routing rather than copied from a billing destination.
      properties:
        name: { type: string, maxLength: 200, description: Company or practice name. }
        contactName: { type: string, maxLength: 200, description: Individual contact name. }
        address: { type: string, maxLength: 500 }
        city: { type: string, maxLength: 100 }
        state: { type: string, pattern: '^[A-Z]{2}$' }
        zip: { type: string, pattern: '^\d{5}(?:-\d{4})?$' }
        phone: { type: string, maxLength: 30, description: 10 to 15 digits with optional phone punctuation or empty to clear. }
        fax: { type: string, maxLength: 30, description: 10 to 15 digits with optional phone punctuation or empty to clear. }
        email: { type: string, format: email, maxLength: 254 }
    CreateRfaItem:
      type: object
      additionalProperties: false
      required: [ diagnosisCode, serviceDescription ]
      properties:
        diagnosisDescription: { type: [ string, 'null' ], minLength: 1, maxLength: 2000, description: Diagnosis description retained with this treatment line and included in the physician-reviewed form. }
        externalId: { type: string, minLength: 1, maxLength: 255 }
        diagnosisCode: { type: string, minLength: 1, maxLength: 16 }
        serviceDescription: { type: string, minLength: 1, maxLength: 1000 }
        procedureCode: { type: string, minLength: 1, maxLength: 16 }
        quantity: { type: number, exclusiveMinimum: 0, maximum: 100000 }
        units: { type: integer, minimum: 1, maximum: 100000 }
        frequency: { type: string, minLength: 1, maxLength: 200 }
        duration: { type: string, minLength: 1, maxLength: 200 }
        requestedFrom: { type: string, format: date }
        requestedTo: { type: string, format: date, description: Requires requestedFrom and must be on or after it. }
        metadata: { type: object, additionalProperties: true, default: {} }
    CreateRfaRequest:
      type: object
      additionalProperties: false
      required: [ claimId, patientId, renderingProviderId, employeeName, providerName, items ]
      properties:
        writtenConfirmation: { type: boolean, description: Written confirmation of a prior oral request; independent of new or material-change request type. }
        requestingPractice: { $ref: '#/components/schemas/RfaContact' }
        authorizationContact: { $ref: '#/components/schemas/RfaContact' }
        externalId: { type: string, minLength: 1, maxLength: 255 }
        claimId: { type: string, minLength: 1, maxLength: 255 }
        patientId: { type: string, minLength: 1, maxLength: 255 }
        renderingProviderId: { type: string, minLength: 1, maxLength: 255 }
        claimsAdminId: { type: string, minLength: 1, maxLength: 255 }
        requestType: { $ref: '#/components/schemas/RfaRequestType' }
        reviewType: { $ref: '#/components/schemas/RfaReviewType' }
        expedited: { type: boolean, default: false, description: Applies only to prospective or concurrent review; retrospective expedited requests are rejected. }
        employeeName: { type: string, minLength: 1, maxLength: 200 }
        providerName: { type: string, minLength: 1, maxLength: 200 }
        placeOfServiceCode: { type: string, pattern: '^[0-9]{2}$' }
        providerNpi: { type: string, maxLength: 20 }
        providerPhone: { type: string, maxLength: 30 }
        providerFax: { type: string, maxLength: 30, description: "UR return fax snapshot. Use 10 to 15 digits with optional phone punctuation, or an empty string to clear. No server fallback to organization defaults." }
        claimNumber: { type: string, maxLength: 100 }
        dateOfInjury: { type: string, format: date }
        rationale: { type: string, maxLength: 20000 }
        materialChange: { type: string, maxLength: 20000, description: Required for resubmission_material_change requests. }
        signedAt: { type: string, format: date-time }
        items: { type: array, minItems: 1, maxItems: 100, items: { $ref: '#/components/schemas/CreateRfaItem' } }
        metadata: { type: object, additionalProperties: true, default: {} }
    UpdateRfaRequest:
      type: object
      additionalProperties: false
      minProperties: 1
      properties:
        draftOnly: { type: boolean, const: true, description: Guard cancellation against concurrent edits or submission. Requires status=canceled and expectedRevision, and forbids other changes. Only unsigned, unsubmitted drafts without submission dispatches can be canceled this way. History is retained. }
        expectedRevision: { type: integer, minimum: 1, maximum: 2000000000, description: Required with draftOnly; must match the current contentRevision. }
        writtenConfirmation: { type: boolean, description: Written confirmation of a prior oral request; independent of new or material-change request type. }
        requestingPractice: { $ref: '#/components/schemas/RfaContact' }
        authorizationContact: { $ref: '#/components/schemas/RfaContact' }
        status: { type: string, enum: [ draft, ready, incomplete, deferred, canceled, closed ] }
        signedAt: { type: [ string, 'null' ], format: date-time }
        rationale: { type: [ string, 'null' ], maxLength: 20000 }
        materialChange: { type: [ string, 'null' ], maxLength: 20000 }
        incompleteReason: { type: string, minLength: 1, maxLength: 5000, description: Required when status is incomplete. }
        deferredReason: { type: string, minLength: 1, maxLength: 5000, description: Required when status is deferred. }
        closedReason: { type: string, minLength: 1, maxLength: 5000, description: Required when status is closed. }
        metadata: { type: object, additionalProperties: true }
    RecordRfaTransmissionRequest:
      type: object
      additionalProperties: false
      required: [ direction, channel, status, occurredAt ]
      properties:
        direction: { type: string, enum: [ outbound, inbound ] }
        channel: { type: string, enum: [ fax, email, edi, portal, mail, manual ] }
        status: { type: string, enum: [ queued, sent, delivered, received, failed ] }
        destination: { type: string, maxLength: 500 }
        providerMessageId: { type: string, maxLength: 500 }
        proofDocumentId: { type: string, minLength: 1, maxLength: 255 }
        occurredAt: { type: string, format: date-time }
        receivedAt: { type: string, format: date-time, description: Actual receipt evidence. Required when status is received unless mailReceiptEvidence is provided. }
        transmittedAt:
          type: string
          format: date-time
          description: Actual electronic transmission time for fax/email/EDI; requires receivedAt and must be on or before it. The 5.30 PM Pacific cutoff uses this time when supplied, otherwise receivedAt. Do not use an attempt queue time.
        mailReceiptEvidence:
          description: Explicit evidence for an inbound mail record with received status and a scoped proofDocumentId. Omit receivedAt and transmittedAt. USPS deposit presumes receipt five business days later; latest sender-written document date presumes five calendar days later only when mailing and receipt evidence are unavailable; certified return receipt uses its actual receipt timestamp. A missing calendar needed to determine the five-business-day USPS receipt presumption returns 422 without recording the transmission.
          oneOf:
            - type: object
              additionalProperties: false
              required: [kind, date]
              properties:
                kind: { type: string, enum: [usps_deposit] }
                date: { type: string, format: date }
            - type: object
              additionalProperties: false
              required: [kind, date]
              properties:
                kind: { type: string, enum: [latest_document_date] }
                date: { type: string, format: date }
            - type: object
              additionalProperties: false
              required: [kind, receivedAt]
              properties:
                kind: { type: string, enum: [certified_return_receipt] }
                receivedAt: { type: string, format: date-time }
        nonBusinessDates: { type: array, maxItems: 100, items: { type: string, format: date }, default: [], description: California non-business dates used in the deadline calculation. }
        metadata: { type: object, additionalProperties: true, default: {} }
      description: Inbound records must be received. Outbound records cannot be received. Sent, delivered, and received records require providerMessageId or proofDocumentId.
    CreateRfaInformationRequestRequest:
      type: object
      additionalProperties: false
      required: [ requestedAt, requestText ]
      properties:
        requestedAt: { type: string, format: date-time }
        requestText: { type: string, minLength: 1, maxLength: 20000 }
        dueAt: { type: string, format: date-time }
    RespondRfaInformationRequestRequest:
      type: object
      additionalProperties: false
      required: [ respondedAt, responseDocumentIds ]
      properties:
        respondedAt: { type: string, format: date-time }
        responseDocumentIds: { type: array, minItems: 1, maxItems: 100, items: { type: string, minLength: 1, maxLength: 255 } }
    ReviewRfaInformationReceiptRequest:
      type: object
      additionalProperties: false
      required: [ expectedExceptionEventId, informationRequestIds, completeRequestReceivedAt, reviewerReceivedAt, evidenceDocumentIds, missingInformationOnly, allRequestedInformationReceived, standardReviewConfirmed ]
      properties:
        expectedExceptionEventId: { type: string, minLength: 1, maxLength: 255, description: Latest exception event ID returned by the RFA. }
        informationRequestIds: { type: array, minItems: 1, maxItems: 100, uniqueItems: true, items: { type: string, minLength: 1, maxLength: 255 }, description: All recorded information requests. }
        completeRequestReceivedAt: { type: string, format: date-time, description: Explicitly verified original complete or accepted-as-complete receipt; must equal stored receivedAt as an instant. }
        reviewerReceivedAt: { type: string, format: date-time, description: Actual receipt of all requested information by the reviewer or claims administrator; sending a response is insufficient. }
        evidenceDocumentIds: { type: array, minItems: 1, maxItems: 100, uniqueItems: true, items: { type: string, minLength: 1, maxLength: 255 }, description: Uploaded same-RFA documents supporting actual receipt and completeness. }
        missingInformationOnly: { type: boolean, const: true, description: No additional examination, test, specialist consultation, incomplete form, or liability deferral applies. }
        allRequestedInformationReceived: { type: boolean, const: true, description: All reasonably necessary requested information was received. }
        standardReviewConfirmed: { type: boolean, const: true, description: Standard prospective or concurrent review; no expedited, retrospective, MTUS formulary, or other special timeframes apply. }
    RfaDecisionClockReview:
      type: [ object, 'null' ]
      additionalProperties: false
      required: [ eventId, exceptionEventId, receivedAt, dueAt, informationRequestIds, evidenceDocumentIds, sourceUrls ]
      properties:
        eventId: { type: string }
        exceptionEventId: { type: string }
        receivedAt: { type: string, format: date-time }
        dueAt: { type: string, format: date-time }
        informationRequestIds: { type: array, items: { type: string } }
        evidenceDocumentIds: { type: array, items: { type: string } }
        sourceUrls: { type: array, items: { type: string, format: uri } }
    RfaDecisionItem:
      type: object
      additionalProperties: false
      required: [ itemId, outcome ]
      properties:
        itemId: { type: string, minLength: 1, maxLength: 255 }
        outcome: { type: string, enum: [ approved, modified, denied ] }
        authorizationNumber: { type: string, minLength: 1, maxLength: 100, description: Required for approved and modified treatment. }
        authorizedProcedureCode: { type: string, minLength: 1, maxLength: 16 }
        authorizedQuantity: { type: number, exclusiveMinimum: 0, maximum: 100000 }
        authorizedUnits: { type: integer, minimum: 1, maximum: 100000 }
        effectiveFrom: { type: string, format: date }
        effectiveTo: { type: string, format: date, description: Requires effectiveFrom and must be on or after it. }
        decisionReason: { type: string, maxLength: 20000, description: Required for modified and denied treatment. }
        reviewerName: { type: string, maxLength: 200, description: Required for modified and denied treatment. }
        reviewerPhone: { type: string, maxLength: 30, description: Required for modified and denied treatment. }
    RecordRfaDecisionRequest:
      type: object
      additionalProperties: false
      required: [ decidedAt, responseDocumentId, decisions ]
      properties:
        decidedAt: { type: string, format: date-time }
        responseDocumentId: { type: string, minLength: 1, maxLength: 255 }
        imrDocumentId: { type: string, minLength: 1, maxLength: 255, description: Required if any item is modified or denied. }
        decisions: { type: array, minItems: 1, maxItems: 100, items: { $ref: '#/components/schemas/RfaDecisionItem' } }
    CorrectRfaDecisionRequest:
      type: object
      additionalProperties: false
      required: [ itemId, expectedDecisionEventId, reason, replacement ]
      properties:
        itemId: { type: string, minLength: 1, maxLength: 255, description: Already-decided item to correct. }
        expectedDecisionEventId: { type: string, minLength: 1, maxLength: 255, description: Selected item's currentDecisionEventId from a fresh RFA read. }
        reason: { type: string, minLength: 1, maxLength: 20000, description: Correction explanation. Trimmed and must not be blank. Retained in the authenticated RFA audit trail. }
        replacement:
          description: Complete replacement decision with exactly one decisions entry whose itemId matches the outer itemId. Approved or modified requires an authorization number; modified or denied also requires reviewer name, phone, reason, and an uploaded official IMR form.
          allOf:
            - $ref: '#/components/schemas/RecordRfaDecisionRequest'
            - type: object
              properties:
                decisions: { type: array, minItems: 1, maxItems: 1, items: { $ref: '#/components/schemas/RfaDecisionItem' } }
    RfaReadiness:
      type: object
      additionalProperties: false
      required: [ ready, missing ]
      properties:
        ready: { type: boolean }
        missing: { type: array, items: { type: string } }
    UpdateRfaTreatmentClosureRequest:
      type: object
      additionalProperties: false
      required: [closed, reason, expectedVersion]
      properties:
        closed: { type: boolean }
        reason: { type: string, minLength: 1, maxLength: 2000 }
        expectedVersion: { type: integer, minimum: 0 }
    RfaTreatmentClosure:
      type: object
      additionalProperties: false
      required: [closed, reason, version, updatedAt, updatedBy]
      properties:
        closed: { type: boolean }
        reason: { type: string }
        version: { type: integer, minimum: 1 }
        updatedAt: { type: string, format: date-time }
        updatedBy: { type: string }
    RfaAgingCounts:
      type: object
      additionalProperties: false
      required: ['0_5', '6_14', '15_30', '31_plus']
      properties:
        '0_5': { type: integer, minimum: 0 }
        '6_14': { type: integer, minimum: 0 }
        '15_30': { type: integer, minimum: 0 }
        '31_plus': { type: integer, minimum: 0 }
    RfaItem:
      type: object
      additionalProperties: false
      required: [ id, ordinal, diagnosisCode, serviceDescription, outcome, metadata ]
      properties:
        diagnosisDescription: { type: [ string, 'null' ], minLength: 1, maxLength: 2000, description: Diagnosis description retained with this treatment line and included in the physician-reviewed form. }
        id: { type: string }
        externalId: { type: [ string, 'null' ] }
        ordinal: { type: integer, minimum: 1 }
        diagnosisCode: { type: string }
        serviceDescription: { type: string }
        procedureCode: { type: [ string, 'null' ] }
        quantity: { type: [ number, 'null' ] }
        units: { type: [ integer, 'null' ] }
        frequency: { type: [ string, 'null' ] }
        duration: { type: [ string, 'null' ] }
        requestedFrom: { type: [ string, 'null' ], format: date }
        requestedTo: { type: [ string, 'null' ], format: date }
        outcome: { $ref: '#/components/schemas/RfaItemOutcome' }
        authorizationNumber: { type: [ string, 'null' ] }
        authorizedProcedureCode: { type: [ string, 'null' ] }
        authorizedQuantity: { type: [ number, 'null' ] }
        authorizedUnits: { type: [ integer, 'null' ] }
        effectiveFrom: { type: [ string, 'null' ], format: date }
        effectiveTo: { type: [ string, 'null' ], format: date }
        decisionReason: { type: [ string, 'null' ] }
        reviewerName: { type: [ string, 'null' ] }
        reviewerPhone: { type: [ string, 'null' ] }
        decidedAt: { type: [ string, 'null' ], format: date-time }
        decisionClosure:
          oneOf:
            - $ref: "#/components/schemas/RfaTreatmentClosure"
            - type: "null"
        currentDecisionEventId: { type: [ string, 'null' ], description: Current immutable decision or correction event for this item. Use as expectedDecisionEventId when correcting it. }
        currentResponseDocumentId: { type: [ string, 'null' ], description: UR response evidence for this item's current decision. Use item-level evidence when items were decided separately. }
        currentImrDocumentId: { type: [ string, 'null' ], description: Official IMR form associated with this item's current decision, when applicable. }
        metadata: { type: object, additionalProperties: true }
    RfaLibraryDocument:
      type: object
      additionalProperties: false
      required: [ id, billingProviderId, filename, description, reportType, sha256, sizeBytes, createdAt, updatedAt ]
      properties:
        id: { type: string }
        billingProviderId: { type: string }
        filename: { type: string }
        description: { type: string }
        reportType: { type: string }
        sha256: { type: string }
        sizeBytes: { type: integer, minimum: 1, maximum: 26214400 }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
    RfaLibraryDocumentEnvelope:
      type: object
      required: [ data ]
      properties:
        data: { $ref: '#/components/schemas/RfaLibraryDocument' }
    RfaLibraryListEnvelope:
      type: object
      required: [ data ]
      properties:
        data:
          type: object
          required: [ billingProviderId, canManage, documents ]
          properties:
            billingProviderId: { type: [ string, 'null' ] }
            canManage: { type: boolean }
            documents: { type: array, items: { $ref: '#/components/schemas/RfaLibraryDocument' } }
    RfaLibraryArchiveEnvelope:
      type: object
      required: [ data ]
      properties:
        data:
          type: object
          required: [ id, archived ]
          properties:
            id: { type: string }
            archived: { type: boolean, const: true }
    RfaDocumentSource:
      type: object
      additionalProperties: false
      required: [ type, parentId, documentId ]
      properties:
        type: { type: string, enum: [ bill, injury, library ] }
        parentId: { type: string, minLength: 1, maxLength: 255, pattern: '^[A-Za-z0-9_-]+$' }
        documentId: { type: string, minLength: 1, maxLength: 255, pattern: '^[A-Za-z0-9_-]+$' }
    RfaDocumentCandidate:
      type: object
      additionalProperties: false
      required: [ type, parentId, documentId, filename, reportType ]
      properties:
        type: { type: string, enum: [ bill, injury, library ] }
        parentId: { type: string }
        documentId: { type: string }
        filename: { type: string }
        reportType: { type: [ string, 'null' ] }
    CopyRfaDocumentRequest:
      type: object
      additionalProperties: false
      required: [ source, documentType, contentRevision ]
      properties:
        source: { $ref: '#/components/schemas/RfaDocumentSource' }
        documentType: { $ref: '#/components/schemas/RfaDocumentType' }
        contentRevision: { type: integer, minimum: 1 }
    RfaDocument:
      type: object
      additionalProperties: false
      required:
        - id
        - documentType
        - filename
        - sha256
        - sizeBytes
        - createdAt
        - contentUrl
        - contentRevision
      properties:
        id: { type: string }
        documentType: { $ref: '#/components/schemas/RfaDocumentType' }
        filename: { type: string }
        sha256: { type: string }
        sizeBytes: { type: integer, minimum: 1 }
        createdAt: { type: string, format: date-time }
        contentUrl: { type: string }
        contentRevision:
          type: integer
          minimum: 1
    RfaTransmission:
      type: object
      additionalProperties: false
      required:
        - id
        - direction
        - channel
        - status
        - occurredAt
        - metadata
        - createdAt
        - purpose
        - packetId
      properties:
        id: { type: string }
        direction: { type: string, enum: [ outbound, inbound ] }
        channel: { type: string, enum: [ fax, email, edi, portal, mail, manual ] }
        status: { type: string, enum: [ queued, sent, delivered, received, failed ] }
        destination: { type: [ string, 'null' ] }
        providerMessageId: { type: [ string, 'null' ] }
        proofDocumentId: { type: [ string, 'null' ] }
        occurredAt: { type: string, format: date-time }
        receivedAt: { type: [ string, 'null' ], format: date-time }
        metadata: { type: object, additionalProperties: true }
        createdAt: { type: string, format: date-time }
        purpose:
          type: string
          enum:
            - submission
            - forward
        packetId:
          type:
            - string
            - "null"
    RfaInformationRequest:
      type: object
      additionalProperties: false
      required: [ id, requestedAt, requestText, responseDocumentIds, createdAt ]
      properties:
        id: { type: string }
        requestedAt: { type: string, format: date-time }
        requestText: { type: string }
        dueAt: { type: [ string, 'null' ], format: date-time }
        respondedAt: { type: [ string, 'null' ], format: date-time }
        responseDocumentIds: { type: array, items: { type: string } }
        createdAt: { type: string, format: date-time }
    Rfa:
      type: object
      additionalProperties: false
      required:
        - id
        - claimId
        - patientId
        - renderingProviderId
        - requestType
        - reviewType
        - expedited
        - status
        - lifecycleStatus
        - employeeName
        - providerName
        - metadata
        - createdAt
        - updatedAt
        - readiness
        - items
        - documents
        - transmissions
        - informationRequests
        - contentRevision
        - events
      properties:
        writtenConfirmation: { type: boolean, description: Written confirmation of a prior oral request; independent of new or material-change request type. }
        requestingPractice: { $ref: '#/components/schemas/RfaContact' }
        authorizationContact: { $ref: '#/components/schemas/RfaContact' }
        id: { type: string }
        externalId: { type: [ string, 'null' ] }
        copiedFromRfaId: { type: [ string, 'null' ] }
        claimId: { type: string }
        patientId: { type: string }
        renderingProviderId: { type: string }
        claimsAdminId: { type: [ string, 'null' ] }
        requestType: { $ref: '#/components/schemas/RfaRequestType' }
        reviewType: { $ref: '#/components/schemas/RfaReviewType' }
        expedited: { type: boolean }
        status: { $ref: '#/components/schemas/RfaStatus' }
        lifecycleStatus: { $ref: '#/components/schemas/RfaLifecycleStatus' }
        employeeName: { type: string }
        providerName: { type: string }
        placeOfServiceCode: { type: [ string, 'null' ], pattern: '^[0-9]{2}$' }
        providerNpi: { type: [ string, 'null' ] }
        providerPhone: { type: [ string, 'null' ] }
        providerFax: { type: [ string, 'null' ] }
        claimNumber: { type: [ string, 'null' ] }
        dateOfInjury: { type: [ string, 'null' ], format: date }
        rationale: { type: [ string, 'null' ] }
        materialChange: { type: [ string, 'null' ] }
        signedAt: { type: [ string, 'null' ], format: date-time }
        submittedAt: { type: [ string, 'null' ], format: date-time }
        receivedAt: { type: [ string, 'null' ], format: date-time }
        decisionDueAt: { type: [ string, 'null' ], format: date-time }
        decisionDeadlineBasis: { type: [ string, 'null' ], enum: [ 72_hours, 5_business_days, 30_calendar_days, calendar_unavailable, exception_review_required, information_received_5_business_days, null ] }
        latestExceptionEventId: { type: [ string, 'null' ], description: "Most recently appended incomplete, deferred, or information-request exception event; ordered by immutable sequence." }
        decisionClockReview: { $ref: '#/components/schemas/RfaDecisionClockReview' }
        decidedAt: { type: [ string, 'null' ], format: date-time }
        responseDocumentId: { type: [ string, 'null' ] }
        imrDocumentId: { type: [ string, 'null' ] }
        incompleteReason: { type: [ string, 'null' ] }
        deferredReason: { type: [ string, 'null' ] }
        closedReason: { type: [ string, 'null' ] }
        metadata: { type: object, additionalProperties: true }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
        readiness: { $ref: '#/components/schemas/RfaReadiness' }
        items: { type: array, items: { $ref: '#/components/schemas/RfaItem' } }
        documents: { type: array, items: { $ref: '#/components/schemas/RfaDocument' } }
        transmissions: { type: array, items: { $ref: '#/components/schemas/RfaTransmission' } }
        informationRequests: { type: array, items: { $ref: '#/components/schemas/RfaInformationRequest' } }
        events:
          type: array
          description: Minimal history summaries; internal actor credentials and event payloads are excluded.
          items:
            type: object
            additionalProperties: false
            required: [ id, type, occurredAt ]
            properties:
              id: { type: string }
              type: { type: string }
              occurredAt: { type: string, format: date-time }
              text: { type: string, description: Present only for a history note event. }
        contentRevision:
          type: integer
          minimum: 1
    RfaEvent:
      type: object
      additionalProperties: false
      required: [ id, sequence, eventType, actor, payload, occurredAt ]
      properties:
        id: { type: string }
        sequence: { type: integer, minimum: 1 }
        eventType: { type: string }
        actor: { type: string }
        payload: { type: object, additionalProperties: true }
        occurredAt: { type: string, format: date-time }
    RfaEnvelope:
      type: object
      additionalProperties: false
      required: [ data ]
      properties:
        data: { $ref: '#/components/schemas/Rfa' }
    RfaListEnvelope:
      type: object
      additionalProperties: false
      required:
        - data
        - nextCursor
        - summary
      properties:
        data:
          type: array
          items:
            $ref: "#/components/schemas/Rfa"
        nextCursor:
          type:
            - string
            - "null"
        summary:
          type: object
          additionalProperties: false
          required:
            - total
            - byStatus
            - byLifecycleStatus
            - aging
          properties:
            total:
              type: integer
              minimum: 0
            byStatus:
              type: object
              propertyNames:
                enum:
                  - draft
                  - ready
                  - submitted
                  - received
                  - incomplete
                  - under_review
                  - information_requested
                  - deferred
                  - approved
                  - modified
                  - denied
                  - mixed
                  - canceled
                  - closed
              additionalProperties:
                type: integer
                minimum: 0
            aging:
              type: object
              required: [byBucket, byLifecycleStatus]
              description: Global counts in the complete filtered scope, including zero buckets. Age is UTC calendar days since submission for unresolved sent and received RFAs.
              properties:
                byBucket: { $ref: '#/components/schemas/RfaAgingCounts' }
                byLifecycleStatus:
                  type: object
                  required: [incomplete, sent, failed, received, closed, canceled]
                  additionalProperties: { $ref: '#/components/schemas/RfaAgingCounts' }
            byLifecycleStatus:
              type: object
              propertyNames:
                enum: [ incomplete, sent, failed, received, closed, canceled ]
              additionalProperties:
                type: integer
                minimum: 0
    RfaEventListEnvelope:
      type: object
      additionalProperties: false
      required: [ data ]
      properties:
        data: { type: array, items: { $ref: '#/components/schemas/RfaEvent' } }
    EventPage:
      type: object
      required: [ events ]
      properties:
        events:
          type: array
          items:
            type: object
            required: [ id, sequence, type, apiVersion, createdAt, data ]
            properties:
              id: { type: string }
              sequence: { type: string, pattern: '^[0-9]+$' }
              type: { type: string }
              apiVersion: { type: string }
              createdAt: { type: string, format: date-time }
              data: { type: object, additionalProperties: true }
        nextCursor: { type: [ string, 'null' ] }
    WebhookDelivery:
      type: object
      required: [ id, eventId, sequence, eventType, status, attemptCount, createdAt ]
      properties:
        id: { type: string }
        eventId: { type: string }
        sequence: { type: string, pattern: '^[0-9]+$' }
        eventType: { type: string }
        status: { type: string }
        attemptCount: { type: integer }
        responseStatus: { type: [ integer, 'null' ] }
        nextAttemptAt: { type: [ string, 'null' ], format: date-time }
        deliveredAt: { type: [ string, 'null' ], format: date-time }
        createdAt: { type: string, format: date-time }
    OrganizationTeamMember:
      type: object
      required:
      - id
      - email
      - name
      - role
      - active
      - createdAt
      - canManage
      properties:
        id:
          type: string
        email:
          type: string
        name:
          type: string
        createdAt:
          type: string
        role:
          type: string
          description: Existing account role; may include legacy or protected roles that cannot be assigned.
        active:
          type: boolean
        canManage:
          type: boolean
    OrganizationTeam:
      type: object
      required:
      - members
      - roles
      - capabilities
      - identityDomain
      properties:
        members:
          type: array
          items:
            $ref: '#/components/schemas/OrganizationTeamMember'
        roles:
          type: array
          items:
            type: object
            required:
            - id
            - label
            - permissions
            properties:
              id:
                type: string
                enum:
                - admin
                - manager
                - biller
                - payments
                - viewer
              label:
                type: string
              permissions:
                type: array
                items:
                  type: string
        capabilities:
          type: object
          required:
          - canManage
          - canAdd
          properties:
            canManage:
              type: boolean
            canAdd:
              type: boolean
              const: false
        identityDomain:
          type: string
          const: mindbill
    OrganizationTeamMemberPatch:
      type: object
      additionalProperties: false
      minProperties: 1
      properties:
        role:
          type: string
          enum:
          - admin
          - manager
          - biller
          - payments
          - viewer
        active:
          type: boolean
    CustomClaimsAdministratorWrite:
      type: object
      additionalProperties: false
      required:
      - name
      description: Values are trimmed. Provide at least one nonblank fax, email, or mailingAddress. For PATCH, omitted
        nullable fields are cleared.
      properties:
        name:
          type: string
          minLength: 1
          maxLength: 200
        fax:
          type:
          - string
          - 'null'
          maxLength: 50
        email:
          type:
          - string
          - 'null'
          maxLength: 254
          description: Valid email address, empty string, or null.
        mailingAddress:
          type:
          - string
          - 'null'
          maxLength: 2000
        notes:
          type:
          - string
          - 'null'
          maxLength: 4000
    CustomClaimsAdministrator:
      type: object
      required:
      - id
      - name
      - fax
      - email
      - mailingAddress
      - submissionMethod
      - notes
      - active
      - createdAt
      properties:
        id:
          type: string
        name:
          type: string
        createdAt:
          type: string
        fax:
          type:
          - string
          - 'null'
        email:
          type:
          - string
          - 'null'
        mailingAddress:
          type:
          - string
          - 'null'
        notes:
          type:
          - string
          - 'null'
        submissionMethod:
          type: string
          enum:
          - fax
          - email
          - mail
        active:
          type: boolean
    ReportAutofillField:
      type: object
      additionalProperties: false
      required: [key, value, sourceText, confidence]
      properties:
        key:
          type: string
          enum: [patientFirstName, patientLastName, dob, claimNumber, doi, adjNumber, employer, dos, bodyParts, dxCode, renderingProvider, claimsAdminName, evaluationLocation, addressLine, city, state, zip, billingProvider, billingProviderNpi, renderingProviderNpi]
        value:
          type: string
          minLength: 1
          maxLength: 2000
          description: Explicit report fact. Date keys use real YYYY-MM-DD dates; NPI keys contain exactly ten digits. Patient address keys never describe the provider or employer address.
        sourceText: { type: string, minLength: 1, maxLength: 3000, description: Short source quote for the reviewer. }
        confidence: { type: string, enum: [high, medium] }
    ReportAutofillMatch:
      type: object
      required: [status, candidates]
      properties:
        status: { type: string, enum: [matched, ambiguous, none] }
        selectedId: { type: string, description: Present only for a unique matched candidate. }
        candidates:
          type: array
          maxItems: 25
          items:
            type: object
            required: [id, name]
            properties:
              id: { type: string }
              name: { type: string }
    ReportAutofillDraft:
      type: object
      required: [model, requiresReview, fields, matches, warnings]
      properties:
        model: { type: string, const: gpt-5.6-luna }
        requiresReview: { type: boolean, const: true }
        fields:
          type: array
          maxItems: 20
          description: At most one entry per key. Unsupported, missing or conflicting facts are omitted.
          items: { $ref: '#/components/schemas/ReportAutofillField' }
        matches:
          type: object
          required: [patient, billingProvider, renderingProvider, serviceLocation]
          properties:
            patient: { $ref: '#/components/schemas/ReportAutofillMatch' }
            billingProvider: { $ref: '#/components/schemas/ReportAutofillMatch' }
            renderingProvider: { $ref: '#/components/schemas/ReportAutofillMatch' }
            serviceLocation: { $ref: '#/components/schemas/ReportAutofillMatch' }
        warnings: { type: array, items: { type: string } }
    BrowserPermission:
      type: string
      enum: [ bills:create, bills:read, bills:act, documents:read, payers:read, eors:read, organization:manage, team:manage, autofill:run, rfas:create, rfas:read, rfas:edit, rfas:act, rfas:sign ]
    BrowserSession:
      type: object
      required: [ sessionId, token, expiresAt, organizationId, subject, permissions, resource ]
      properties:
        sessionId: { type: string }
        token: { type: string, description: Short-lived browser credential. }
        expiresAt: { type: string, format: date-time }
        organizationId: { type: string, description: Internal billing context resolved automatically from the workspace or an authorized legacy override. No developer configuration is required. }
        subject: { type: string }
        permissions: { type: array, items: { $ref: '#/components/schemas/BrowserPermission' } }
        resource:
          oneOf:
            - type: object
              anyOf:
                - required: [ billId ]
                - required: [ customerExternalId ]
              properties:
                billId: { type: string }
                customerExternalId: { type: string, minLength: 1, maxLength: 255 }
            - type: 'null'
    EditRfaDraftItem:
      type: object
      additionalProperties: false
      required:
        - diagnosisCode
        - serviceDescription
      properties:
        diagnosisDescription: { type: [ string, 'null' ], minLength: 1, maxLength: 2000, description: Diagnosis description retained with this treatment line and included in the physician-reviewed form. }
        diagnosisCode:
          type: string
          minLength: 1
          maxLength: 16
        serviceDescription:
          type: string
          minLength: 1
          maxLength: 1000
        procedureCode:
          type: string
          minLength: 1
          maxLength: 16
        quantity:
          type: number
          exclusiveMinimum: 0
          maximum: 100000
        units:
          type: integer
          minimum: 1
          maximum: 100000
        frequency:
          type: string
          minLength: 1
          maxLength: 200
        duration:
          type: string
          minLength: 1
          maxLength: 200
        requestedFrom:
          type: string
          format: date
        requestedTo:
          type: string
          format: date
          description: Requires requestedFrom and must be on or after it.
        metadata:
          type: object
          additionalProperties: true
          default: {}
        id:
          type: string
          minLength: 1
          maxLength: 255
    EditRfaDraftRequest:
      type: object
      additionalProperties: false
      required:
        - employeeName
        - providerName
        - items
        - expectedRevision
      properties:
        writtenConfirmation: { type: boolean, description: Written confirmation of a prior oral request; independent of new or material-change request type. }
        requestingPractice: { $ref: '#/components/schemas/RfaContact' }
        authorizationContact: { $ref: '#/components/schemas/RfaContact' }
        claimsAdminId:
          type: string
          minLength: 1
          maxLength: 255
        requestType:
          $ref: "#/components/schemas/RfaRequestType"
        reviewType:
          $ref: "#/components/schemas/RfaReviewType"
        expedited:
          type: boolean
          default: false
        employeeName:
          type: string
          minLength: 1
          maxLength: 200
        providerName:
          type: string
          minLength: 1
          maxLength: 200
        placeOfServiceCode: { type: string, pattern: '^[0-9]{2}$' }
        providerNpi:
          type: string
          maxLength: 20
        providerPhone:
          type: string
          maxLength: 30
        providerFax:
          type: string
          maxLength: 30
          description: UR return fax snapshot; 10 to 15 digits with optional phone punctuation, or an empty string to clear.
        claimNumber:
          type: string
          maxLength: 100
        dateOfInjury:
          type: string
          format: date
        rationale:
          type: string
          maxLength: 20000
        materialChange:
          type: string
          maxLength: 20000
          description: Required for resubmission_material_change requests.
        items:
          type: array
          minItems: 1
          maxItems: 100
          items:
            $ref: "#/components/schemas/EditRfaDraftItem"
        metadata:
          type: object
          additionalProperties: true
          default: {}
        expectedRevision:
          type: integer
          minimum: 1
    CopyRfaRequest:
      type: object
      additionalProperties: false
      required:
        - expectedRevision
      properties:
        expectedRevision:
          type: integer
          minimum: 1
    RfaFormRequest:
      type: object
      additionalProperties: false
      properties:
        billingProviderId:
          type: string
          minLength: 1
          maxLength: 200
          description: Optional organization billing provider; defaults to the patient billing provider.
        diagnosisDescriptions:
          description: Optional per-item overrides; otherwise uses each saved diagnosisDescription. Each treatment line must have a description to generate the form.
          default: {}
          type: object
          additionalProperties:
            type: string
            minLength: 1
            maxLength: 2000
    RfaSigningPreview:
      type: object
      additionalProperties: false
      required:
        - data
      properties:
        data:
          type: object
          additionalProperties: false
          required:
            - id
            - contentHash
            - contentRevision
            - renderingProviderId
            - previewDocumentId
            - expiresAt
          properties:
            id: &a1
              type: string
            contentHash:
              type: string
              pattern: ^[a-f0-9]{64}$
            contentRevision:
              type: integer
              minimum: 1
            renderingProviderId: *a1
            previewDocumentId: *a1
            expiresAt:
              type: string
              format: date-time
    SignRfaRequest:
      type: object
      additionalProperties: false
      required:
        - snapshotId
        - contentHash
        - renderingProviderId
        - physicianAuthorized
        - actorReference
      properties:
        snapshotId:
          type: string
          minLength: 1
          maxLength: 200
        contentHash:
          type: string
          pattern: ^[a-f0-9]{64}$
        renderingProviderId:
          type: string
          minLength: 1
          maxLength: 200
        physicianAuthorized:
          type: boolean
          const: true
        actorReference:
          type: string
          minLength: 1
          maxLength: 200
    RetainRfaPacketRequest:
      type: object
      additionalProperties: false
      required:
        - documentIds
      properties:
        documentIds:
          type: array
          minItems: 2
          maxItems: 100
          uniqueItems: true
          items:
            type: string
            minLength: 1
    RfaPacket:
      type: object
      additionalProperties: false
      required:
        - id
        - source
        - sha256
        - sizeBytes
        - contentRevision
        - createdAt
      properties:
        id:
          type: string
        source:
          type: string
          enum:
            - download
            - submission
        sha256:
          type: string
          pattern: ^[a-f0-9]{64}$
        sizeBytes: &a2
          type: integer
          minimum: 1
        contentRevision: *a2
        createdAt:
          type: string
          format: date-time
    RfaPacketTransmission:
      type: object
      additionalProperties: false
      required:
        - id
        - packetId
        - purpose
        - channel
        - status
        - destination
        - occurredAt
        - receivedAt
      properties:
        id:
          type: string
        packetId:
          type:
            - string
            - "null"
        purpose:
          type: string
          enum:
            - submission
            - forward
        channel:
          type: string
          enum:
            - fax
            - email
            - edi
            - portal
            - mail
            - manual
        status:
          type: string
          enum:
            - queued
            - sent
            - delivered
            - received
            - failed
        destination:
          type:
            - string
            - "null"
        occurredAt:
          type: string
          format: date-time
        receivedAt:
          type:
            - string
            - "null"
          format: date-time
    RfaPacketHistoryEnvelope:
      type: object
      additionalProperties: false
      required:
        - data
      properties:
        data:
          type: object
          additionalProperties: false
          required:
            - packets
            - transmissions
          properties:
            packets:
              type: array
              items:
                $ref: "#/components/schemas/RfaPacket"
            transmissions:
              type: array
              items:
                $ref: "#/components/schemas/RfaPacketTransmission"
    RfaPacketEnvelope:
      type: object
      additionalProperties: false
      required:
        - data
      properties:
        data:
          type: object
          additionalProperties: false
          required:
            - packetId
          properties:
            packetId:
              type: string
    ForwardRfaPacketRequest:
      oneOf:
        - type: object
          additionalProperties: false
          required:
            - packetId
            - channel
            - to
          properties:
            packetId:
              type: string
              minLength: 1
              maxLength: 100
            channel:
              type: string
              const: fax
            to:
              type: string
              pattern: ^\+[1-9]\d{7,14}$
        - type: object
          additionalProperties: false
          required:
            - packetId
            - channel
            - to
          properties:
            packetId:
              type: string
              minLength: 1
              maxLength: 100
            channel:
              type: string
              const: email
            to:
              type: string
              format: email
              maxLength: 254
    RfaForwardEnvelope:
      type: object
      additionalProperties: false
      required:
        - data
      properties:
        data:
          type: object
          additionalProperties: false
          required:
            - transmissionId
            - packetId
          properties:
            transmissionId: &a3
              type: string
            packetId: *a3
    RfaSchedulingItem:
      type: object
      additionalProperties: false
      required: [ itemId, serviceDescription, outcome, eligible, authorizationToken, version, disposition, current, appointmentAt, providerName, location, reason, updatedAt ]
      properties:
        itemId: { type: string }
        serviceDescription: { type: string }
        outcome: { type: string }
        eligible: { type: boolean }
        authorizationToken: { type: string, pattern: '^[a-f0-9]{64}$' }
        version: { type: integer, minimum: 0 }
        disposition: { type: string, enum: [ pending, scheduled, no_appointment, canceled ] }
        current: { type: boolean }
        appointmentAt: { type: [ string, 'null' ], format: date-time }
        providerName: { type: [ string, 'null' ] }
        location: { type: [ string, 'null' ] }
        reason: { type: [ string, 'null' ] }
        updatedAt: { type: [ string, 'null' ], format: date-time }
    RfaSchedulingEnvelope:
      type: object
      additionalProperties: false
      required: [ data ]
      properties:
        data: { type: array, items: { $ref: '#/components/schemas/RfaSchedulingItem' } }
    UpdateRfaSchedulingRequest:
      oneOf:
        - type: object
          additionalProperties: false
          required: [ expectedVersion, authorizationToken, disposition, appointmentAt, providerName, location ]
          properties:
            expectedVersion: { type: integer, minimum: 0 }
            authorizationToken: { type: string, pattern: '^[a-f0-9]{64}$' }
            disposition: { const: scheduled }
            appointmentAt: { type: string, format: date-time, description: ISO 8601 timestamp with UTC or an explicit offset. }
            providerName: { type: string, minLength: 1, maxLength: 200 }
            location: { type: string, minLength: 1, maxLength: 500 }
        - type: object
          additionalProperties: false
          required: [ expectedVersion, authorizationToken, disposition, reason ]
          properties:
            expectedVersion: { type: integer, minimum: 0 }
            authorizationToken: { type: string, pattern: '^[a-f0-9]{64}$' }
            disposition: { type: string, enum: [ no_appointment, canceled ] }
            reason: { type: string, minLength: 1, maxLength: 2000 }
    NotificationStatusEvents:
      type: [array, 'null']
      minItems: 1
      maxItems: 13
      description: >-
        Optional status-event selection. Omitted or null preserves all supported status
        events. An explicit list narrows delivery when statusUpdates is true; false
        disables all status events. Duplicates are normalized and order is ignored.
        Changes require fresh recipient consent or a new invitation. Aging reminders
        and report digests are independent. For SBR-only notifications use
        [bill.second_review], agingDays=[], and reportDigest=off; for rejection-only
        notifications use [bill.rejected] with the same other categories disabled.
        Practice recipients cover all current and future providers' bills in their org.
      items:
        type: string
        enum: [bill.no_response, bill.submitted, bill.accepted, bill.rejected, bill.denied, bill.partially_paid, bill.paid, bill.second_review, bill.ibr, bill.closed, bill.written_off, payment.posted, eor.received]
    NotificationEnrollment:
      type: object
      additionalProperties: false
      required: [enabled, audience, email, statusUpdates, agingDays, quietHours, consent]
      properties:
        enabled: { const: true }
        audience: { type: string, enum: [practice, assigned_bills] }
        email: { type: string, format: email, maxLength: 254 }
        statusUpdates: { type: boolean }
        statusEvents: { $ref: '#/components/schemas/NotificationStatusEvents' }
        agingDays: { type: array, maxItems: 3, items: { type: integer, enum: [30, 60, 90] } }
        quietHours: { type: boolean, description: When true defer delivery outside 07:00-19:00 America/Los_Angeles. }
        consent:
          type: object
          additionalProperties: false
          required: [grantedAt, emailVerifiedAt, version]
          properties:
            grantedAt: { type: string, format: date-time }
            emailVerifiedAt: { type: string, format: date-time }
            version: { type: string, pattern: '^[A-Za-z0-9_.-]{1,64}$' }
    NotificationRecipient:
      type: object
      required: [enabled, audience, email, statusUpdates, agingDays, quietHours, assignedBillIds, eligible, unsubscribedAt, consentGrantedAt, consentVersion]
      properties:
        enabled: { type: boolean }
        audience: { type: string, enum: [practice, assigned_bills] }
        email: { type: string, description: Empty on a revoke-before-enrollment tombstone. }
        statusUpdates: { type: boolean }
        statusEvents: { $ref: '#/components/schemas/NotificationStatusEvents' }
        agingDays: { type: array, items: { type: integer, enum: [30, 60, 90] } }
        quietHours: { type: boolean }
        assignedBillIds: { type: array, items: { type: string } }
        eligible: { type: boolean }
        unsubscribedAt: { type: [string, 'null'], format: date-time }
        consentGrantedAt: { type: [string, 'null'], format: date-time }
        consentVersion: { type: [string, 'null'] }
    NotificationBillAssignmentResult:
      type: object
      required: [data]
      properties:
        data:
          type: object
          required: [externalUserId, billId, assigned]
          properties:
            externalUserId: { type: string }
            billId: { type: string }
            assigned: { type: boolean }
    SavedBillingProvider:
      type: object
      properties:
        id:
          type: string
        externalId:
          type: string
        name:
          type: string
        npi:
          type: string
        taxId:
          type: string
        phone:
          type: string
        billingStreet:
          type: string
        billingCity:
          type: string
        billingState:
          type: string
        billingZip:
          type: string
        billType:
          type: string
          enum:
          - Professional
          - Institutional
        taxIdType:
          type: string
          enum:
          - EIN
          - SSN
      additionalProperties: false
      required:
      - name
      - npi
      - billType
    SavedRenderingProvider:
      type: object
      properties:
        id:
          type: string
        externalId:
          type: string
        name:
          type: string
        npi:
          type: string
        specialty:
          type: string
        taxonomy:
          type: string
        licenseNumber:
          type: string
        licenseState:
          type: string
        email:
          type: string
        active:
          type: boolean
        isQME:
          type: boolean
        isAME:
          type: boolean
      additionalProperties: false
      required:
      - name
      - npi
    SavedLocation:
      type: object
      properties:
        id:
          type: string
        externalId:
          type: string
        name:
          type: string
        street:
          type: string
        city:
          type: string
        state:
          type: string
        zip:
          type: string
        billingProviderId:
          type: string
        nickname:
          type: string
        county:
          type: string
        posCode:
          type: string
        isPrimary:
          type: boolean
        active:
          type: boolean
      additionalProperties: false
      required:
      - name
      - street
      - city
      - state
      - zip
    PracticeIdentity:
      type: object
      properties:
        name:
          type: string
        legalName:
          type: string
        taxId:
          type: string
        npi:
          type: string
        phone:
          type: string
        email:
          type: string
        website:
          type: string
        taxIdType:
          type: string
          enum:
          - EIN
          - SSN
        posCodes:
          type: array
          items:
            type: object
            properties:
              code:
                type: string
              name:
                type: string
      additionalProperties: false
    BillingProfileWrite:
      type: object
      properties:
        practiceIdentity:
          $ref: '#/components/schemas/PracticeIdentity'
        billingProviders:
          type: array
          items:
            $ref: '#/components/schemas/SavedBillingProvider'
          minItems: 1
          maxItems: 50
        renderingProviders:
          type: array
          items:
            $ref: '#/components/schemas/SavedRenderingProvider'
          minItems: 1
          maxItems: 500
      minProperties: 1
      additionalProperties: false
    LocationsWrite:
      type: object
      properties:
        locations:
          type: array
          items:
            $ref: '#/components/schemas/SavedLocation'
          minItems: 1
          maxItems: 200
      additionalProperties: false
      required:
      - locations
    W9Write:
      type: object
      properties:
        filename:
          type: string
          pattern: \.[pP][dD][fF]$
          maxLength: 255
        contentBase64:
          type: string
          description: Base64 PDF. Decoded maximum 10 MiB; PDF magic bytes are validated.
          minLength: 100
          maxLength: 13981020
        taxYear:
          type: integer
          minimum: 2000
          maximum: 2100
      additionalProperties: false
      required:
      - filename
      - contentBase64
    OrganizationProfile:
      type: object
      properties:
        organizationId:
          type: string
        practiceIdentity:
          type: object
          properties: {}
          description: Practice identity; stored SSNs are masked with taxIdConfigured and taxIdLast4.
        billingProviders:
          type: array
          items:
            type: object
            properties: {}
            description: Saved billing provider; stored SSNs are masked.
        renderingProviders:
          type: array
          items:
            $ref: '#/components/schemas/SavedRenderingProvider'
        locations:
          type: array
          items:
            $ref: '#/components/schemas/SavedLocation'
        w9:
          type:
          - object
          - 'null'
          properties:
            filename:
              type: string
            addDate:
              type: string
            taxYear:
              type: integer
        onboarding:
          type: object
          properties:
            status:
              type:
              - string
              - 'null'
            complete:
              type: boolean
            checklist: {}
      required:
      - organizationId
      - billingProviders
      - renderingProviders
      - locations
      - w9
      - onboarding
    BillDashboardItem:
      type: object
      properties:
        id:
          type:
          - string
          - 'null'
        billNumber:
          type: integer
        externalId:
          type:
          - string
          - 'null'
        patientId: { type: [string, 'null'], description: Canonical patient filter ID. }
        claimsAdminId: { type: [string, 'null'], description: Canonical claims administrator filter ID. }
        renderingProviderId: { type: [string, 'null'], description: Canonical doctor filter ID, including an npi-prefixed fallback when returned. }
        patientName:
          type:
          - string
          - 'null'
        claimNumber:
          type:
          - string
          - 'null'
        claimsAdministrator:
          type:
          - string
          - 'null'
        dateOfService:
          type:
          - string
          - 'null'
        billingProviderId:
          type:
          - string
          - 'null'
        submittedAt:
          type:
          - string
          - 'null'
        procedureCodes:
          type: array
          items:
            type: string
        status:
          type: object
          properties:
            key:
              type: string
            label:
              type: string
            severity:
              type: string
            isAlert:
              type: boolean
        arAgeDays:
          type:
          - number
          - 'null'
        totalCharge:
          type: number
        totalPaid:
          type: number
        balanceDue:
          type: number
    BillDashboardPage:
      type: object
      properties:
        data:
          type: object
          properties:
            items:
              type: array
              items:
                $ref: '#/components/schemas/BillDashboardItem'
            total:
              type: integer
            balanceTotal:
              type: number
            page:
              type: integer
            pageSize:
              type: integer
            filters:
              type: object
              properties:
                renderingProviders:
                  type: array
                  description: All available doctors for this partner, organization, and environment, across the full authorized lifecycle scope, independent of pagination and current filters.
                  items:
                    type: object
                    required: [id, name]
                    properties:
                      id: { type: string }
                      name: { type: string }
                patients:
                  type: array
                  description: Available patients across the full authorized lifecycle scope, independent of pagination and current filters.
                  items:
                    type: object
                    required: [id, name]
                    properties:
                      id: { type: string }
                      name: { type: string }
                claimsAdministrators:
                  type: array
                  description: Available claims administrators across the full authorized lifecycle scope, independent of pagination and current filters.
                  items:
                    type: object
                    required: [id, name]
                    properties:
                      id: { type: string }
                      name: { type: string }
          required:
          - items
          - total
          - balanceTotal
          - page
          - pageSize
      required:
      - data
    DirectoryEntry:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
        hasElectronic:
          type: boolean
        states:
          type: array
          items:
            type: string
        confidence:
          type: string
          enum:
          - high
          - medium
          - directory
        recommended:
          type: boolean
        signals:
          type: array
          items:
            type: object
            properties:
              kind:
                type: string
              state:
                type: string
              label:
                type: string
        payers:
          type: array
          items:
            type: object
            properties:
              key:
                type: string
              label:
                type: string
              default:
                type: boolean
              active:
                type: boolean
              affiliatedEntities:
                type: array
                items:
                  type: string
              claimNumberPatterns:
                type: array
                items:
                  type: object
                  properties: {}
        payerSelectionRequired:
          type: boolean
        aliases:
          type: array
          items:
            type: string
        affiliatedEntities:
          type: array
          items:
            type: string
        claimNumberPatterns:
          type: array
          items:
            type: object
            properties: {}
    DirectorySearch:
      type: object
      properties:
        results:
          type: array
          items:
            $ref: '#/components/schemas/DirectoryEntry'
        recommendedId:
          type:
          - string
          - 'null'
        suggestions:
          type: array
          items:
            type: object
            properties: {}
        total:
          type: integer
        nextOffset:
          type: integer
      required:
      - results
      - recommendedId
      - suggestions
      - total
    DeliveryOptions:
      type: object
      properties:
        payerName:
          type: string
        recommended:
          type: object
          properties: {}
        options:
          type: array
          items:
            type: object
            properties:
              route:
                type: string
              label:
                type: string
              detail:
                type: string
              fallback:
                type: boolean
              confidence:
                type: string
              payerName:
                type: string
              target:
                type: string
              chKey:
                type: string
              payerId:
                type: string
              printAndMail:
                type: boolean
              costUsd:
                type: number
        contacts:
          type: object
          properties:
            faxNumber:
              type:
              - string
              - 'null'
            claimsEmail:
              type:
              - string
              - 'null'
            portalUrl:
              type:
              - string
              - 'null'
            mailingAddress:
              type:
              - string
              - 'null'
      required:
      - payerName
      - options
    CourtesyForwardRequest:
      type: object
      properties:
        mode:
          type: string
          enum:
          - preview
          - send
        to:
          type: array
          items:
            type: string
          maxItems: 20
        cc:
          type: array
          items:
            type: string
          maxItems: 20
          default: []
        subject:
          type: string
          maxLength: 200
        bodyText:
          type: string
          maxLength: 10000
        includeCms1500:
          type: boolean
          default: true
        documentIds:
          type: array
          items:
            type: string
          maxItems: 30
          default: []
        packetHash:
          type: string
          description: Required for send. Hash from the reviewed preview for this exact packet, recipients, and message.
          pattern: ^[a-f0-9]{64}$
      additionalProperties: false
      required:
      - mode
      - to
      - subject
      - bodyText
    CourtesyForwardResponse:
      oneOf:
      - type: object
        properties:
          filename:
            type: string
          documentCount:
            type: integer
          packetHash:
            type: string
          pdfBase64:
            type: string
          environment:
            type: string
        required:
        - filename
        - documentCount
        - packetHash
        - pdfBase64
        - environment
      - type: object
        properties:
          ok:
            type: boolean
          sent:
            type: boolean
          messageId:
            type: string
          simulated:
            type: boolean
          dryRun:
            type: boolean
        required:
        - ok
        - sent
    ProvisionOrganizationRequest:
      type: object
      properties:
        externalId:
          type: string
          minLength: 1
          maxLength: 255
        name:
          type: string
          minLength: 1
          maxLength: 200
        accessMode:
          type: string
          enum:
          - managed
          - invite
          default: managed
          description: Legacy invite input is accepted with adminName and adminEmail; this endpoint provisions managed
            access.
        practiceIdentity:
          $ref: '#/components/schemas/PracticeIdentity'
        billingProviders:
          type: array
          items:
            type: object
            properties:
              id:
                type: string
              externalId:
                type: string
              name:
                type: string
              npi:
                type: string
              taxId:
                type: string
              phone:
                type: string
              billingStreet:
                type: string
              billingCity:
                type: string
              billingState:
                type: string
              billingZip:
                type: string
              billType:
                type: string
                enum:
                - Professional
                - Institutional
              taxIdType:
                type: string
                enum:
                - EIN
                - SSN
            additionalProperties: false
            required:
            - id
            - name
            - npi
            - taxId
            - billType
          maxItems: 100
        renderingProviders:
          type: array
          items:
            $ref: '#/components/schemas/SavedRenderingProvider'
          maxItems: 500
        locations:
          type: array
          items:
            $ref: '#/components/schemas/SavedLocation'
          maxItems: 500
        adminName:
          type: string
          minLength: 1
          maxLength: 200
        adminEmail:
          type: string
          format: email
      additionalProperties: false
      required:
      - externalId
      - name
    ProvisionOrganizationResponse:
      type: object
      properties:
        organizationId:
          type: string
        externalId:
          type: string
        name:
          type: string
        status:
          type: string
        accessMode:
          const: managed
        created:
          type: boolean
    ManagementSessionRequest:
      type: object
      properties:
        subject:
          type: string
          minLength: 1
          maxLength: 255
        role:
          type: string
          enum:
          - biller
          - viewer
          default: biller
        expiresIn:
          type: integer
          minimum: 60
          maximum: 900
          default: 300
      required:
      - subject
      additionalProperties: false
    ManagementSessionResponse:
      type: object
      properties:
        url:
          type: string
          format: uri
        expiresAt:
          type: string
          format: date-time
        organizationId:
          type: string
        subject:
          type: string
        role:
          type: string
          enum:
          - biller
          - viewer
    RfaDeliveryPreviewRequest:
      oneOf:
        - type: object
          additionalProperties: false
          required: [ channel, documentIds, to ]
          properties:
            channel: { type: string, const: fax }
            to: { type: string, pattern: '^\+[1-9]\d{7,14}$', description: Verified authorization fax in E.164 format. }
            recipientName: { type: string, minLength: 1, maxLength: 200, description: Optional trimmed recipient or adjuster name printed on the cover. Must match the reviewed preview at submission. }
            message: { type: string, maxLength: 1000, default: '', description: Optional trimmed message printed on the cover and used as the email body. Must match the preview at submission. }
            documentIds: { type: array, minItems: 2, maxItems: 100, uniqueItems: true, items: { type: string, minLength: 1 } }
        - type: object
          additionalProperties: false
          required: [ channel, documentIds, to ]
          properties:
            channel: { type: string, const: email }
            to: { type: string, format: email, maxLength: 254, description: Verified authorization email; trimmed and normalized to lowercase. }
            recipientName: { type: string, minLength: 1, maxLength: 200, description: Optional trimmed recipient or adjuster name printed on the cover. Must match the reviewed preview at submission. }
            message: { type: string, maxLength: 1000, default: '', description: Optional trimmed message printed on the cover and used as the email body. Must match the preview at submission. }
            documentIds: { type: array, minItems: 2, maxItems: 100, uniqueItems: true, items: { type: string, minLength: 1 } }
        - type: object
          additionalProperties: false
          required: [ channel, documentIds ]
          properties:
            channel: { type: string, const: download }
            recipientName: { type: string, minLength: 1, maxLength: 200, description: Optional trimmed recipient or adjuster name printed on the cover. Must match the reviewed preview at submission. }
            message: { type: string, maxLength: 1000, default: '', description: Optional trimmed message printed on the cover and used as the email body. Must match the preview at submission. }
            documentIds: { type: array, minItems: 2, maxItems: 100, uniqueItems: true, items: { type: string, minLength: 1 } }
    RfaDeliverySubmitRequest:
      oneOf:
        - type: object
          additionalProperties: false
          required: [ channel, packetId, sha256, to ]
          properties:
            channel: { type: string, const: fax }
            to: { type: string, pattern: '^\+[1-9]\d{7,14}$', description: Verified authorization fax in E.164 format. }
            recipientName: { type: string, minLength: 1, maxLength: 200, description: Optional trimmed recipient or adjuster name printed on the cover. Must match the reviewed preview at submission. }
            message: { type: string, maxLength: 1000, default: '', description: Optional trimmed message printed on the cover and used as the email body. Must match the preview at submission. }
            packetId: { type: string, minLength: 1, maxLength: 100 }
            sha256: { type: string, pattern: '^[a-f0-9]{64}$' }
            nonBusinessDates: { type: array, maxItems: 366, default: [], items: { type: string, pattern: '^\d{4}-\d{2}-\d{2}$' } }
        - type: object
          additionalProperties: false
          required: [ channel, packetId, sha256, to ]
          properties:
            channel: { type: string, const: email }
            to: { type: string, format: email, maxLength: 254, description: Verified authorization email; trimmed and normalized to lowercase. }
            recipientName: { type: string, minLength: 1, maxLength: 200, description: Optional trimmed recipient or adjuster name printed on the cover. Must match the reviewed preview at submission. }
            message: { type: string, maxLength: 1000, default: '', description: Optional trimmed message printed on the cover and used as the email body. Must match the preview at submission. }
            packetId: { type: string, minLength: 1, maxLength: 100 }
            sha256: { type: string, pattern: '^[a-f0-9]{64}$' }
            nonBusinessDates: { type: array, maxItems: 366, default: [], items: { type: string, pattern: '^\d{4}-\d{2}-\d{2}$' } }
    RfaDeliveryPreviewEnvelope:
      type: object
      additionalProperties: false
      required: [ data ]
      properties:
        data:
          type: object
          additionalProperties: false
          required: [ packetId, sha256, contentRevision ]
          properties:
            packetId: { type: string }
            sha256: { type: string, pattern: '^[a-f0-9]{64}$' }
            contentRevision: { type: integer, minimum: 1 }
    RfaDeliverySubmitEnvelope:
      type: object
      additionalProperties: false
      required: [ data ]
      properties:
        data:
          type: object
          additionalProperties: false
          required: [ transmissionId, packetId ]
          properties:
            transmissionId: { type: string }
            packetId: { type: string }
    RfaProviderSignatureRequest:
      type: object
      additionalProperties: false
      required: [contentBase64, physicianAuthorized, actorReference]
      properties:
        contentBase64:
          type: string
          minLength: 1
          maxLength: 699052
          description: Canonical base64 PNG without a data-URL prefix. Decoded content is limited to 512 KiB, 4096 pixels per dimension and four million pixels total.
        physicianAuthorized: { type: boolean, const: true }
        actorReference: { type: string, minLength: 1, maxLength: 200 }
