@mindbill/browser 0.43.2 → 0.43.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +11 -4
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1303,6 +1303,15 @@ type CaTherapyContext = {
|
|
|
1303
1303
|
globalPeriodApplies: boolean;
|
|
1304
1304
|
hpsaBonusEligible: boolean;
|
|
1305
1305
|
};
|
|
1306
|
+
/** Documented interpretation and imaging-session facts; an omitted completeness fact remains unknown. */
|
|
1307
|
+
type CaProfessionalComponentContext = {
|
|
1308
|
+
interpretationLocation: "same_as_patient_service" | "different_from_patient_service";
|
|
1309
|
+
supervisionLevel?: "general" | "direct" | "personal";
|
|
1310
|
+
/** Actual session label, 1–64 letters/digits/._:-, beginning with a letter or digit. Never a patient identifier. */
|
|
1311
|
+
imagingSessionReference?: string;
|
|
1312
|
+
/** All imaging for this patient/provider group/date is included, including separately billed services. */
|
|
1313
|
+
completeSameDayImagingServices?: boolean;
|
|
1314
|
+
};
|
|
1306
1315
|
type BillFeeQuoteInput = {
|
|
1307
1316
|
drug?: BilledDrug;
|
|
1308
1317
|
padbContext?: CaPadbContext;
|
|
@@ -1319,9 +1328,7 @@ type BillFeeQuoteInput = {
|
|
|
1319
1328
|
hasFeeAgreement?: boolean;
|
|
1320
1329
|
serviceZip?: string;
|
|
1321
1330
|
/** Explicit physical interpretation location for a professional component. */
|
|
1322
|
-
professionalComponentContext?:
|
|
1323
|
-
interpretationLocation: "same_as_patient_service" | "different_from_patient_service";
|
|
1324
|
-
};
|
|
1331
|
+
professionalComponentContext?: CaProfessionalComponentContext;
|
|
1325
1332
|
/** California equipment pricing uses worker residence, independently of service location. */
|
|
1326
1333
|
dmeposContext?: {
|
|
1327
1334
|
residenceZip: string;
|
|
@@ -1933,4 +1940,4 @@ type RfaClient = {
|
|
|
1933
1940
|
/** Uses short-lived browser credentials. Never pass a partner API key. */
|
|
1934
1941
|
declare function createRfaClient({ sessionEndpoint, getSession, apiBaseUrl, fetch: fetchOverride }?: OrganizationClientOptions): RfaClient;
|
|
1935
1942
|
|
|
1936
|
-
export { type AddBillNoteInput, BILL_FEE_QUOTE_BASES, BILL_TASKS_AGING_BUCKETS, type BillActivityRecord, type BillActorInput, type BillAttemptSummary, type BillClaimsAdministratorAuthorizationStatus, type BillClaimsAdministratorContact, type BillClaimsAdministratorDirectory, type BillClaimsAdministratorMailingAddress, type BillClaimsAdministratorPattern, type BillClaimsAdministratorPayer, type BillClaimsAdministratorSource, type BillCourtesyCopyInput, type BillCourtesyCopyPreview, type BillCourtesyCopyResult, type BillDeliveryOption, type BillDeliveryOptions, type BillDeliveryPreviewInput, type BillDiagnosisCode, type BillEorDocument, type BillFeeContext, type BillFeeQuote, type BillFeeQuoteBasis, type BillFeeQuoteInput, type BillFeeSource, type BillHistoryEntry, type BillLifecycleAction, type BillLifecycleActionId, type BillLifecycleClient, type BillLifecycleClientOptions, type BillLifecycleData, type BillLifecycleDelivery, type BillLifecycleSession, type BillLifecycleSessionProvider, type BillLifecycleSessionRequest, type BillPaymentRecord, type BillPostalPlace, type BillProcedureCodePage, type BillProcedureCodeSearchInput, type BillReferenceClient, type BillReferenceClientOptions, type BillRejection, type BillRejectionIssue, type BillRemittanceSummary, type BillReviewAttachment, type BillReviewBillingProvider, type BillReviewClaimPatternStatus, type BillReviewClinician, type BillReviewData, type BillReviewDocumentType, type BillReviewFeatures, type BillReviewLineItem, type BillReviewLocation, type BillReviewPayer, type BillReviewPayerListInput, type BillReviewPayerOption, type BillReviewPayerPage, type BillReviewPayerSuggestion, type BillReviewSaveInput, type BillSubmissionClient, type BillSubmissionClientOptions, type BillSubmissionDetail, type BillSubmissionRoute, type BillTasksAgingBucket, type BillTasksDashboardData, type BillTasksDashboardItem, type BillTasksDashboardRow, type BillTasksDashboardSection, type BillTasksDashboardSectionInput, type BillTasksDashboardTone, type BillTeamNote, type BilledDrug, type BrowserBillAddress, type BrowserBillCreateInput, type BrowserBillSubmissionDocument, type BrowserBillSubmissionInput, type BrowserBillSubmissionResult, type BrowserSubmittedBill, type CaAnesthesiaContext, type CaAnesthesiaEvent, type CaAnesthesiaInterval, type CaAnesthesiaOptionalParticipation, type CaAnesthesiaParticipation, type CaClaimEditFinding, type CaClaimFeeFinding, type CaClaimFeeQuoteInput, type CaClaimFeeQuoteResult, type CaClaimLineQuote, type CaFeeCalculation, type CaFeeCitation, type CaMedicalDirection, type CaMedicalDirectionCase, type CaMonitoredAnesthesiaCare, type CaPadbContext, type CaTherapyContext, type CloseBillInput, type CorrectionDraft, DEFAULT_API_BASE_URL, DEFAULT_SESSION_ENDPOINT, type HistoricalBillReviewData, type OrganizationBillingProviderInput, type OrganizationChecklistItem, type OrganizationClaimsAdministrator, type OrganizationClaimsAdministratorInput, type OrganizationClient, type OrganizationClientOptions, type OrganizationLocationInput, type OrganizationPracticeIdentity, type OrganizationProfileData, type OrganizationRenderingProviderInput, type OrganizationTeam, type OrganizationTeamMember, type OrganizationTeamRole, type PostBillPaymentInput, REPORT_BILL_STATUS_OPTIONS, type ReopenBillInput, type ReportAutofillClient, type ReportAutofillField, type ReportAutofillMatch, type ReportAutofillResult, type ReportBillStatusActionInput, type ReportBillStatusContacts, type ReportBillStatusId, type ReportBillStatusInput, type ReportBillStatusOption, type ResubmitBillInput, type RfaAuthorizationDestinationOption, type RfaClient, type RfaCreateDraftInput, type RfaCreationClaim, type RfaCreationContext, type RfaCreationContextQuery, type RfaCreationProvider, type RfaDecisionsInput, type RfaFaxInput, type RfaFollowUp, type RfaFollowUpList, type RfaFollowUpUpdate, type RfaInformationRequestInput, type RfaInformationResponseInput, type RfaLifecycleClient, type RfaListQuery, type RfaListResult, type RfaReceiptInput, type RfaRecord, type RfaSignInput, type RfaSigningPreview, type RfaSigningPreviewInput, type RfaTreatmentDecisionInput, type RfaUpdateDraftInput, type RfaUploadDocumentInput, SECOND_REVIEW_REASON_TEMPLATE, SECOND_REVIEW_WINDOW_DAYS, type SandboxSimulationScenario, type SecondReviewDeadline, type SecondReviewLineInput, type SendDuplicateBillInput, type SimulateSandboxBillInput, type SubmitBillInput, type SubmitNewBillInput, type SubmitSecondReviewInput, billTasksAgingBucketIndex, buildBillTasksDashboard, createBillLifecycleClient, createBillReferenceClient, createBillSubmissionClient, createOrganizationClient, createReportAutofillClient, createRfaClient, createRfaLifecycleClient, defaultBillReviewPayerOption, normalizeRfaFax, organizationTaxIdWrite, parseSecondReviewCorrection, reportBillStatusContacts, rfaAuthorizationDestinations, rfaAuthorizationGuidance, sanitizeBillReviewSaveInput, secondReviewDeadline };
|
|
1943
|
+
export { type AddBillNoteInput, BILL_FEE_QUOTE_BASES, BILL_TASKS_AGING_BUCKETS, type BillActivityRecord, type BillActorInput, type BillAttemptSummary, type BillClaimsAdministratorAuthorizationStatus, type BillClaimsAdministratorContact, type BillClaimsAdministratorDirectory, type BillClaimsAdministratorMailingAddress, type BillClaimsAdministratorPattern, type BillClaimsAdministratorPayer, type BillClaimsAdministratorSource, type BillCourtesyCopyInput, type BillCourtesyCopyPreview, type BillCourtesyCopyResult, type BillDeliveryOption, type BillDeliveryOptions, type BillDeliveryPreviewInput, type BillDiagnosisCode, type BillEorDocument, type BillFeeContext, type BillFeeQuote, type BillFeeQuoteBasis, type BillFeeQuoteInput, type BillFeeSource, type BillHistoryEntry, type BillLifecycleAction, type BillLifecycleActionId, type BillLifecycleClient, type BillLifecycleClientOptions, type BillLifecycleData, type BillLifecycleDelivery, type BillLifecycleSession, type BillLifecycleSessionProvider, type BillLifecycleSessionRequest, type BillPaymentRecord, type BillPostalPlace, type BillProcedureCodePage, type BillProcedureCodeSearchInput, type BillReferenceClient, type BillReferenceClientOptions, type BillRejection, type BillRejectionIssue, type BillRemittanceSummary, type BillReviewAttachment, type BillReviewBillingProvider, type BillReviewClaimPatternStatus, type BillReviewClinician, type BillReviewData, type BillReviewDocumentType, type BillReviewFeatures, type BillReviewLineItem, type BillReviewLocation, type BillReviewPayer, type BillReviewPayerListInput, type BillReviewPayerOption, type BillReviewPayerPage, type BillReviewPayerSuggestion, type BillReviewSaveInput, type BillSubmissionClient, type BillSubmissionClientOptions, type BillSubmissionDetail, type BillSubmissionRoute, type BillTasksAgingBucket, type BillTasksDashboardData, type BillTasksDashboardItem, type BillTasksDashboardRow, type BillTasksDashboardSection, type BillTasksDashboardSectionInput, type BillTasksDashboardTone, type BillTeamNote, type BilledDrug, type BrowserBillAddress, type BrowserBillCreateInput, type BrowserBillSubmissionDocument, type BrowserBillSubmissionInput, type BrowserBillSubmissionResult, type BrowserSubmittedBill, type CaAnesthesiaContext, type CaAnesthesiaEvent, type CaAnesthesiaInterval, type CaAnesthesiaOptionalParticipation, type CaAnesthesiaParticipation, type CaClaimEditFinding, type CaClaimFeeFinding, type CaClaimFeeQuoteInput, type CaClaimFeeQuoteResult, type CaClaimLineQuote, type CaFeeCalculation, type CaFeeCitation, type CaMedicalDirection, type CaMedicalDirectionCase, type CaMonitoredAnesthesiaCare, type CaPadbContext, type CaProfessionalComponentContext, type CaTherapyContext, type CloseBillInput, type CorrectionDraft, DEFAULT_API_BASE_URL, DEFAULT_SESSION_ENDPOINT, type HistoricalBillReviewData, type OrganizationBillingProviderInput, type OrganizationChecklistItem, type OrganizationClaimsAdministrator, type OrganizationClaimsAdministratorInput, type OrganizationClient, type OrganizationClientOptions, type OrganizationLocationInput, type OrganizationPracticeIdentity, type OrganizationProfileData, type OrganizationRenderingProviderInput, type OrganizationTeam, type OrganizationTeamMember, type OrganizationTeamRole, type PostBillPaymentInput, REPORT_BILL_STATUS_OPTIONS, type ReopenBillInput, type ReportAutofillClient, type ReportAutofillField, type ReportAutofillMatch, type ReportAutofillResult, type ReportBillStatusActionInput, type ReportBillStatusContacts, type ReportBillStatusId, type ReportBillStatusInput, type ReportBillStatusOption, type ResubmitBillInput, type RfaAuthorizationDestinationOption, type RfaClient, type RfaCreateDraftInput, type RfaCreationClaim, type RfaCreationContext, type RfaCreationContextQuery, type RfaCreationProvider, type RfaDecisionsInput, type RfaFaxInput, type RfaFollowUp, type RfaFollowUpList, type RfaFollowUpUpdate, type RfaInformationRequestInput, type RfaInformationResponseInput, type RfaLifecycleClient, type RfaListQuery, type RfaListResult, type RfaReceiptInput, type RfaRecord, type RfaSignInput, type RfaSigningPreview, type RfaSigningPreviewInput, type RfaTreatmentDecisionInput, type RfaUpdateDraftInput, type RfaUploadDocumentInput, SECOND_REVIEW_REASON_TEMPLATE, SECOND_REVIEW_WINDOW_DAYS, type SandboxSimulationScenario, type SecondReviewDeadline, type SecondReviewLineInput, type SendDuplicateBillInput, type SimulateSandboxBillInput, type SubmitBillInput, type SubmitNewBillInput, type SubmitSecondReviewInput, billTasksAgingBucketIndex, buildBillTasksDashboard, createBillLifecycleClient, createBillReferenceClient, createBillSubmissionClient, createOrganizationClient, createReportAutofillClient, createRfaClient, createRfaLifecycleClient, defaultBillReviewPayerOption, normalizeRfaFax, organizationTaxIdWrite, parseSecondReviewCorrection, reportBillStatusContacts, rfaAuthorizationDestinations, rfaAuthorizationGuidance, sanitizeBillReviewSaveInput, secondReviewDeadline };
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/claim-fees.ts","../src/rfa-directory.ts","../src/second-review-corrections.ts","../src/rfa-lifecycle.ts","../src/report-autofill.ts","../src/index.ts"],"sourcesContent":["import type { BillFeeQuoteInput, BillFeeQuoteBasis } from \"./index\";\n\n/** One patient's complete services for one provider/group. Dates are service dates, not publication dates. */\nexport type CaClaimFeeQuoteInput = {\n lines: Array<Omit<BillFeeQuoteInput, \"billingProviderId\" | \"payerId\" | \"physicianContext\"> & {\n id: string;\n serviceCounty?: string;\n physicianContext?: Omit<NonNullable<BillFeeQuoteInput[\"physicianContext\"]>, \"providerKind\"> & {\n providerKind: NonNullable<BillFeeQuoteInput[\"physicianContext\"]>[\"providerKind\"] | \"clinical_social_worker\";\n telehealthModality?: \"audio_video\" | \"audio_only\";\n cmsSpecialtyCode?: string;\n };\n }>;\n completeDateOfServiceContext: boolean;\n ordinaryMultipleSurgeryContext?: boolean;\n};\nexport type CaFeeCitation = { id: string; url: string; sha256?: string; effectiveFrom?: string; effectiveThrough?: string };\nexport type CaFeeCalculation = {\n method: \"rbrvs\" | \"therapy_mppr\"; locality: string; serviceZip?: string; serviceCounty?: string;\n setting: \"facility\" | \"nonfacility\"; units: number; conversionFactor: string; providerPercent: number;\n baseMaximumCents?: number; cmsIndicators?: Record<string, string>;\n sourceFiles?: Array<{ kind: string; filename: string }>;\n components: Array<{ name: string; rvu: string; gpci: string; payableUnits: number }>;\n rounding: string;\n};\nexport type CaClaimEditFinding = {\n type: string; lineIds: string[]; message: string; citationUrl: string;\n column1?: string; column2?: string; modifierIndicator?: number; code?: string; limit?: number;\n submittedUnits?: number; adjudicationIndicator?: number; scope?: \"line\" | \"patient_provider_date\";\n};\nexport type CaClaimFeeFinding = { code: string; lineIds: string[]; message: string; citationUrl?: string; edit?: CaClaimEditFinding };\nexport type CaClaimLineQuote = ({ status: \"priced\"; amountCents: number; scheduleMaximumCents: number;\n basis: BillFeeQuoteBasis | \"ca_ambulance\"; notes: string[];\n feeBreakdown?: { method: string; inputs: Array<{ label: string; value: string }>; steps: Array<{ label: string; value: string }> };\n} | { status: \"requires_review\" | \"not_separately_payable\"; reason: string }) & {\n provenance: CaFeeCitation[]; calculation?: CaFeeCalculation;\n};\nexport type CaClaimFeeQuoteResult = {\n status: \"priced\" | \"requires_review\" | \"not_separately_payable\";\n lines: Array<{ id: string; input: CaClaimFeeQuoteInput[\"lines\"][number]; quote: CaClaimLineQuote;\n assessment: CaClaimFeeQuoteResult[\"status\"]; findings: CaClaimFeeFinding[];\n paymentAdjustment?: { rule: \"ca_multiple_surgery\"; rank: number; percent: 100 | 50;\n unadjustedScheduleMaximumCents: number; scheduleMaximumCents: number; amountCents: number; citationUrl: string };\n }>;\n totals: { submittedChargeCents: number | null; pricedSubtotalCents: number;\n estimatedPayableCents: number | null; scheduleMaximumCents: number | null; reviewLineCount: number };\n claimEdits: Array<{ dateOfService: string; lineIds: string[]; status: \"evaluated\" | \"requires_review\" | \"source_unavailable\" | \"not_applicable\";\n reason?: string; findings: CaClaimEditFinding[]; provenance?: unknown;\n supportedDateRange?: { from: string; through: string }; supportedDateIntervals?: Array<{ from: string; through: string }>;\n }>;\n limitations: string[];\n};\n\nconst record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === \"object\" && !Array.isArray(v);\nconst strings = (v: unknown): v is string[] => Array.isArray(v) && v.every((x) => typeof x === \"string\");\nconst money = (v: unknown) => Number.isSafeInteger(v) && (v as number) >= 0;\nconst status = (v: unknown) => [\"priced\", \"requires_review\", \"not_separately_payable\"].includes(v as string);\nconst finding = (v: unknown) => record(v) && typeof v.message === \"string\" && strings(v.lineIds) && (v.citationUrl === undefined || typeof v.citationUrl === \"string\");\n/** Validate the transport before a browser displays an allowance. Unknown/partial results fail closed. */\nexport function parseCaClaimFeeQuote(value: unknown, input: CaClaimFeeQuoteInput): CaClaimFeeQuoteResult {\n const invalid = () => { throw new Error(\"Claim fee quote returned an invalid response.\"); };\n if (!record(value) || !status(value.status) || !Array.isArray(value.lines) || value.lines.length !== input.lines.length || !strings(value.limitations) || !record(value.totals) || !Array.isArray(value.claimEdits)) return invalid();\n const totals = value.totals;\n if (!money(totals.pricedSubtotalCents) || !money(totals.reviewLineCount) || [totals.submittedChargeCents, totals.estimatedPayableCents, totals.scheduleMaximumCents].some((v) => v !== null && !money(v))) return invalid();\n if (value.status === \"requires_review\" && totals.estimatedPayableCents !== null) return invalid();\n const expected = new Set(input.lines.map((line) => line.id));\n for (const line of value.lines) {\n if (!record(line) || typeof line.id !== \"string\" || !expected.delete(line.id) || !record(line.input) || typeof line.input.code !== \"string\" || line.input.id !== line.id || line.input.code !== input.lines.find((r) => r.id === line.id)?.code || line.input.dateOfService !== input.lines.find((r) => r.id === line.id)?.dateOfService || !status(line.assessment) || !record(line.quote) || !Array.isArray(line.findings) || !line.findings.every(finding)) return invalid();\n const quote = line.quote;\n if (!status(quote.status) || !Array.isArray(quote.provenance) || !quote.provenance.every((s) => record(s) && typeof s.id === \"string\" && typeof s.url === \"string\" && (s.effectiveFrom === undefined || typeof s.effectiveFrom === \"string\") && (s.effectiveThrough === undefined || typeof s.effectiveThrough === \"string\"))) return invalid();\n if (quote.status === \"priced\") {\n if (!money(quote.amountCents) || !money(quote.scheduleMaximumCents) || typeof quote.basis !== \"string\" || !strings(quote.notes)) return invalid();\n } else if (typeof quote.reason !== \"string\") return invalid();\n if (quote.calculation !== undefined) {\n const c = quote.calculation;\n if (!record(c) || typeof c.locality !== \"string\" || typeof c.conversionFactor !== \"string\" || !Number.isFinite(c.providerPercent) || ![\"facility\", \"nonfacility\"].includes(c.setting as string) || (c.sourceFiles !== undefined && (!Array.isArray(c.sourceFiles) || !c.sourceFiles.every((f) => record(f) && typeof f.kind === \"string\" && typeof f.filename === \"string\"))) || (c.cmsIndicators !== undefined && (!record(c.cmsIndicators) || !Object.values(c.cmsIndicators).every((v) => typeof v === \"string\"))) || !Array.isArray(c.components) || !c.components.every((r) => record(r) && typeof r.name === \"string\" && typeof r.rvu === \"string\" && typeof r.gpci === \"string\" && typeof r.payableUnits === \"number\")) return invalid();\n }\n if (quote.feeBreakdown !== undefined) {\n const b = quote.feeBreakdown;\n if (!record(b) || ![b.inputs, b.steps].every((rows) => Array.isArray(rows) && rows.every((r) => record(r) && typeof r.label === \"string\" && typeof r.value === \"string\"))) return invalid();\n }\n if (line.paymentAdjustment !== undefined) {\n const a = line.paymentAdjustment;\n if (!record(a) || !money(a.amountCents) || !money(a.scheduleMaximumCents) || !money(a.unadjustedScheduleMaximumCents) || typeof a.citationUrl !== \"string\" || ![100,50].includes(a.percent as number) || !money(a.rank)) return invalid();\n }\n }\n if (!value.claimEdits.every((edit) => record(edit) && typeof edit.dateOfService === \"string\" && strings(edit.lineIds) && [\"evaluated\", \"requires_review\", \"source_unavailable\", \"not_applicable\"].includes(edit.status as string) && Array.isArray(edit.findings) && edit.findings.every(finding) && (edit.reason === undefined || typeof edit.reason === \"string\"))) return invalid();\n return value as unknown as CaClaimFeeQuoteResult;\n}\n","import type { BillClaimsAdministratorDirectory } from \"./index\";\n\nexport type RfaAuthorizationDestinationOption = {\n method: \"fax\" | \"email\";\n destination: string;\n label: string;\n phone?: string;\n};\n\n/** Accept fax numbers only, never telephone notes, email addresses, or extensions. */\nexport function normalizeRfaFax(value: string): string | null {\n const input = value.trim();\n if (/^\\+[1-9]\\d{7,14}$/.test(input)) return input;\n if (!/^\\+?[\\d ().-]+$/.test(input)) return null;\n const digits = input.replace(/\\D/g, \"\");\n if (digits.length === 10 && !input.startsWith(\"+\")) return `+1${digits}`;\n return digits.length === 11 && digits.startsWith(\"1\") ? `+${digits}` : null;\n}\n\n/** Returns choices only. Selecting or transmitting a destination is a separate user action. */\nexport function rfaAuthorizationDestinations(directory: BillClaimsAdministratorDirectory | null): RfaAuthorizationDestinationOption[] {\n if (!directory || [\"adjuster_specific_required\", \"daisybill_unverified\", \"profile_not_published\"].includes(directory.authorizationStatus ?? \"\")) return [];\n return (directory.authorization ?? []).flatMap((contact) => {\n const common = { label: contact.location || contact.name || \"Authorization department\", ...(contact.phone ? { phone: contact.phone } : {}) };\n const options: RfaAuthorizationDestinationOption[] = [];\n const fax = contact.fax ? normalizeRfaFax(contact.fax) : null;\n if (fax && contact.method !== \"email\") options.push({ ...common, method: \"fax\", destination: fax });\n if (contact.email?.trim() && contact.method !== \"fax\") options.push({ ...common, method: \"email\", destination: contact.email.trim() });\n return options;\n });\n}\n\nexport function rfaAuthorizationGuidance(directory: BillClaimsAdministratorDirectory | null): string {\n switch (directory?.authorizationStatus) {\n case \"central_fax\": return \"Select the central authorization fax after confirming it applies to this claim.\";\n case \"central_email\": return \"Authorization is routed by email. Download the signed packet and record delivery after sending it through your email service.\";\n case \"claim_handling_location_routes\": return \"Choose the office handling this claim. Authorization destinations vary by office.\";\n case \"adjuster_specific_required\": return \"Obtain the authorization destination from the handling adjuster.\";\n case \"daisybill_unverified\": return \"The directory has not verified an authorization destination. Confirm it with the handling adjuster.\";\n case \"profile_not_published\": return \"No authorization destination is currently published. Confirm a current destination with the handling adjuster.\";\n default: return \"Select an authorization contact or enter a fax confirmed with the handling adjuster.\";\n }\n}\n","import type { SecondReviewLineInput } from \"./index\";\n\nexport type CorrectionDraft = {\n correctBilling: boolean;\n units: string;\n modifiers: string;\n charge: string;\n chargeReviewed: boolean;\n};\n\nexport function parseSecondReviewCorrection(draft: CorrectionDraft): SecondReviewLineInput[\"correction\"] {\n if (!draft.correctBilling) return undefined;\n const units = Number(draft.units);\n const charge = Number(draft.charge);\n const modifiers = draft.modifiers.trim().toUpperCase().split(/[\\s,]+/).filter(Boolean);\n if (!draft.units.trim() || !Number.isInteger(units) || units < 1 || units > 10_000) {\n throw new Error(\"Corrected units must be a whole number from 1 to 10,000.\");\n }\n if (modifiers.length > 4 || new Set(modifiers).size !== modifiers.length || modifiers.some((value) => !/^[A-Z0-9]{2}$/.test(value))) {\n throw new Error(\"Enter up to four unique two-character modifiers, separated by commas. Leave blank to remove modifiers.\");\n }\n if (!draft.charge.trim() || !Number.isFinite(charge) || charge < 0 || charge > 999_999.99 || Math.abs(charge * 100 - Math.round(charge * 100)) > 0.000001) {\n throw new Error(\"Enter the corrected charge in dollars and cents.\");\n }\n if (!draft.chargeReviewed) throw new Error(\"Confirm that you reviewed the corrected charge. It is not recalculated automatically.\");\n return { units, modifiers, charge };\n}\n","import type { BillLifecycleSession, OrganizationClientOptions, RfaRecord } from \"./index\";\n\nexport type RfaReceiptInput = {\n channel: \"fax\" | \"email\" | \"edi\" | \"portal\" | \"mail\" | \"manual\";\n receivedAt: string;\n proofDocumentId?: string;\n providerMessageId?: string;\n};\nexport type RfaInformationRequestInput = { requestedAt: string; requestText: string; dueAt?: string };\nexport type RfaInformationResponseInput = { respondedAt: string; responseDocumentIds: string[] };\nexport type RfaTreatmentDecisionInput = {\n itemId: string; outcome: \"approved\" | \"modified\" | \"denied\";\n authorizationNumber?: string; authorizedProcedureCode?: string; authorizedQuantity?: number; authorizedUnits?: number;\n effectiveFrom?: string; effectiveTo?: string; decisionReason?: string; reviewerName?: string; reviewerPhone?: string;\n};\nexport type RfaDecisionsInput = { decidedAt: string; responseDocumentId: string; imrDocumentId?: string; decisions: RfaTreatmentDecisionInput[] };\nexport type RfaFollowUp = {\n id: string; rfaId: string; claimId: string; responseDocumentId: string | null; responseFilename: string | null;\n kind: string; status: string; dueAt: string; assigneeReference: string | null; snoozedUntil: string | null;\n lastOutcome: string | null; lastNote: string | null; createdAt: string; updatedAt: string; resolvedAt: string | null;\n};\nexport type RfaFollowUpUpdate = {\n assigneeReference?: string | null; snoozedUntil?: string | null;\n outcome?: \"message_left\" | \"decision_pending\" | \"decision_issued\" | \"not_on_file\" | \"reviewed\";\n note?: string;\n responseReview?: { disposition: \"no_new_decision\"; noNewDecisionConfirmed: true } | { disposition: \"decisions_recorded\"; allDecisionsRecordedConfirmed: true };\n};\nexport type RfaFollowUpList = { data: RfaFollowUp[]; nextCursor: string | null };\nexport type RfaLifecycleClient = {\n recordReceipt(id: string, input: RfaReceiptInput, idempotencyKey: string): Promise<RfaRecord>;\n recordInformationRequest(id: string, input: RfaInformationRequestInput, idempotencyKey: string): Promise<RfaRecord>;\n recordInformationResponse(id: string, requestId: string, input: RfaInformationResponseInput, idempotencyKey: string): Promise<RfaRecord>;\n recordDecisions(id: string, input: RfaDecisionsInput, idempotencyKey: string): Promise<RfaRecord>;\n listFollowUps(query?: { claimId?: string; includeResolved?: boolean; limit?: number; cursor?: string }): Promise<RfaFollowUpList>;\n updateFollowUp(id: string, input: RfaFollowUpUpdate, idempotencyKey: string): Promise<RfaFollowUp>;\n clearSession(): void;\n};\n/** Records clinical workflow evidence. These methods never send faxes or reconcile notification queues. */\nexport function createRfaLifecycleClient({ sessionEndpoint = \"/api/mindbill/session\", getSession, apiBaseUrl = \"https://app.mindbill.org\", fetch: fetchOverride }: OrganizationClientOptions = {}): RfaLifecycleClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n let pending: Promise<BillLifecycleSession> | null = null;\n const failure = async (response: Response): Promise<Error> => {\n const body = await response.json().catch(() => null) as { detail?: unknown; message?: unknown } | null;\n const detail = body?.detail ?? body?.message;\n return new Error(typeof detail === \"string\" ? detail : `The RFA request failed (${response.status}).`);\n };\n const mint = (force = false): Promise<BillLifecycleSession> => {\n if (!force && session && (!session.expiresAt || Date.parse(session.expiresAt) > Date.now() + 30_000)) return Promise.resolve(session);\n if (pending) return pending;\n pending = (async () => {\n const value: unknown = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await failure(response);\n return response.json();\n })();\n const envelope = value as { session?: unknown; data?: unknown } | null;\n const candidate = (envelope?.session ?? envelope?.data ?? value) as BillLifecycleSession | null;\n if (!candidate || typeof candidate.token !== \"string\" || candidate.token.length < 8) throw new Error(\"The RFA session endpoint did not return a browser session token.\");\n session = { token: candidate.token, ...(typeof candidate.expiresAt === \"string\" ? { expiresAt: candidate.expiresAt } : {}), ...(typeof candidate.apiBaseUrl === \"string\" ? { apiBaseUrl: candidate.apiBaseUrl } : {}) };\n return session;\n })().finally(() => { pending = null; });\n return pending;\n };\n const request = async <T>(path: string, init: RequestInit = {}): Promise<T> => {\n const perform = (active: BillLifecycleSession) => {\n const headers = new Headers(init.headers); headers.set(\"authorization\", `Bearer ${active.token}`);\n if (init.body) headers.set(\"content-type\", \"application/json\");\n return fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/${path}`, { ...init, headers });\n };\n let response = await perform(await mint());\n if (response.status === 401) response = await perform(await mint(true));\n if (!response.ok) throw await failure(response);\n return response.json() as Promise<T>;\n };\n const mutate = async <T extends { id: string }>(path: string, input: unknown, key: string, method = \"POST\"): Promise<T> => {\n if (!key.trim()) throw new Error(\"An idempotency key is required.\");\n const result = await request<{ data: T }>(path, { method, headers: { \"idempotency-key\": key }, body: JSON.stringify(input) });\n if (!result.data?.id) throw new Error(\"The RFA response was invalid.\");\n return result.data;\n };\n const path = (id: string, suffix: string) => `rfas/${encodeURIComponent(id)}/${suffix}`;\n return {\n recordReceipt: (id, input, key) => {\n if (!input.proofDocumentId?.trim() && !input.providerMessageId?.trim()) return Promise.reject(new Error(\"Receipt requires a proof document or provider reference.\"));\n return mutate(path(id, \"transmissions\"), { ...input, direction: \"inbound\", status: \"received\", occurredAt: input.receivedAt }, key);\n },\n recordInformationRequest: (id, input, key) => mutate(path(id, \"information-requests\"), input, key),\n recordInformationResponse: (id, requestId, input, key) => mutate(path(id, `information-requests/${encodeURIComponent(requestId)}`), input, key),\n recordDecisions: (id, input, key) => mutate(path(id, \"decisions\"), input, key),\n listFollowUps: async (query = {}) => {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) if (value !== undefined) params.set(key, String(value));\n const result = await request<RfaFollowUpList>(`rfa-follow-ups${params.size ? `?${params}` : \"\"}`);\n if (!Array.isArray(result.data) || !(result.nextCursor === null || typeof result.nextCursor === \"string\")) throw new Error(\"The RFA follow-up response was invalid.\");\n return result;\n },\n updateFollowUp: (id, input, key) => mutate(`rfa-follow-ups/${encodeURIComponent(id)}`, input, key, \"PATCH\"),\n clearSession: () => { session = null; },\n };\n}\n","import type { BillLifecycleSession, OrganizationClientOptions } from \"./index\";\n\nexport type ReportAutofillField = { key: string; value: string; sourceText: string; confidence: \"high\" | \"medium\" };\nexport type ReportAutofillMatch = { status: \"matched\" | \"ambiguous\" | \"none\"; candidates: Array<{ id: string; name: string }>; selectedId?: string };\nexport type ReportAutofillResult = {\n model: \"gpt-5.6-luna\"; requiresReview: true; fields: ReportAutofillField[];\n matches: Record<\"patient\" | \"billingProvider\" | \"renderingProvider\" | \"serviceLocation\", ReportAutofillMatch>;\n warnings: string[];\n};\nexport type ReportAutofillClient = { analyze(report: File): Promise<ReportAutofillResult>; clearSession(): void };\n/** Available only by written agreement, with an organization-wide autofill:run session. Does not save a document or submit a bill. */\nexport function createReportAutofillClient({ sessionEndpoint = \"/api/mindbill/session\", getSession, apiBaseUrl = \"https://app.mindbill.org\", fetch: fetchOverride }: OrganizationClientOptions = {}): ReportAutofillClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n const error = async (response: Response) => {\n const body = await response.json().catch(() => null) as { detail?: unknown; message?: unknown } | null;\n return new Error(typeof body?.detail === \"string\" ? body.detail : typeof body?.message === \"string\" ? body.message : `Report analysis failed (${response.status}).`);\n };\n const mint = async (): Promise<BillLifecycleSession> => {\n if (session && (!session.expiresAt || Date.parse(session.expiresAt) > Date.now() + 30_000)) return session;\n const value: unknown = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await error(response);\n return response.json();\n })();\n const envelope = value as { session?: unknown; data?: unknown } | null;\n const candidate = (envelope?.session ?? envelope?.data ?? value) as BillLifecycleSession | null;\n if (!candidate || typeof candidate.token !== \"string\" || candidate.token.length < 8) throw new Error(\"The report session endpoint did not return a browser session token.\");\n session = candidate;\n return candidate;\n };\n return {\n clearSession: () => { session = null; },\n analyze: async report => {\n if (report.type !== \"application/pdf\") throw new Error(\"Choose a PDF report.\");\n if (!report.size || report.size > 25 * 1024 * 1024) throw new Error(\"Choose a non-empty PDF report no larger than 25 MB.\");\n const perform = async () => {\n const active = await mint(); const body = new FormData(); body.append(\"report\", report);\n return fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/report-autofill`, { method: \"POST\", headers: { authorization: `Bearer ${active.token}` }, body });\n };\n let response = await perform();\n if (response.status === 401) { session = null; response = await perform(); }\n if (!response.ok) throw await error(response);\n const envelope = await response.json() as { data?: ReportAutofillResult };\n const result = envelope.data;\n if (!result || result.requiresReview !== true || !Array.isArray(result.fields) || !Array.isArray(result.warnings) || !result.matches\n || result.fields.some(field => !field || typeof field.key !== \"string\" || typeof field.value !== \"string\" || typeof field.sourceText !== \"string\" || ![\"high\", \"medium\"].includes(field.confidence))\n || result.warnings.some(warning => typeof warning !== \"string\")\n || ([\"patient\", \"billingProvider\", \"renderingProvider\", \"serviceLocation\"] as const).some(kind => {\n const match = result.matches[kind];\n return !match || ![\"matched\", \"ambiguous\", \"none\"].includes(match.status) || !Array.isArray(match.candidates) || match.candidates.some(candidate => !candidate || typeof candidate.id !== \"string\" || typeof candidate.name !== \"string\");\n })) throw new Error(\"The report analysis response was invalid.\");\n return result;\n },\n };\n}\n","import { parseCaClaimFeeQuote, type CaClaimFeeQuoteInput, type CaClaimFeeQuoteResult } from \"./claim-fees\";\nexport type { CaClaimFeeQuoteInput, CaClaimFeeQuoteResult, CaClaimLineQuote, CaFeeCalculation, CaFeeCitation, CaClaimEditFinding, CaClaimFeeFinding } from \"./claim-fees\";\nexport { normalizeRfaFax, rfaAuthorizationDestinations, rfaAuthorizationGuidance } from \"./rfa-directory\";\nexport type { RfaAuthorizationDestinationOption } from \"./rfa-directory\";\nexport const DEFAULT_API_BASE_URL = \"https://app.mindbill.org\";\nexport const DEFAULT_SESSION_ENDPOINT = \"/api/mindbill/session\";\nexport { parseSecondReviewCorrection, type CorrectionDraft } from \"./second-review-corrections\";\n\nexport type BillReviewDocumentType =\n | \"final_report\"\n | \"letter_of_attestation\"\n | \"proof_of_service\"\n | \"form_122\"\n | \"return_to_work_voucher\"\n | \"w9\"\n | \"medical_records\"\n | \"appeal\"\n | \"other\";\n\nexport type BillReviewBillingProvider = {\n name: string;\n taxId: string;\n taxIdType?: \"EIN\" | \"SSN\";\n taxIdConfigured?: boolean;\n taxIdLast4?: string;\n npi: string;\n billType: \"Professional\" | \"Institutional\";\n phone?: string;\n billingStreet?: string;\n billingCity?: string;\n billingState?: string;\n billingZip?: string;\n};\n\nexport type BillReviewClinician = {\n /** Canonical opaque provider ID, when available. */\n id?: string;\n name: string;\n specialty: string;\n npi: string;\n taxonomy?: string;\n licenseNumber?: string;\n licenseState?: string;\n signaturePng?: string;\n signatureKey?: string;\n isQME?: boolean;\n isAME?: boolean;\n email?: string;\n active?: boolean;\n};\n\nexport type BillReviewLocation = {\n billingProviderId?: string;\n name: string;\n nickname?: string;\n street: string;\n city: string;\n state: string;\n zip: string;\n county?: string;\n posCode?: string;\n isPrimary?: boolean;\n active?: boolean;\n};\n\nexport type BillReviewLineItem = {\n id?: string;\n code: string;\n modifiers: string[];\n units: number;\n charge: number;\n feeSchedule?: number;\n serviceDate?: string | null;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n};\n\nexport type BillReviewAttachment = {\n id: string;\n filename: string;\n description?: string | null;\n documentType: string;\n reportType?: string | null;\n source?: string;\n addedAt?: string;\n contentUrl?: string;\n};\n\n/** One selectable payer (subpayor) under a claims administrator. */\nexport type BillReviewPayerOption = {\n id: string;\n label: string;\n /** Directory-provided default marker. Interactive forms still require an explicit choice. */\n default?: boolean;\n active?: boolean;\n aliases?: string[];\n hint?: string | null;\n affiliatedEntities?: string[];\n route?: string | null;\n optionType?: string | null;\n deliveryType?: string | null;\n clearinghouse?: string | null;\n payerId?: string | null;\n /** Original directory route when live delivery uses a replacement clearinghouse. */\n sourceClearinghouse?: string | null;\n /** Original directory payer ID when live delivery uses a replacement route. */\n sourcePayerId?: string | null;\n clearinghousePayerIds?: Record<string, string>;\n preferredClearinghouse?: string | null;\n};\n\nexport type BillReviewPayer = {\n id: string;\n name: string;\n hasElectronic?: boolean;\n states?: string[];\n confidence?: \"high\" | \"medium\" | \"directory\";\n recommended?: boolean;\n signals?: Array<{\n kind: \"name\" | \"claim_number\";\n state: \"match\" | \"warning\";\n label: string;\n }>;\n /** True when a bill for this claims administrator must name one of `payers`. */\n payerSelectionRequired?: boolean;\n /** Selectable payers (subpayors) under this claims administrator. */\n payers?: BillReviewPayerOption[];\n aliases?: string[];\n affiliatedEntities?: string[];\n claimNumberHint?: string | null;\n claimNumberPatterns?: BillClaimsAdministratorPattern[];\n route?: string | null;\n};\n\n/** A directory suggestion derived from host-provided evidence. Suggestions are never auto-applied. */\nexport type BillReviewPayerSuggestion = BillReviewPayer & {\n deterministic: boolean;\n reason: string;\n /** A uniquely proven routing payer under a multi-payer claims administrator. */\n selectedPayerId?: string;\n};\n\n/** Host-system evidence shown alongside claims-administrator suggestions. */\nexport type BillClaimsAdministratorSource = {\n source: \"eams\" | \"report\" | string;\n label: string;\n name: string;\n url?: string;\n};\n\n/**\n * The directory-marked default payer option, or null when none is marked.\n * Interactive forms should still require an explicit routing-payer choice.\n */\nexport function defaultBillReviewPayerOption(\n payer: Pick<BillReviewPayer, \"payerSelectionRequired\" | \"payers\">,\n): BillReviewPayerOption | null {\n if (!payer.payerSelectionRequired) return null;\n return payer.payers?.find((option) => option.default) ?? null;\n}\n\nexport type BillPostalPlace = { city: string; state: string };\nexport type BillDiagnosisCode = { code: string; description: string };\n\nexport type BillReviewFeatures = {\n authorizationNumber?: boolean;\n serviceDateRange?: boolean;\n wcabNumber?: boolean;\n codingPresets?: boolean;\n};\n\nexport type BillReviewClaimPatternStatus = {\n state: \"match\" | \"warning\" | \"unknown\";\n label: string;\n detail?: string;\n suggestion?: string;\n};\n\nexport type BillReviewData = {\n options?: Pick<OrganizationProfileData, \"billingProviders\" | \"renderingProviders\" | \"locations\">;\n bill: {\n id: string;\n billNumber: string | number;\n status: string;\n transmissionState?: string;\n billingMode: \"med_legal\" | \"professional\";\n dos: string;\n dosEnd?: string | null;\n authorizationNumber?: string | null;\n billingSnapshot?: {\n billingProvider?: BillReviewBillingProvider;\n renderingProvider?: BillReviewClinician;\n placeOfService?: BillReviewLocation;\n } | null;\n lineItems: BillReviewLineItem[];\n attachments: BillReviewAttachment[];\n totalCharge: number;\n totalPaid: number;\n balanceDue: number;\n };\n patient: {\n /** Canonical opaque patient ID, when available. */\n id?: string;\n name: string;\n firstName?: string;\n middleName?: string;\n lastName?: string;\n dob?: string;\n phone?: string;\n address?: {\n line1?: string;\n city?: string;\n state?: string;\n postalCode?: string;\n };\n };\n injury: {\n claimNumber?: string;\n employer?: string;\n doi?: string;\n injuryEndDate?: string;\n cumulativeTrauma?: boolean;\n adjNumber?: string;\n claimsAdminId?: string;\n claimsAdminName?: string;\n injuryDescription?: string;\n /** Diagnosis codes enriched with their human-readable ICD-10 descriptions. */\n diagnoses?: BillDiagnosisCode[];\n /** @deprecated Prefer diagnoses so users can understand each code. */\n diagnosisCodes?: string[];\n claimPatternStatus?: BillReviewClaimPatternStatus;\n };\n};\n\nexport type BillReviewSaveInput = {\n claimsAdminId: string;\n /** The chosen payer (subpayor) when the claims administrator requires payer selection. */\n payerId?: string;\n patientOverrides?: {\n firstName: string;\n middleName?: string;\n lastName: string;\n dob?: string;\n };\n injuryOverrides?: {\n claimNumber?: string;\n employer?: string;\n doi?: string;\n injuryEndDate?: string;\n cumulativeTrauma?: boolean;\n adjNumber?: string;\n };\n dos: string;\n dosEnd?: string | null;\n authorizationNumber?: string | null;\n billingProvider?: BillReviewBillingProvider;\n renderingProvider?: BillReviewClinician;\n placeOfService?: BillReviewLocation;\n lineItems: Array<{\n id?: string;\n code: string;\n modifiers: string[];\n units: number;\n charge?: number;\n serviceDate?: string | null;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n }>;\n};\n\nfunction pickDefined(\n source: object,\n keys: readonly string[],\n): Record<string, unknown> {\n const record = source as Record<string, unknown>;\n return Object.fromEntries(\n keys.flatMap((key) => record[key] === undefined ? [] : [[key, record[key]]]),\n );\n}\n\n/**\n * Removes read-only snapshot metadata before a review mutation is sent.\n * Lifecycle reads can include display-only fields such as entity IDs; the v2\n * write contract accepts only the values that should be frozen onto the bill.\n */\nexport function sanitizeBillReviewSaveInput(\n input: BillReviewSaveInput,\n): BillReviewSaveInput {\n return {\n claimsAdminId: input.claimsAdminId,\n ...(input.payerId !== undefined ? { payerId: input.payerId } : {}),\n ...(input.patientOverrides ? {\n patientOverrides: pickDefined(input.patientOverrides, [\n \"firstName\", \"middleName\", \"lastName\", \"dob\",\n ]) as NonNullable<BillReviewSaveInput[\"patientOverrides\"]>,\n } : {}),\n ...(input.injuryOverrides ? {\n injuryOverrides: pickDefined(input.injuryOverrides, [\n \"claimNumber\", \"employer\", \"doi\", \"injuryEndDate\",\n \"cumulativeTrauma\", \"adjNumber\",\n ]) as NonNullable<BillReviewSaveInput[\"injuryOverrides\"]>,\n } : {}),\n dos: input.dos,\n ...(input.dosEnd !== undefined ? { dosEnd: input.dosEnd } : {}),\n ...(input.authorizationNumber !== undefined\n ? { authorizationNumber: input.authorizationNumber }\n : {}),\n ...(input.billingProvider ? {\n billingProvider: pickDefined(input.billingProvider, [\n \"name\", \"taxId\", \"taxIdType\", \"taxIdConfigured\", \"npi\", \"billType\", \"phone\", \"billingStreet\",\n \"billingCity\", \"billingState\", \"billingZip\",\n ]) as BillReviewBillingProvider,\n } : {}),\n ...(input.renderingProvider ? {\n renderingProvider: pickDefined(input.renderingProvider, [\n \"name\", \"specialty\", \"npi\", \"taxonomy\", \"licenseNumber\",\n \"licenseState\", \"signaturePng\", \"signatureKey\", \"isQME\", \"isAME\",\n \"email\", \"active\",\n ]) as BillReviewClinician,\n } : {}),\n ...(input.placeOfService ? {\n placeOfService: pickDefined(input.placeOfService, [\n \"billingProviderId\", \"name\", \"nickname\", \"street\", \"city\", \"state\",\n \"zip\", \"county\", \"posCode\", \"isPrimary\", \"active\",\n ]) as BillReviewLocation,\n } : {}),\n lineItems: input.lineItems.map((line) => pickDefined(line, [\n \"id\", \"code\", \"modifiers\", \"units\", \"charge\", \"serviceDate\",\n \"serviceDateEnd\", \"diagnosisPointers\",\n ]) as BillReviewSaveInput[\"lineItems\"][number]),\n };\n}\n\nexport type BillSubmissionRoute = \"ebill\" | \"fax\" | \"mail\" | \"email\";\nexport type BillDeliveryOption = {\n route: BillSubmissionRoute;\n label: string;\n detail: string;\n fallback: boolean;\n confidence: string;\n payerName: string;\n target?: string;\n chKey?: string;\n payerId?: string;\n printAndMail?: boolean;\n costUsd?: number;\n};\nexport type BillDeliveryOptions = {\n payerName: string;\n recommended: BillDeliveryOption;\n options: BillDeliveryOption[];\n contacts: {\n faxNumber?: string | null;\n claimsEmail?: string | null;\n portalUrl?: string | null;\n mailingAddress?: string | null;\n adjusterName?: string | null;\n adjusterPhone?: string | null;\n adjusterEmail?: string | null;\n };\n};\nexport type BillActorInput = {\n /** Human-readable name shown for user-initiated audit history. */\n actorName?: string;\n};\n\nexport type AddBillNoteInput = BillActorInput & {\n note: string;\n};\n\nexport type SubmitBillInput = BillActorInput & {\n route: BillSubmissionRoute;\n destination?: {\n faxNumber?: string;\n email?: string;\n mailingAddress?: string;\n };\n attention?: string;\n subject?: string;\n note?: string;\n /** CC recipients for the email route (at most 10). */\n cc?: string[];\n};\nexport type BillLifecycleActionId =\n | \"resubmit\"\n | \"second_review\"\n | \"independent_bill_review\"\n | \"view_eor\"\n | \"post_payment\"\n | \"close\"\n | \"reopen\"\n | \"send_duplicate\"\n | \"report_bill_status\"\n | \"submit_new_bill\";\n\nexport type BillLifecycleAction = {\n id: BillLifecycleActionId;\n label: string;\n enabled: boolean;\n primary?: boolean;\n reason?: string;\n};\n\nexport type BillEorDocument = {\n id: string;\n filename: string;\n description: string | null;\n addedAt: string;\n contentUrl: string;\n};\n\nexport type BillActivityRecord = {\n id: string;\n type: string;\n createdAt: string;\n title?: string;\n description: string;\n actor: string | null;\n delivery: BillSubmissionRoute | null;\n amount: number | null;\n accepted: boolean | null;\n stcCategory: string | null;\n};\n\n/** One user-facing bill history row (Date / Action / User / Details).\n * Server-presented: the wording is authored by MindBill so every surface (MindBill\n * app, React, Angular, embeds) reads identically. */\nexport type BillHistoryEntry = {\n id: string;\n /** Immutable bill attempt that produced this event. Present on unified chain history. */\n attemptId?: string;\n /** ISO timestamp for ordering and the Date column. */\n date: string;\n /** Short Action label — \"Original Bill\", \"277 Accept\", \"Payment\", \"Note\", … */\n action: string;\n kind:\n | \"created\"\n | \"submission\"\n | \"ack\"\n | \"eor\"\n | \"payment\"\n | \"review\"\n | \"close\"\n | \"reopen\"\n | \"note\"\n | \"portal\"\n | \"task\"\n | \"system\";\n /** Who acted: a biller name, MindBill automation, or the responding clearinghouse. */\n actor: string | null;\n /** The one-line Details column. */\n summary: string;\n /** Drives row highlighting: submissions are pale blue, notes pale yellow. */\n tone: \"submission\" | \"note\" | \"neutral\" | \"problem\" | \"success\";\n amount?: number;\n /** Expandable content; absent → the row is not expandable. */\n details?: {\n rows?: Array<{ label: string; value: string }>;\n documents?: Array<{ id: string; filename: string }>;\n complianceDueDates?: Array<{ date: string; text: string }>;\n codes?: Array<{ code: string; text: string }>;\n text?: string;\n };\n};\n\n/** One immutable transmission attempt within a logical bill chain. */\nexport type BillAttemptSummary = {\n /** Unique transmission identity. Draft attempts fall back to the bill record ID. */\n id: string;\n /** Underlying bill record. Multiple transmissions may share this value. */\n billId?: string;\n submissionId?: string;\n billNumber?: string | number;\n label: string;\n deliveryLabel?: string;\n sentAt?: string;\n ackLabel?: string;\n ackAt?: string;\n status?: string;\n complianceLabel?: string;\n complianceAt?: string;\n /** The latest attempt that receives lifecycle mutations. */\n isCurrent: boolean;\n};\n\nexport type BillPaymentRecord = {\n id: string;\n method: \"check\" | \"eft\";\n checkNumber: string;\n status: string | null;\n depositDate: string | null;\n checkReceived: boolean | null;\n receivedDate: string | null;\n amount: number;\n principalAmount: number;\n feeAmount: number | null;\n feeReason: string | null;\n source: \"paper\" | \"835\" | \"portal\";\n postedAt: string;\n updatedAt: string | null;\n note: string | null;\n};\n\nexport type BillRemittanceSummary = {\n billedAmount: number;\n expectedAmount: number;\n payerAllowedAmount: number | null;\n payerReportedPaid: number | null;\n postedPrincipal: number;\n postedAdditional: number;\n totalPostedCash: number;\n balanceDue: number;\n denialReason: string | null;\n};\n\nexport type BillLifecycleDelivery = {\n payerName: string;\n contacts: BillDeliveryOptions[\"contacts\"];\n /**\n * Partner-safe directory details. `id` is an opaque MindBill directory ID;\n * Values are safe, partner-facing directory details; internal database identifiers are opaque.\n */\n directory?: BillClaimsAdministratorDirectory | null;\n};\n\nexport type BillClaimsAdministratorContact = {\n location?: string | null;\n method?: \"fax\" | \"email\";\n name?: string | null;\n phone?: string | null;\n email?: string | null;\n fax?: string | null;\n portalUrl?: string | null;\n address?: string | null;\n note?: string | null;\n};\n\nexport type BillClaimsAdministratorMailingAddress = {\n company?: string | null;\n address: string;\n notes?: string | null;\n submissionTypes?: string[];\n billTreatmentTypes?: string[];\n};\n\nexport type BillClaimsAdministratorPattern = {\n length?: number | string | null;\n pattern: string;\n example?: string | null;\n matches?: boolean | null;\n};\n\nexport type BillClaimsAdministratorPayer = {\n name: string;\n route?: string | null;\n aliases?: string[];\n hint?: string | null;\n affiliatedEntities?: string[];\n optionType?: string | null;\n deliveryType?: string | null;\n clearinghouse?: string | null;\n payerId?: string | null;\n sourceClearinghouse?: string | null;\n sourcePayerId?: string | null;\n clearinghousePayerIds?: Record<string, string>;\n preferredClearinghouse?: string | null;\n};\n\nexport type BillReviewPayerPage = {\n results: BillReviewPayer[];\n suggestions?: BillReviewPayerSuggestion[];\n total: number;\n nextOffset?: number;\n recommendedId?: string;\n};\n\nexport type BillReviewPayerListInput = {\n query?: string;\n claimNumber?: string;\n sourceClaimsAdministratorName?: string;\n employerName?: string;\n limit?: number;\n offset?: number;\n};\n\nexport type BillClaimsAdministratorAuthorizationStatus = \"central_fax\" | \"central_email\" | \"claim_handling_location_routes\" | \"adjuster_specific_required\" | \"daisybill_unverified\" | \"profile_not_published\";\n\nexport type BillClaimsAdministratorDirectory = {\n authorizationStatus?: BillClaimsAdministratorAuthorizationStatus;\n authorizationSource?: { url: string; observedAt: string };\n id?: string;\n name?: string;\n type?: string | null;\n description?: string | null;\n website?: string | null;\n aliases?: string[];\n affiliatedEntities?: string[];\n hours?: string | null;\n claimNumberHint?: string | null;\n billProcessingWorkflow?: string | null;\n billProcessingWorkflowNotes?: string | null;\n telephoneNumbers?: string[];\n emailAddresses?: string[];\n webPortals?: string[];\n payers?: BillClaimsAdministratorPayer[];\n authorizationNotice?: string | null;\n billReview?: BillClaimsAdministratorContact[];\n authorization?: BillClaimsAdministratorContact[];\n mailingAddresses?: BillClaimsAdministratorMailingAddress[];\n claimNumberPatterns?: BillClaimsAdministratorPattern[];\n};\n\n/** End-user-safe details explaining why the latest submission was rejected. */\nexport type BillRejectionIssue = {\n code?: string | null;\n description: string;\n /** Bill-submission field paths implicated by this issue. */\n fieldPaths?: string[];\n};\n\nexport type BillRejection = {\n reason: string;\n code?: string | null;\n issues?: BillRejectionIssue[];\n receivedAt?: string | null;\n source?: string | null;\n};\n\nexport type BillTeamNote = { id: string; body: string; author: string; createdAt: string; pinned: boolean };\n\nexport type BillCourtesyCopyInput = {\n to: string[];\n cc?: string[];\n subject: string;\n bodyText: string;\n includeCms1500?: boolean;\n documentIds?: string[];\n};\nexport type BillCourtesyCopyPreview = {\n filename: string; documentCount: number; packetHash: string; pdfBase64: string;\n environment: \"sandbox\" | \"live\";\n};\nexport type BillCourtesyCopyResult = { ok: boolean; sent: boolean; simulated?: boolean; dryRun?: boolean; messageId?: string };\n\n/** Historical financial balances are unavailable, not zero. */\nexport type HistoricalBillReviewData = Omit<BillReviewData, \"bill\"> & {\n bill: Omit<BillReviewData[\"bill\"], \"totalPaid\" | \"balanceDue\"> & {\n totalPaid: number | null;\n balanceDue: number | null;\n };\n};\nexport type BillSubmissionDetail = {\n attemptId: string;\n billId: string;\n source: \"submission_snapshot\" | \"bill_record\" | \"unavailable\";\n capturedAt?: string | null;\n detail: HistoricalBillReviewData | null;\n /** Exact retained files for this attempt; never regenerated from current bill values. */\n artifacts?: Array<{ id: string; label: string; kind: \"submitted_attachment\" | \"submitted_edi\"; contentType: string }>;\n};\n\nexport type BillLifecycleData = BillReviewData & {\n environment: \"sandbox\" | \"live\";\n lifecycle: {\n state: string;\n nativeStatus: string;\n submittedAt?: string | null;\n agingDays?: number | null;\n updatedAt?: string | null;\n actions: BillLifecycleAction[];\n };\n eors: BillEorDocument[];\n activity: BillActivityRecord[];\n /** Presented history rows. Optional: absent when the API\n * predates the presented-history rollout — fall back to `activity`. */\n history?: BillHistoryEntry[];\n /** Canonical team notes, shared with the MindBill app. Absent on older APIs. */\n notes?: BillTeamNote[];\n /** Immutable submissions that share this bill's unified history. */\n attempts?: BillAttemptSummary[];\n /** Per-attempt details. Older APIs may omit this; never substitute the current bill. */\n submissionDetails?: BillSubmissionDetail[];\n payments: BillPaymentRecord[];\n remittance: BillRemittanceSummary;\n delivery: BillLifecycleDelivery;\n rejection?: BillRejection | null;\n};\n\nexport type BillLifecycleSession = {\n token: string;\n expiresAt?: string;\n apiBaseUrl?: string;\n};\n\nexport type BillLifecycleSessionRequest = {\n signal: AbortSignal;\n};\n\nexport type BillLifecycleSessionProvider = (\n request: BillLifecycleSessionRequest,\n) => Promise<BillLifecycleSession>;\n\nexport type CloseBillInput = BillActorInput & { reason: string };\nexport type ReopenBillInput = BillActorInput & { reason: string };\nexport type PostBillPaymentInput = BillActorInput & {\n amount: number;\n penaltyAmount?: number;\n interestAmount?: number;\n method: \"check\" | \"eft\";\n checkNumber?: string;\n depositDate: string;\n note?: string;\n};\nexport type SecondReviewLineInput = {\n lineItemId: string;\n reason: string;\n /** SBR-1 box for this service line. Omitted leaves the box blank. */\n serviceAuthorized?: boolean;\n /** Absolute corrected values for this Second Review only; charge is explicitly reviewed, never inferred. */\n correction?: { units: number; modifiers: string[]; charge: number };\n};\n\nexport type SubmitSecondReviewInput = BillActorInput & {\n /** @deprecated Prefer `lineItems[].reason`; retained for older hosts. */\n reason?: string;\n /** @deprecated MindBill derives this from the payer response on the server. */\n payerClaimControlNumber?: string;\n disputedAmount?: number;\n attachmentIds: string[];\n route: BillSubmissionRoute;\n /** New PDFs to include with the Second Review. */\n documents?: BrowserBillSubmissionDocument[];\n destination?: SubmitBillInput[\"destination\"];\n attention?: string;\n subject?: string;\n note?: string;\n cc?: string[];\n /** Line-by-line SBR-1 selections, reasons, and authorization answers. */\n lineItems?: SecondReviewLineInput[];\n /** @deprecated Prefer `lineItems`; omitted = the whole bill. */\n lineItemIds?: string[];\n /** @deprecated Prefer `lineItems[].serviceAuthorized`. */\n serviceAuthorized?: boolean;\n};\n\nexport type ReportBillStatusId =\n | \"message_left\"\n | \"eor_pending\"\n | \"eor_sent\"\n | \"bill_not_on_file\"\n | \"forwarded\";\n\nexport type ReportBillStatusOption = {\n id: ReportBillStatusId;\n label: string;\n description: string;\n};\n\n/** The five supported outcomes of a bill payment-status phone call. */\nexport const REPORT_BILL_STATUS_OPTIONS: ReportBillStatusOption[] = [\n {\n id: \"message_left\",\n label: \"Message Left Requesting Bill Payment Status\",\n description: \"Claims Administrator/Bill Review representative unavailable.\",\n },\n {\n id: \"eor_pending\",\n label: \"Explanation of Review (EOR) Pending\",\n description: \"Claims Administrator/Bill Review reported the bill is still in process and an EOR has not been generated or sent.\",\n },\n {\n id: \"eor_sent\",\n label: \"Explanation of Review (EOR) Sent\",\n description: \"Claims Administrator/Bill Review reported sending an EOR to the provider.\",\n },\n {\n id: \"bill_not_on_file\",\n label: \"Bill Not On File\",\n description: \"Claims Administrator/Bill Review reported not receiving the bill.\",\n },\n {\n id: \"forwarded\",\n label: \"Bill Forwarded to Different Payer / Network\",\n description: \"Claims Administrator/Bill Review reported forwarding the bill to a different payer.\",\n },\n];\n\n/**\n * Outcome of a phone call to the Claims Administrator / Bill Review vendor\n * about an outstanding bill, recorded through the lifecycle actions endpoint.\n */\nexport type ReportBillStatusInput = BillActorInput & {\n status: ReportBillStatusId;\n company?: string;\n representativeName?: string;\n representativeRole?: string;\n phone?: string;\n callReference?: string;\n note?: string;\n};\n\n/**\n * Payload for the \"report_bill_status\" lifecycle action: records the outcome\n * of a phone call to the Claims Administrator / Bill Review vendor about an\n * outstanding bill. Posted through the generic lifecycle actions endpoint.\n */\nexport type ReportBillStatusActionInput = ReportBillStatusInput & {\n action: \"report_bill_status\";\n};\n\n/**\n * Payload for the \"send_duplicate\" lifecycle action. A duplicate is a fresh,\n * editable bill snapshot linked to the submitted original. The original stays\n * immutable; the biller must review the snapshot and explicitly confirm its\n * delivery route before this action is posted.\n */\nexport type SendDuplicateBillInput = ResubmitBillInput;\n\nexport type ReportBillStatusContacts = {\n claimsAdmin: {\n name: string;\n hoursOfOperation?: string;\n phones: Array<{ label: string; value: string }>;\n } | null;\n billReview: { name: string; phone?: string } | null;\n};\n\n/**\n * Partner-safe \"who to call\" summary for the Report Bill Status flow, derived\n * from the lifecycle delivery block (payer contacts + optional directory).\n */\nexport function reportBillStatusContacts(\n delivery: BillLifecycleDelivery,\n): ReportBillStatusContacts {\n const payerName = delivery.payerName?.trim();\n const directory = delivery.directory ?? null;\n const phones: Array<{ label: string; value: string }> = [];\n const adjusterPhone = delivery.contacts.adjusterPhone?.trim();\n if (adjusterPhone) {\n const adjusterName = delivery.contacts.adjusterName?.trim();\n phones.push({\n label: adjusterName ? `Adjuster (${adjusterName})` : \"Adjuster\",\n value: adjusterPhone,\n });\n }\n const hours = directory?.hours?.trim();\n const claimsAdmin = payerName\n ? {\n name: payerName,\n ...(hours ? { hoursOfOperation: hours } : {}),\n phones,\n }\n : null;\n const billReviewContact = (directory?.billReview ?? []).find(\n (contact) => contact.name?.trim() || contact.phone?.trim(),\n );\n const billReview = billReviewContact\n ? {\n name: billReviewContact.name?.trim() || \"Bill Review\",\n ...(billReviewContact.phone?.trim() ? { phone: billReviewContact.phone.trim() } : {}),\n }\n : null;\n return { claimsAdmin, billReview };\n}\n\n/**\n * Default Second Bill Review dispute reason for an invalid med-legal denial.\n * Prefilled (editable) in the SBR panel.\n */\nexport const SECOND_REVIEW_REASON_TEMPLATE =\n \"This is an appeal of the invalid denial of this med-legal bill; per LC §4622 and the OMFS/MLFS, payment is due as billed.\";\n\n/** Days allowed to request Second Review after service of the denial EOR. */\nexport const SECOND_REVIEW_WINDOW_DAYS = 90;\n\nexport type SecondReviewDeadline = {\n /** ISO date (yyyy-mm-dd) of the latest denial/EOR document. */\n eorDate: string;\n /** ISO date (yyyy-mm-dd) 90 days after the EOR date. */\n deadline: string;\n};\n\n/**\n * The 90-day Second Review window anchored on the latest EOR date, or null\n * when the lifecycle data provides no parseable denial/EOR date.\n */\nexport function secondReviewDeadline(\n eors: Array<Pick<BillEorDocument, \"addedAt\">>,\n): SecondReviewDeadline | null {\n const times = eors\n .map((eor) => Date.parse(eor.addedAt))\n .filter((time) => Number.isFinite(time));\n if (!times.length) return null;\n const eorTime = Math.max(...times);\n const isoDate = (time: number): string => new Date(time).toISOString().slice(0, 10);\n return {\n eorDate: isoDate(eorTime),\n deadline: isoDate(eorTime + SECOND_REVIEW_WINDOW_DAYS * 86_400_000),\n };\n}\n/**\n * A corrected immutable snapshot submitted as the next attempt on the same bill.\n * The logical bill ID remains stable; only the submission/control-number attempt advances.\n */\nexport type ResubmitBillInput = BillActorInput & {\n reason?: string;\n bill: BrowserBillCreateInput;\n /** Explicit delivery route confirmed by the biller for this new attempt. */\n submission?: Omit<SubmitBillInput, keyof BillActorInput>;\n documents?: BrowserBillSubmissionDocument[];\n};\n/**\n * \"Submit New Bill\" from a CLOSED bill: the same snapshot payload shape as a\n * resubmission, but the server creates a FRESH original bill linked to the closed\n * predecessor — the closed bill stays closed and keeps its record, and the\n * submissions ribbon/timeline chains both records.\n */\nexport type SubmitNewBillInput = ResubmitBillInput;\nexport type SandboxSimulationScenario = \"accepted\" | \"rejected\" | \"processed\" | \"denied\" | \"partial_payment\" | \"paid\";\nexport type SimulateSandboxBillInput = {\n scenario: SandboxSimulationScenario;\n amount?: number;\n reasonCode?: string;\n};\n\nexport type BrowserBillAddress = {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n postalCode: string;\n};\n\n/** Complete bill snapshot accepted by the browser create endpoint. */\nexport type BrowserBillCreateInput = {\n externalId?: string;\n billingMode?: \"med_legal\" | \"professional\";\n patient: {\n id?: string;\n externalId?: string;\n firstName: string;\n middleName?: string;\n lastName: string;\n dateOfBirth: string;\n ssn?: string;\n gender?: \"M\" | \"F\" | \"X\";\n phone?: string;\n address: BrowserBillAddress;\n };\n claim: {\n id?: string;\n externalId?: string;\n claimNumber: string;\n adjNumber?: string;\n employer: string;\n dateOfInjury: string;\n injuryState?: string;\n description?: string;\n claimsAdministrator: {\n id: string;\n name: string;\n /** The chosen payer (subpayor) when the claims administrator requires payer selection. */\n payerId?: string;\n };\n };\n service: { date: string; endDate?: string | null; authorizationNumber?: string | null };\n billingProvider: { id?: string; name: string; taxId: string; taxIdType?: \"EIN\" | \"SSN\"; npi: string; phone: string; address: BrowserBillAddress } | { savedProviderId: string } | { sourceBillId: string };\n renderingProvider: {\n name: string;\n specialty?: string;\n npi: string;\n taxonomy: string;\n licenseNumber?: string;\n licenseState?: string;\n isQme?: boolean;\n isAme?: boolean;\n };\n serviceLocation: { name?: string; address: BrowserBillAddress; placeOfServiceCode: string };\n diagnoses: string[];\n serviceLines: Array<{\n code: string;\n modifiers?: string[];\n units?: number;\n charge?: number;\n serviceDate?: string;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n /** Calculation context revalidated by the server before bill creation. */\n feeContext?: BillFeeContext;\n drug?: BilledDrug;\n /** Existing authorized RFA item linked to this service line. */\n rfaItemId?: string;\n }>;\n};\n\n/** Canonical immutable PDF snapshot sent with a bill submission. */\nexport type BrowserBillSubmissionDocument = {\n externalId?: string;\n filename: string;\n description?: string;\n documentType: BillReviewDocumentType;\n /** Opaque PWK report-type code selected by the component (for example OZ:J4). */\n reportTypeCode?: string;\n contentBase64: string;\n};\n\nexport type BrowserBillSubmissionInput = BillActorInput & {\n /** Usually omitted: MindBill stamps the customer from the server-issued session.\n * If supplied, it must match the session customer restriction. */\n customerExternalId?: string;\n bill: BrowserBillCreateInput;\n submission?: {\n route?: BillSubmissionRoute;\n destination?: SubmitBillInput[\"destination\"];\n attention?: string;\n subject?: string;\n note?: string;\n cc?: string[];\n };\n documents?: BrowserBillSubmissionDocument[];\n};\n\nexport type BrowserSubmittedBill = Record<string, unknown> & {\n id: string;\n customerExternalId?: string | null;\n externalId?: string | null;\n state?: string;\n};\n\nexport type BrowserBillSubmissionResult = {\n billId: string;\n bill: BrowserSubmittedBill;\n};\n\nexport type BillLifecycleClientOptions = {\n /** ID of an already-submitted bill. Bills are created only by the atomic server API. */\n billId: string;\n sessionEndpoint?: string | undefined;\n getSession?: BillLifecycleSessionProvider | undefined;\n apiBaseUrl?: string | undefined;\n fetch?: typeof globalThis.fetch | undefined;\n};\n\n/** Browser-session options for pre-submission reference-data lookups. */\nexport type BillReferenceClientOptions = Omit<BillLifecycleClientOptions, \"billId\">;\n\n/** Browser-session options for an atomic immutable bill submission. */\nexport type BillSubmissionClientOptions = BillReferenceClientOptions;\n\nexport type BillSubmissionClient = {\n submitBill: (\n input: BrowserBillSubmissionInput,\n options?: { idempotencyKey?: string },\n ) => Promise<BrowserBillSubmissionResult>;\n clearSession: () => void;\n};\n\n/** Input for the pre-submission delivery preview keyed on a payer-directory id. */\nexport type BillDeliveryPreviewInput = {\n claimsAdministratorId: string;\n /** Selected payer child when the administrator exposes multiple payer routes. */\n payerId?: string;\n /** Two-letter state; defaults to CA server-side. */\n injuryState?: string;\n};\n\nexport type BillProcedureCodeSearchInput = {\n query?: string;\n limit?: number;\n jurisdiction?: \"CA\" | \"NY\" | \"OWCP\";\n};\n\n/** Catalog membership does not imply that a fee is available for a service date. */\nexport type BillProcedureCodePage = {\n results: Array<{ code: string }>;\n total: number;\n limit: number;\n jurisdiction: \"CA\" | \"NY\" | \"OWCP\";\n catalogAsOf: string | null;\n};\n\nexport type BillFeeSource = {\n id: string;\n url: string;\n sha256?: string;\n effectiveFrom: string;\n effectiveThrough: string;\n};\n\n/** Drug identifiers and quantities printed on the professional claim. */\nexport type BilledDrug = {\n ndcNumber: string;\n metricQuantity: string;\n unitOfMeasure: \"UN\" | \"ML\" | \"GR\";\n administered?: {\n drugName: string;\n administeredAmount: string;\n doseUnit: \"mg\" | \"mcg\" | \"g\" | \"mL\" | \"units\";\n hcpcsCode: string;\n amountPerHcpcsUnit: string;\n amountPerNdcUnit: string;\n hcpcsUnitSource: string;\n productLabelSource: string;\n unitDefinitionsVerified: true;\n };\n};\n\n/** Minutes since midnight on the service date; end must follow start. */\nexport type CaAnesthesiaInterval = { startMinute: number; endMinute: number };\n/** Opaque references to the actual physician and service record. */\nexport type CaAnesthesiaEvent = { physicianRef: string; recordRef: string; minute: number };\nexport type CaAnesthesiaParticipation = CaAnesthesiaInterval & { physicianRef: string; recordRef: string };\nexport type CaAnesthesiaOptionalParticipation = CaAnesthesiaParticipation | { applicability: \"not_indicated\"; recordRef: string };\nexport type CaMedicalDirectionCase = {\n caseRef: string;\n anesthetistRole: \"crna\" | \"anesthesiologist_assistant\" | \"intern\" | \"resident\" | \"student_nurse_anesthetist\";\n qualificationRecordRef: string;\n procedure: \"cataract\" | \"iridectomy\" | \"other\";\n interval: CaAnesthesiaInterval;\n activities: {\n preAnestheticEvaluation: CaAnesthesiaEvent;\n prescribedPlan: CaAnesthesiaEvent;\n demandingProcedures: CaAnesthesiaParticipation[];\n induction: CaAnesthesiaOptionalParticipation;\n emergence: CaAnesthesiaOptionalParticipation;\n qualifiedAnesthetistProcedures: CaAnesthesiaEvent;\n frequentMonitoring: { recordRef: string; observations: CaAnesthesiaEvent[] };\n indicatedPostAnesthesiaCare: CaAnesthesiaEvent;\n };\n};\n/** All overlapping cases across all payers, including cases outside this bill. */\nexport type CaMedicalDirection = {\n physicianRef: string;\n groupPhysicianRefs: string[];\n billedCaseRef: string;\n rosterScope: \"all_overlapping_cases_all_payers\";\n rosterRecordRef: string;\n cases: CaMedicalDirectionCase[];\n physicalPresenceAndImmediateAvailability: CaAnesthesiaParticipation[];\n otherPatientServices: Array<{\n kind: \"emergency\" | \"labor_analgesia\" | \"obstetric_monitoring\" | \"receiving_patient\" | \"recovery_care\" | \"other\";\n interval: CaAnesthesiaInterval;\n recordRef: string;\n }>;\n};\nexport type CaMonitoredAnesthesiaCare = {\n medicallyNecessary: true;\n intraoperativePhysiologicalMonitoring: true;\n preparedForGeneralAnesthesiaOrAdverseReaction: true;\n perioperativeAnesthesiaCare: true;\n underlyingProcedureProvider: \"different_provider\" | \"same_provider\";\n underlyingProcedure: \"nerve_block_or_injection\" | \"other\";\n};\n/** Clinical facts supplement AA or QK; monitored care also requires QS. */\nexport type CaAnesthesiaContext = {\n providerKind: \"physician\";\n actualMinutes: number;\n placeOfService: string;\n completeSameDayServices: true;\n otherSameDayServices: boolean;\n codingRequirementsSatisfied: true;\n monitoredCare?: CaMonitoredAnesthesiaCare;\n} & ({ personallyPerformedAlone: true; medicalDirection?: never } | { personallyPerformedAlone: false; medicalDirection: CaMedicalDirection });\n\nexport type CaPadbContext = {\n providerKind: \"physician\";\n placeOfService: \"11\";\n productKind: \"injectable\";\n bundledOrPackaged: false;\n codingRequirementsSatisfied: true;\n completeSameDayServices: true;\n sameDayServices: Array<{ code: string; units: number }>;\n};\n\nexport type CaTherapyContext = {\n providerKind: \"physical_therapist\" | \"other\";\n personallyPerformed: boolean;\n hospitalPatient: boolean;\n incidentToPhysicianService: boolean;\n assistantInvolved: boolean;\n placeOfService: string;\n directOneOnOneMinutes: number;\n totalVisitMinutes: number;\n visitsOnDate: number;\n completeSameDayServices: boolean;\n otherSameDayServices: boolean;\n globalPeriodApplies: boolean;\n hpsaBonusEligible: boolean;\n };\n\nexport type BillFeeQuoteInput = {\n drug?: BilledDrug;\n padbContext?: CaPadbContext;\n anesthesiaContext?: CaAnesthesiaContext;\n billingProviderId?: string;\n payerId?: string;\n code: string;\n dateOfService: string;\n chargeCents?: number;\n units?: number;\n modifiers?: string[];\n pages?: number;\n reportKind?: \"progress\" | \"permanent_stationary_pr3\" | \"permanent_stationary_pr4\";\n hasFeeAgreement?: boolean;\n serviceZip?: string;\n /** Explicit physical interpretation location for a professional component. */\n professionalComponentContext?: {\n interpretationLocation: \"same_as_patient_service\" | \"different_from_patient_service\";\n };\n /** California equipment pricing uses worker residence, independently of service location. */\n dmeposContext?: {\n residenceZip: string;\n /** Continuous rental month for this equipment item; only for applicable RR lines. */\n rentalMonth?: number;\n /** Actual prior payments for this item, including rentals; explicit zero means no prior payments. */\n priorPaymentsCents?: number;\n };\n /** Supply verified service facts; omitted context can require review. */\n physicianContext?: {\n providerKind: \"physician\" | \"physician_assistant\" | \"nurse_practitioner\" | \"clinical_nurse_specialist\" | \"other\";\n incidentToPhysicianService?: boolean;\n placeOfService: string;\n standaloneService: boolean;\n globalPeriodApplies: boolean;\n hpsaBonusEligible: boolean;\n };\n therapyContext?: CaTherapyContext;\n catalogContext?: {\n codingRequirementsSatisfied: boolean;\n statusIAlternative?: \"none\" | \"cpt\" | \"drug\";\n completeSurgicalPackage?: boolean;\n };\n prolongedServiceContext?: {\n totalMinutes: number;\n relatedEvaluationDate: string;\n ongoingPatientManagement: boolean;\n personallyPerformed: boolean;\n timeCountedInOtherServices: boolean;\n completeSameDayServices: boolean;\n sameDayServices: Array<{ code: string; units: number }>;\n };\n reportQualification?:\n | { kind: \"psychiatric_report\"; requestedBy: \"wcab\" | \"administrative_director\"; medicalLegalEvaluation: boolean; reportPayableUnderMedicalLegalSchedule: boolean }\n | { kind: \"consultation_report\"; requestedBy: \"wcab\" | \"administrative_director\" | \"qme\" | \"ame\"; medicalLegalEvaluation: boolean; reportPayableUnderMedicalLegalSchedule: boolean }\n | { kind: \"chart_notes\"; requestedBy: \"claims_administrator\"; writtenRequest: boolean }\n | { kind: \"duplicate_report\"; requestedBy: \"claims_administrator\"; writtenRequest: boolean; relatedToBilling: boolean; initialRequiredCopy: boolean };\n};\n\n/** Authoritative service, provider, payer and location fields come from the submitted bill. */\nexport type BillFeeContext = Omit<BillFeeQuoteInput, \"code\" | \"dateOfService\" | \"units\" | \"modifiers\" | \"chargeCents\" | \"billingProviderId\" | \"payerId\" | \"serviceZip\" | \"drug\">;\n\n/** Fee families returned by the California and practice-contract quote endpoint. */\nexport const BILL_FEE_QUOTE_BASES = [\n \"ca_report\", \"ca_physician_rbrvs\", \"ca_therapy_rbrvs\", \"ca_clfs\",\n \"ca_simple_dispensed_drug\", \"ca_dmepos\", \"ca_padb\", \"ca_anesthesia\", \"payer_contract\",\n] as const;\nexport type BillFeeQuoteBasis = typeof BILL_FEE_QUOTE_BASES[number];\n\nexport type BillFeeQuote =\n | {\n status: \"priced\";\n /** Total for the service line in cents, already accounting for units. */\n amountCents: number;\n scheduleMaximumCents: number;\n basis: BillFeeQuoteBasis;\n anesthesia?: { actualMinutes: number; baseUnits: number; timeUnitsTenths: number; conversionFactorCents: number; locality: string; medicalDirection?: { concurrentCases: number; baseReductionPercent: number; physicianPaymentPercent: 50 } };\n provenance: BillFeeSource[];\n notes: string[];\n }\n | { status: \"requires_review\" | \"not_separately_payable\"; reason: string; provenance: BillFeeSource[] };\n\nexport type BillReferenceClient = {\n listClaimsAdministrators: (input?: BillReviewPayerListInput) => Promise<BillReviewPayerPage>;\n searchClaimsAdministrators: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;\n getClaimsAdministratorDirectory: (id: string, injuryState?: string) => Promise<BillClaimsAdministratorDirectory>;\n searchDiagnosisCodes: (query: string, limit?: number, offset?: number) => Promise<BillDiagnosisCode[]>;\n searchProcedureCodes: (input?: BillProcedureCodeSearchInput) => Promise<BillProcedureCodePage>;\n quoteFee: (input: BillFeeQuoteInput) => Promise<BillFeeQuote>;\n quoteClaimFees: (input: CaClaimFeeQuoteInput) => Promise<CaClaimFeeQuoteResult>;\n lookupPostalCode: (postalCode: string) => Promise<BillPostalPlace | null>;\n /**\n * Delivery-route preview (recommended route + selectable options + payer\n * contacts) for a claims administrator BEFORE the bill exists — powers the\n * send-route picker shown at submit time.\n */\n getDeliveryPreview: (input: BillDeliveryPreviewInput) => Promise<BillDeliveryOptions>;\n clearSession: () => void;\n};\n\nexport type BillLifecycleClient = {\n getBillId: () => string;\n getLifecycle: (signal?: AbortSignal) => Promise<BillLifecycleData>;\n listClaimsAdministrators: (input?: BillReviewPayerListInput) => Promise<BillReviewPayerPage>;\n searchClaimsAdministrators: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;\n getClaimsAdministratorDirectory: (id: string, injuryState?: string) => Promise<BillClaimsAdministratorDirectory>;\n searchDiagnosisCodes: (query: string, limit?: number, offset?: number) => Promise<BillDiagnosisCode[]>;\n searchProcedureCodes: (input?: BillProcedureCodeSearchInput) => Promise<BillProcedureCodePage>;\n quoteFee: (input: BillFeeQuoteInput) => Promise<BillFeeQuote>;\n quoteClaimFees: (input: CaClaimFeeQuoteInput) => Promise<CaClaimFeeQuoteResult>;\n lookupPostalCode: (postalCode: string) => Promise<BillPostalPlace | null>;\n getDeliveryOptions: () => Promise<BillDeliveryOptions>;\n getDeliveryPreview: (input: BillDeliveryPreviewInput) => Promise<BillDeliveryOptions>;\n getAttachment: (attachmentId: string) => Promise<Blob>;\n getEor: (documentId: string) => Promise<Blob>;\n getPacket: () => Promise<Blob>;\n getSubmissionArtifact: (attemptId: string, artifactId: string) => Promise<Blob>;\n /** Prepare a self-filing packet. Does not file IBR or send anything to a payer. */\n prepareIbrPacket: () => Promise<Blob>;\n previewCourtesyCopy: (input: BillCourtesyCopyInput) => Promise<BillCourtesyCopyPreview>;\n /** Reuse the same key when retrying the same send after a network interruption. */\n sendCourtesyCopy: (input: BillCourtesyCopyInput & { packetHash: string }, idempotencyKey: string) => Promise<BillCourtesyCopyResult>;\n addNote: (input: AddBillNoteInput) => Promise<BillLifecycleData>;\n closeBill: (input: CloseBillInput) => Promise<BillLifecycleData>;\n reopenBill: (input: ReopenBillInput) => Promise<BillLifecycleData>;\n postPayment: (input: PostBillPaymentInput) => Promise<BillLifecycleData>;\n submitSecondReview: (input: SubmitSecondReviewInput) => Promise<BillLifecycleData>;\n resubmitBill: (input: ResubmitBillInput) => Promise<BillLifecycleData>;\n submitNewBill: (input: SubmitNewBillInput) => Promise<BillLifecycleData>;\n sendDuplicateBill: (input: SendDuplicateBillInput) => Promise<BillLifecycleData>;\n reportBillStatus: (input: ReportBillStatusInput) => Promise<BillLifecycleData>;\n simulateSandbox: (input: SimulateSandboxBillInput) => Promise<BillLifecycleData>;\n clearSession: () => void;\n};\n\nasync function responseError(response: Response, fallback: string): Promise<Error> {\n const body: unknown = await response.json().catch(() => null);\n const detail = body && typeof body === \"object\"\n ? (body as { detail?: unknown; message?: unknown; error?: unknown }).detail\n ?? (body as { message?: unknown }).message\n ?? (body as { error?: unknown }).error\n : null;\n return new Error(typeof detail === \"string\" ? detail : fallback);\n}\n\nfunction isSessionFresh(session: BillLifecycleSession | null): boolean {\n if (!session) return false;\n if (!session.expiresAt) return true;\n const expiresAt = new Date(session.expiresAt).getTime();\n return Number.isFinite(expiresAt) && expiresAt > Date.now() + 30_000;\n}\n\nfunction normalizeSession(value: unknown): BillLifecycleSession {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing session endpoint returned an invalid response.\");\n }\n const candidate = value as { token?: unknown; expiresAt?: unknown; apiBaseUrl?: unknown; session?: unknown; data?: unknown };\n const nested = candidate.session ?? candidate.data;\n const session = nested && typeof nested === \"object\" ? nested as typeof candidate : candidate;\n if (typeof session.token !== \"string\" || session.token.length < 8) {\n throw new Error(\"The billing session endpoint did not return a browser session token.\");\n }\n return {\n token: session.token,\n ...(typeof session.expiresAt === \"string\" ? { expiresAt: session.expiresAt } : {}),\n ...(typeof session.apiBaseUrl === \"string\" ? { apiBaseUrl: session.apiBaseUrl } : {}),\n };\n}\n\nfunction normalizeLifecycle(value: unknown): BillLifecycleData {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n const data = value as Partial<BillLifecycleData>;\n if (\n ![\"sandbox\", \"live\"].includes(data.environment ?? \"\")\n || !data.bill\n || !data.patient\n || !data.injury\n || !data.lifecycle\n || !Array.isArray(data.lifecycle.actions)\n || !Array.isArray(data.eors)\n || !Array.isArray(data.activity)\n || !Array.isArray(data.payments)\n || !data.remittance\n || typeof data.remittance !== \"object\"\n || !data.delivery\n || typeof data.delivery !== \"object\"\n || !data.delivery.contacts\n || typeof data.delivery.contacts !== \"object\"\n || (data.rejection != null && (\n typeof data.rejection !== \"object\"\n || typeof data.rejection.reason !== \"string\"\n || (data.rejection.issues != null && (\n !Array.isArray(data.rejection.issues)\n || data.rejection.issues.some((issue) => (\n !issue\n || typeof issue !== \"object\"\n || typeof issue.description !== \"string\"\n || (issue.code != null && typeof issue.code !== \"string\")\n ))\n ))\n ))\n ) {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n return data as BillLifecycleData;\n}\n\nfunction normalizeDeliveryOptions(value: unknown): BillDeliveryOptions {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n const data = value as Partial<BillDeliveryOptions>;\n if (\n typeof data.payerName !== \"string\"\n || !data.recommended\n || typeof data.recommended !== \"object\"\n || ![\"ebill\", \"fax\", \"mail\", \"email\"].includes(data.recommended.route ?? \"\")\n || !Array.isArray(data.options)\n || !data.contacts\n ) {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n return data as BillDeliveryOptions;\n}\n\nfunction idempotencyKey(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") return globalThis.crypto.randomUUID();\n return `mb-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Browser-safe client for one atomic create-and-submit operation.\n *\n * The browser session is short-lived and origin-bound. The host application\n * never needs the Partner API document schema or a long-lived API key.\n */\nexport function createBillSubmissionClient({\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillSubmissionClientOptions = {}): BillSubmissionClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const submitBill = async (\n input: BrowserBillSubmissionInput,\n options: { idempotencyKey?: string } = {},\n ): Promise<BrowserBillSubmissionResult> => {\n const controller = new AbortController();\n const requestIdempotencyKey = options.idempotencyKey ?? idempotencyKey();\n let browserSession = await mintSession(controller.signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n return fetcher(`${base}/partner/v2/bills`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${current.token}`,\n \"content-type\": \"application/json\",\n \"idempotency-key\": requestIdempotencyKey,\n },\n body: JSON.stringify(input),\n signal: controller.signal,\n });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(controller.signal, true);\n response = await perform(browserSession);\n }\n if (!response.ok) throw await responseError(response, \"The bill could not be submitted.\");\n const body: unknown = await response.json().catch(() => null);\n const envelope = body && typeof body === \"object\" && \"data\" in body\n ? (body as { data?: unknown }).data\n : body;\n if (!envelope || typeof envelope !== \"object\" || typeof (envelope as { id?: unknown }).id !== \"string\") {\n throw new Error(\"The billing service submitted the bill but returned an invalid bill ID.\");\n }\n const bill = envelope as BrowserSubmittedBill;\n return { billId: bill.id, bill };\n };\n\n return {\n submitBill,\n clearSession() { session = null; sessionRequest = null; },\n };\n}\n\n/** Browser-safe, framework-neutral client for an already-submitted bill. */\nexport function createBillLifecycleClient({\n billId,\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillLifecycleClientOptions): BillLifecycleClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n const currentBillId = billId.trim();\n if (!currentBillId) throw new Error(\"billId is required for the submitted-bill lifecycle client.\");\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const request = async (path: string, init: RequestInit = {}, providedSignal?: AbortSignal): Promise<Response> => {\n const controller = providedSignal ? null : new AbortController();\n const signal = providedSignal ?? controller?.signal;\n if (!signal) throw new Error(\"An AbortSignal could not be created.\");\n let browserSession = await mintSession(signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n const headers = new Headers(init.headers);\n headers.set(\"authorization\", `Bearer ${current.token}`);\n return fetcher(`${base}${path}`, { ...init, headers, signal });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(signal, true);\n response = await perform(browserSession);\n }\n return response;\n };\n\n const billPath = (suffix = \"\"): string =>\n `/partner/v2/bills/${encodeURIComponent(currentBillId)}${suffix}`;\n\n const loadLifecycle = async (signal?: AbortSignal) => {\n const response = await request(billPath(\"/lifecycle\"), {}, signal);\n if (!response.ok) throw await responseError(response, \"Bill lifecycle could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n\n const listClaimsAdministrators = async (input: BillReviewPayerListInput = {}): Promise<BillReviewPayerPage> => {\n const params = new URLSearchParams();\n if (input.query?.trim()) params.set(\"q\", input.query.trim());\n if (input.claimNumber?.trim()) params.set(\"claimNumber\", input.claimNumber.trim());\n if (input.sourceClaimsAdministratorName?.trim()) params.set(\"sourceClaimsAdministratorName\", input.sourceClaimsAdministratorName.trim());\n if (input.employerName?.trim()) params.set(\"employerName\", input.employerName.trim());\n const limit = Math.max(1, Math.min(100, Math.floor(input.limit ?? 50)));\n const offset = Math.max(0, Math.floor(input.offset ?? 0));\n params.set(\"limit\", String(limit));\n if (offset) params.set(\"offset\", String(offset));\n const response = await request(`/partner/v2/claims-administrators?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator search is unavailable.\");\n const body = await response.json() as { results?: unknown; suggestions?: unknown; total?: unknown; nextOffset?: unknown; recommendedId?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Claims administrator search returned an invalid response.\");\n const normalizePayer = (value: unknown): BillReviewPayer | null => {\n if (!value || typeof value !== \"object\") return null;\n const payer = value as Record<string, unknown>;\n if (typeof payer.id !== \"string\" || typeof payer.name !== \"string\") return null;\n const payers = Array.isArray(payer.payers) ? payer.payers.flatMap((option): BillReviewPayerOption[] => {\n if (!option || typeof option !== \"object\") return [];\n const candidate = option as Record<string, unknown>;\n const id = typeof candidate.id === \"string\" ? candidate.id : typeof candidate.key === \"string\" ? candidate.key : null;\n if (!id || typeof candidate.label !== \"string\") return [];\n return [{\n id,\n label: candidate.label,\n ...(typeof candidate.default === \"boolean\" ? { default: candidate.default } : {}),\n ...(typeof candidate.active === \"boolean\" ? { active: candidate.active } : {}),\n ...(Array.isArray(candidate.aliases) ? { aliases: candidate.aliases.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof candidate.hint === \"string\" ? { hint: candidate.hint } : {}),\n ...(Array.isArray(candidate.affiliatedEntities) ? { affiliatedEntities: candidate.affiliatedEntities.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof candidate.route === \"string\" ? { route: candidate.route } : {}),\n ...(typeof candidate.optionType === \"string\" ? { optionType: candidate.optionType } : {}),\n ...(typeof candidate.deliveryType === \"string\" ? { deliveryType: candidate.deliveryType } : {}),\n ...(typeof candidate.clearinghouse === \"string\" ? { clearinghouse: candidate.clearinghouse } : {}),\n ...(typeof candidate.payerId === \"string\" ? { payerId: candidate.payerId } : {}),\n ...(typeof candidate.sourceClearinghouse === \"string\" ? { sourceClearinghouse: candidate.sourceClearinghouse } : {}),\n ...(typeof candidate.sourcePayerId === \"string\" ? { sourcePayerId: candidate.sourcePayerId } : {}),\n ...(candidate.clearinghousePayerIds && typeof candidate.clearinghousePayerIds === \"object\" && !Array.isArray(candidate.clearinghousePayerIds)\n ? { clearinghousePayerIds: Object.fromEntries(Object.entries(candidate.clearinghousePayerIds).filter((entry): entry is [string, string] => typeof entry[1] === \"string\")) }\n : {}),\n ...(typeof candidate.preferredClearinghouse === \"string\" ? { preferredClearinghouse: candidate.preferredClearinghouse } : {}),\n }];\n }) : undefined;\n const claimNumberPatterns = Array.isArray(payer.claimNumberPatterns) ? payer.claimNumberPatterns.flatMap((value): BillClaimsAdministratorPattern[] => {\n if (!value || typeof value !== \"object\") return [];\n const pattern = value as Record<string, unknown>;\n if (typeof pattern.pattern !== \"string\") return [];\n return [{\n pattern: pattern.pattern,\n ...(typeof pattern.length === \"string\" || typeof pattern.length === \"number\" ? { length: pattern.length } : {}),\n ...(typeof pattern.example === \"string\" ? { example: pattern.example } : {}),\n ...(typeof pattern.matches === \"boolean\" || pattern.matches === null ? { matches: pattern.matches as boolean | null } : {}),\n }];\n }) : undefined;\n return {\n id: payer.id,\n name: payer.name,\n ...(typeof payer.hasElectronic === \"boolean\" ? { hasElectronic: payer.hasElectronic } : {}),\n ...(Array.isArray(payer.states) ? { states: payer.states.filter((state): state is string => typeof state === \"string\") } : {}),\n ...([\"high\", \"medium\", \"directory\"].includes(String(payer.confidence)) ? { confidence: payer.confidence as NonNullable<BillReviewPayer[\"confidence\"]> } : {}),\n ...(typeof payer.recommended === \"boolean\" ? { recommended: payer.recommended } : {}),\n ...(typeof payer.payerSelectionRequired === \"boolean\" ? { payerSelectionRequired: payer.payerSelectionRequired } : {}),\n ...(payers ? { payers } : {}),\n ...(Array.isArray(payer.aliases) ? { aliases: payer.aliases.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(Array.isArray(payer.affiliatedEntities) ? { affiliatedEntities: payer.affiliatedEntities.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof payer.claimNumberHint === \"string\" ? { claimNumberHint: payer.claimNumberHint } : {}),\n ...(claimNumberPatterns ? { claimNumberPatterns } : {}),\n ...(typeof payer.route === \"string\" ? { route: payer.route } : {}),\n ...(Array.isArray(payer.signals) ? { signals: payer.signals.flatMap((signal) => {\n if (!signal || typeof signal !== \"object\") return [];\n const candidate = signal as Record<string, unknown>;\n if (![\"name\", \"claim_number\"].includes(String(candidate.kind)) || ![\"match\", \"warning\"].includes(String(candidate.state)) || typeof candidate.label !== \"string\") return [];\n return [{ kind: candidate.kind as \"name\" | \"claim_number\", state: candidate.state as \"match\" | \"warning\", label: candidate.label }];\n }) } : {}),\n };\n };\n const results = body.results.flatMap((value): BillReviewPayer[] => {\n const payer = normalizePayer(value);\n return payer ? [payer] : [];\n });\n const suggestions = Array.isArray(body.suggestions) ? body.suggestions.flatMap((value): BillReviewPayerSuggestion[] => {\n const payer = normalizePayer(value);\n if (!payer || !value || typeof value !== \"object\") return [];\n const suggestion = value as Record<string, unknown>;\n if (typeof suggestion.deterministic !== \"boolean\" || typeof suggestion.reason !== \"string\") return [];\n return [{ ...payer, deterministic: suggestion.deterministic, reason: suggestion.reason, ...(typeof suggestion.selectedPayerId === \"string\" ? { selectedPayerId: suggestion.selectedPayerId } : {}) }];\n }) : [];\n const total = typeof body.total === \"number\" && Number.isFinite(body.total) ? Math.max(results.length, Math.floor(body.total)) : offset + results.length;\n return {\n results,\n ...(suggestions.length ? { suggestions } : {}),\n total,\n ...(typeof body.nextOffset === \"number\" && Number.isFinite(body.nextOffset) ? { nextOffset: Math.floor(body.nextOffset) } : {}),\n ...(typeof body.recommendedId === \"string\" ? { recommendedId: body.recommendedId } : {}),\n };\n };\n\n const searchClaimsAdministrators = async (query: string, claimNumber?: string): Promise<BillReviewPayer[]> =>\n (await listClaimsAdministrators({ query, ...(claimNumber ? { claimNumber } : {}) })).results;\n\n const getClaimsAdministratorDirectory = async (id: string, injuryState?: string): Promise<BillClaimsAdministratorDirectory> => {\n const params = new URLSearchParams();\n if (injuryState?.trim()) params.set(\"injuryState\", injuryState.trim());\n const response = await request(`/partner/v2/claims-administrators/${encodeURIComponent(id)}${params.size ? `?${params}` : \"\"}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator details are unavailable.\");\n const body = await response.json() as { data?: unknown };\n if (!body.data || typeof body.data !== \"object\") throw new Error(\"Claims administrator details returned an invalid response.\");\n return body.data as BillClaimsAdministratorDirectory;\n };\n\n const searchDiagnosisCodes = async (query: string, limit = 30, offset = 0): Promise<BillDiagnosisCode[]> => {\n const params = new URLSearchParams({ q: query.trim(), limit: String(Math.max(1, Math.min(100, limit))) });\n if (offset > 0) params.set(\"offset\", String(Math.max(0, Math.floor(offset))));\n const response = await request(`/partner/v2/diagnosis-codes?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Diagnosis-code search is unavailable.\");\n const body = await response.json() as { results?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Diagnosis-code search returned an invalid response.\");\n return body.results.flatMap((value): BillDiagnosisCode[] => {\n if (!value || typeof value !== \"object\") return [];\n const candidate = value as { code?: unknown; description?: unknown };\n return typeof candidate.code === \"string\" && typeof candidate.description === \"string\"\n ? [{ code: candidate.code, description: candidate.description }]\n : [];\n });\n };\n\n const searchProcedureCodes = async (input: BillProcedureCodeSearchInput = {}): Promise<BillProcedureCodePage> => {\n const limit = Number.isFinite(input.limit) ? Math.max(1, Math.min(100, Math.floor(input.limit!))) : 30;\n const params = new URLSearchParams({ q: input.query?.trim() ?? \"\", limit: String(limit), jurisdiction: input.jurisdiction?.trim().toUpperCase() || \"CA\" });\n const response = await request(`/partner/v2/procedure-codes?${params}`);\n if (!response.ok) throw await responseError(response, \"Procedure-code search is unavailable.\");\n const body = await response.json() as Partial<BillProcedureCodePage>;\n if (!Array.isArray(body.results) || typeof body.total !== \"number\" || !Number.isFinite(body.total) || body.total < 0 || typeof body.limit !== \"number\" || !Number.isFinite(body.limit) || body.limit < 1 || ![\"CA\", \"NY\", \"OWCP\"].includes(body.jurisdiction ?? \"\") || !(body.catalogAsOf === null || typeof body.catalogAsOf === \"string\")) {\n throw new Error(\"Procedure-code search returned an invalid response.\");\n }\n return {\n results: body.results.flatMap((entry) => entry && typeof entry.code === \"string\" && entry.code.trim() ? [{ code: entry.code }] : []),\n total: body.total,\n limit: body.limit,\n jurisdiction: body.jurisdiction!,\n catalogAsOf: body.catalogAsOf,\n };\n };\n\n const quoteClaimFees = async (input: CaClaimFeeQuoteInput): Promise<CaClaimFeeQuoteResult> => {\n const response = await request(\"/partner/v2/fee-quotes/ca/claim\", {\n method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify(input),\n });\n if (!response.ok) throw await responseError(response, \"Claim fee pricing is unavailable.\");\n const body = await response.json() as { data?: unknown };\n return parseCaClaimFeeQuote(body.data, input);\n };\n\n const quoteFee = async (input: BillFeeQuoteInput): Promise<BillFeeQuote> => {\n const response = await request(\"/partner/v2/fee-quotes\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n });\n if (!response.ok) throw await responseError(response, \"Fee-schedule pricing is unavailable.\");\n const body = await response.json() as { data?: BillFeeQuote };\n const quote = body.data;\n if (!quote || !Array.isArray(quote.provenance)) throw new Error(\"Fee quote returned an invalid response.\");\n if (quote.status === \"priced\") {\n if (!Number.isSafeInteger(quote.amountCents) || quote.amountCents < 0 || !Number.isSafeInteger(quote.scheduleMaximumCents) || quote.scheduleMaximumCents < 0 || !BILL_FEE_QUOTE_BASES.includes(quote.basis) || !Array.isArray(quote.notes) || quote.notes.some((note) => typeof note !== \"string\")) throw new Error(\"Fee quote returned an invalid response.\");\n } else if ((quote.status !== \"requires_review\" && quote.status !== \"not_separately_payable\") || typeof quote.reason !== \"string\") {\n throw new Error(\"Fee quote returned an invalid response.\");\n }\n return quote;\n };\n\n const lookupPostalCode = async (postalCode: string): Promise<BillPostalPlace | null> => {\n const params = new URLSearchParams({ postalCode: postalCode.trim() });\n const response = await request(`/partner/v2/postal-codes?${params.toString()}`);\n if (response.status === 404) return null;\n if (!response.ok) throw await responseError(response, \"ZIP lookup is unavailable.\");\n const body = await response.json() as { city?: unknown; state?: unknown };\n if (typeof body.city !== \"string\" || typeof body.state !== \"string\") {\n throw new Error(\"ZIP lookup returned an invalid response.\");\n }\n return { city: body.city, state: body.state };\n };\n\n const mutation = async (path: string, init: RequestInit, fallback: string) => {\n const headers = new Headers(init.headers);\n headers.set(\"idempotency-key\", idempotencyKey());\n const response = await request(path, { ...init, headers });\n if (!response.ok) throw await responseError(response, fallback);\n return response;\n };\n const action = async (input: Record<string, unknown>, fallback: string): Promise<BillLifecycleData> => {\n const response = await mutation(billPath(\"/actions\"), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, fallback);\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n const simulateSandbox = async (input: SimulateSandboxBillInput): Promise<BillLifecycleData> => {\n await mutation(`/partner/v2/sandbox/bills/${encodeURIComponent(currentBillId)}/simulate`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, \"Sandbox lifecycle could not be simulated.\");\n return loadLifecycle();\n };\n return {\n getBillId() { return currentBillId; },\n clearSession() { session = null; sessionRequest = null; },\n getLifecycle: loadLifecycle,\n listClaimsAdministrators,\n searchClaimsAdministrators,\n getClaimsAdministratorDirectory,\n searchDiagnosisCodes,\n searchProcedureCodes,\n quoteFee,\n quoteClaimFees,\n lookupPostalCode,\n async getDeliveryOptions() {\n const response = await request(billPath(\"/delivery-options\"));\n if (!response.ok) throw await responseError(response, \"Delivery options could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getDeliveryPreview(input) {\n const params = new URLSearchParams({ claimsAdministratorId: input.claimsAdministratorId.trim() });\n if (input.payerId?.trim()) params.set(\"payerId\", input.payerId.trim());\n if (input.injuryState?.trim()) params.set(\"injuryState\", input.injuryState.trim());\n const response = await request(`/partner/v2/delivery-preview?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Delivery routes could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getAttachment(attachmentId) {\n const response = await request(billPath(`/documents/${encodeURIComponent(attachmentId)}`));\n if (!response.ok) throw await responseError(response, \"Document could not be opened.\");\n return response.blob();\n },\n async getEor(documentId) {\n const response = await request(billPath(`/eors/${encodeURIComponent(documentId)}`));\n if (!response.ok) throw await responseError(response, \"EOR could not be opened.\");\n return response.blob();\n },\n async getPacket() {\n const response = await request(billPath(\"/packet\"));\n if (!response.ok) throw await responseError(response, \"Submission packet could not be downloaded.\");\n return response.blob();\n },\n async getSubmissionArtifact(attemptId, artifactId) {\n const response = await request(billPath(`/submissions/${encodeURIComponent(attemptId)}/artifacts/${encodeURIComponent(artifactId)}`));\n if (!response.ok) throw await responseError(response, \"The retained submission file could not be downloaded.\");\n return response.blob();\n },\n async prepareIbrPacket() {\n const prepared = await mutation(billPath(\"/actions\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ action: \"independent_bill_review\" }),\n }, \"IBR packet could not be prepared.\");\n const body = await prepared.json() as { packetUrl?: unknown };\n // Never forward the browser bearer token to an arbitrary response URL.\n if (typeof body.packetUrl !== \"string\" || !/^\\/partner\\/v2\\/(?:browser\\/)?bills\\/[A-Za-z0-9_-]+\\/ibr-packet$/.test(body.packetUrl)) throw new Error(\"The billing service returned an invalid IBR packet path.\");\n // The server may resolve a root bill to its current linked bill.\n const response = await request(body.packetUrl);\n if (!response.ok) throw await responseError(response, \"IBR packet could not be downloaded.\");\n return response.blob();\n },\n async previewCourtesyCopy(input) {\n const response = await request(billPath(\"/courtesy-forward\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ ...input, mode: \"preview\" }),\n });\n if (!response.ok) throw await responseError(response, \"Courtesy copy could not be previewed.\");\n return response.json() as Promise<BillCourtesyCopyPreview>;\n },\n async sendCourtesyCopy(input, key) {\n if (!key.trim() || key.length > 255) throw new Error(\"A stable idempotency key is required to send a courtesy copy.\");\n const response = await request(billPath(\"/courtesy-forward\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\", \"idempotency-key\": key },\n body: JSON.stringify({ ...input, mode: \"send\" }),\n });\n if (!response.ok) throw await responseError(response, \"Courtesy copy could not be sent. Retry with the same key to check the result safely.\");\n return response.json() as Promise<BillCourtesyCopyResult>;\n },\n addNote(input) { return action({ action: \"add_note\", ...input }, \"Note could not be added.\"); },\n closeBill(input) { return action({ action: \"close\", ...input }, \"Bill could not be closed.\"); },\n reopenBill(input) { return action({ action: \"reopen\", ...input }, \"Bill could not be reopened.\"); },\n postPayment(input) { return action({ action: \"post_payment\", penaltyAmount: 0, interestAmount: 0, ...input, checkNumber: input.checkNumber ?? \"\" }, \"Payment could not be posted.\"); },\n submitSecondReview(input) { return action({ action: \"second_review\", ...input }, \"Second Review could not be submitted.\"); },\n resubmitBill(input) { return action({ action: \"resubmit\", ...input }, \"Bill could not be resubmitted.\"); },\n submitNewBill(input) { return action({ action: \"submit_new_bill\", ...input }, \"The new bill could not be submitted.\"); },\n sendDuplicateBill(input) { return action({ action: \"send_duplicate\", ...input }, \"Duplicate bill could not be sent.\"); },\n reportBillStatus(input) { return action({ action: \"report_bill_status\", ...input }, \"Bill status could not be reported.\"); },\n simulateSandbox,\n };\n}\n\n/**\n * Browser-safe client for reference data needed before a bill exists.\n *\n * Partners can pass the same short-lived session provider used by the submitted-bill\n * lifecycle without inventing a draft bill or exposing payer directory credentials.\n */\nexport function createBillReferenceClient(\n options: BillReferenceClientOptions = {},\n): BillReferenceClient {\n const lifecycle = createBillLifecycleClient({\n ...options,\n billId: \"pre-submission-reference-data\",\n });\n return {\n listClaimsAdministrators: lifecycle.listClaimsAdministrators,\n searchClaimsAdministrators: lifecycle.searchClaimsAdministrators,\n getClaimsAdministratorDirectory: lifecycle.getClaimsAdministratorDirectory,\n searchDiagnosisCodes: lifecycle.searchDiagnosisCodes,\n searchProcedureCodes: lifecycle.searchProcedureCodes,\n quoteFee: lifecycle.quoteFee,\n quoteClaimFees: lifecycle.quoteClaimFees,\n lookupPostalCode: lifecycle.lookupPostalCode,\n getDeliveryPreview: lifecycle.getDeliveryPreview,\n clearSession: lifecycle.clearSession,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Organization profile client (INC-1470): backs the embeddable\n// OrganizationOnboarding / BillingSettings components. Requires a browser\n// session minted with organization:manage for administrative operations.\n// Read-only saved billing profiles need only an org-wide bills:create session.\n\n/** Convert masked profile state to a write without clearing an unchanged saved SSN. */\nexport function organizationTaxIdWrite<T extends { taxId?: string; taxIdType?: \"EIN\" | \"SSN\"; taxIdLast4?: string; taxIdConfigured?: boolean }>(value: T): Omit<T, \"taxIdLast4\" | \"taxIdConfigured\"> {\n const input = { ...value };\n delete input.taxIdLast4;\n delete input.taxIdConfigured;\n if (value.taxIdType === \"SSN\" && value.taxIdConfigured && !value.taxId?.trim()) delete input.taxId;\n return input;\n}\n\nexport type OrganizationPracticeIdentity = {\n name?: string; legalName?: string; taxId?: string; npi?: string;\n taxIdType?: \"EIN\" | \"SSN\";\n /** Read-only metadata. Saved SSNs are never returned in taxId. */\n taxIdLast4?: string; taxIdConfigured?: boolean;\n phone?: string; email?: string; website?: string;\n};\n\nexport type OrganizationBillingProviderInput = {\n id?: string; externalId?: string; name: string; taxId?: string; npi: string;\n taxIdType?: \"EIN\" | \"SSN\";\n /** Read-only metadata; omit taxId on updates to preserve a saved SSN. */\n taxIdLast4?: string; taxIdConfigured?: boolean;\n billType?: \"Professional\" | \"Institutional\"; phone?: string;\n billingStreet?: string; billingCity?: string; billingState?: string; billingZip?: string;\n};\n\nexport type OrganizationLocationInput = {\n id?: string; externalId?: string; name: string; street: string; city: string;\n state: string; zip: string; nickname?: string; posCode?: string;\n isPrimary?: boolean; active?: boolean;\n};\n\nexport type OrganizationRenderingProviderInput = {\n id?: string; externalId?: string; name: string; npi: string; specialty?: string;\n taxonomy?: string; licenseNumber?: string; licenseState?: string;\n isQME?: boolean; isAME?: boolean; email?: string; active?: boolean;\n};\n\nexport type OrganizationChecklistItem = { id: string; label: string; complete: boolean };\n\nexport type OrganizationProfileData = {\n organizationId: string;\n practiceIdentity: OrganizationPracticeIdentity;\n billingProviders: Array<OrganizationBillingProviderInput & { id: string }>;\n /** Optional for compatibility with older organization-profile responses. */\n renderingProviders?: Array<OrganizationRenderingProviderInput & { id: string }>;\n locations: Array<OrganizationLocationInput & { id: string }>;\n w9: { filename: string; addDate: string; taxYear?: number } | null;\n onboarding: { status: string | null; complete: boolean; checklist: OrganizationChecklistItem[] };\n};\n\nexport type OrganizationClientOptions = {\n sessionEndpoint?: string;\n getSession?: BillLifecycleSessionProvider;\n apiBaseUrl?: string;\n fetch?: typeof globalThis.fetch;\n};\n\nexport type OrganizationTeamRole = \"admin\" | \"manager\" | \"biller\" | \"payments\" | \"viewer\";\nexport type OrganizationTeamMember = {\n id: string; email: string; name: string; role: string; active: boolean;\n createdAt: string; canManage: boolean;\n};\nexport type OrganizationTeam = {\n members: OrganizationTeamMember[];\n roles: Array<{ id: OrganizationTeamRole; label: string; permissions: string[] }>;\n capabilities: { canManage: boolean; canAdd: boolean };\n identityDomain: \"mindbill\";\n};\nexport type OrganizationClaimsAdministratorInput = {\n name: string; fax?: string; email?: string; mailingAddress?: string; notes?: string;\n};\nexport type OrganizationClaimsAdministrator = {\n id: string; name: string; fax: string | null; email: string | null;\n mailingAddress: string | null; notes: string | null; submissionMethod: string;\n active: boolean; createdAt: string;\n};\n\nexport type OrganizationClient = {\n /** Requires explicit team:manage; organization:manage alone does not grant team access. */\n getTeam: () => Promise<OrganizationTeam>;\n updateTeamMember: (id: string, input: { role?: OrganizationTeamRole; active?: boolean }) => Promise<OrganizationTeamMember>;\n getClaimsAdministrators: () => Promise<OrganizationClaimsAdministrator[]>;\n createClaimsAdministrator: (input: OrganizationClaimsAdministratorInput) => Promise<OrganizationClaimsAdministrator>;\n updateClaimsAdministrator: (id: string, input: OrganizationClaimsAdministratorInput) => Promise<OrganizationClaimsAdministrator>;\n deleteClaimsAdministrator: (id: string) => Promise<{ id: string; deleted: true }>;\n\n getOrganization: () => Promise<OrganizationProfileData>;\n /** Masked saved profiles for bill entry; requires org-wide bills:create. */\n getBillingProfile: () => Promise<OrganizationProfileData>;\n saveBillingProfile: (input: {\n practiceIdentity?: OrganizationPracticeIdentity;\n billingProviders?: OrganizationBillingProviderInput[];\n renderingProviders?: OrganizationRenderingProviderInput[];\n }) => Promise<OrganizationProfileData>;\n saveLocations: (locations: OrganizationLocationInput[]) => Promise<OrganizationProfileData>;\n saveW9: (input: { filename: string; contentBase64: string; taxYear?: number }) => Promise<OrganizationProfileData>;\n};\n\nexport function createOrganizationClient({\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: OrganizationClientOptions = {}): OrganizationClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n\n const mintSession = async (force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n const pending = getSession\n ? getSession({ signal: new AbortController().signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The organization session could not be created.\");\n return response.json();\n });\n session = normalizeSession(await Promise.resolve(pending));\n return session;\n };\n\n const request = async <T = OrganizationProfileData>(path: string, init: RequestInit = {}): Promise<T> => {\n let current = await mintSession();\n const perform = (active: BillLifecycleSession) => {\n const base = (active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n const headers = new Headers(init.headers);\n headers.set(\"authorization\", `Bearer ${active.token}`);\n if (init.body) headers.set(\"content-type\", \"application/json\");\n return fetcher(`${base}${path}`, { ...init, headers });\n };\n let response = await perform(current);\n if (response.status === 401) {\n current = await mintSession(true);\n response = await perform(current);\n }\n if (!response.ok) throw await responseError(response, \"The organization request failed.\");\n const body = (await response.json()) as { data?: T };\n if (!body.data || typeof body.data !== \"object\") {\n throw new Error(\"The organization response was invalid.\");\n }\n return body.data;\n };\n\n return {\n getTeam: () => request<OrganizationTeam>(\"/partner/v2/organization/team\"),\n updateTeamMember: (id, input) => request<OrganizationTeamMember>(`/partner/v2/organization/team/${encodeURIComponent(id)}`, { method: \"PATCH\", body: JSON.stringify(input) }),\n getClaimsAdministrators: () => request<OrganizationClaimsAdministrator[]>(\"/partner/v2/organization/claims-administrators\"),\n createClaimsAdministrator: (input) => request<OrganizationClaimsAdministrator>(\"/partner/v2/organization/claims-administrators\", { method: \"POST\", body: JSON.stringify(input) }),\n updateClaimsAdministrator: (id, input) => request<OrganizationClaimsAdministrator>(`/partner/v2/organization/claims-administrators/${encodeURIComponent(id)}`, { method: \"PATCH\", body: JSON.stringify(input) }),\n deleteClaimsAdministrator: (id) => request<{ id: string; deleted: true }>(`/partner/v2/organization/claims-administrators/${encodeURIComponent(id)}`, { method: \"DELETE\" }),\n getOrganization: () => request(\"/partner/v2/organization\"),\n getBillingProfile: () => request(\"/partner/v2/organization/billing-profile\"),\n saveBillingProfile: (input) =>\n request(\"/partner/v2/organization/billing-profile\", { method: \"PUT\", body: JSON.stringify({\n ...input,\n ...(input.practiceIdentity ? { practiceIdentity: organizationTaxIdWrite(input.practiceIdentity) } : {}),\n ...(input.billingProviders ? { billingProviders: input.billingProviders.map(organizationTaxIdWrite) } : {}),\n }) }),\n saveLocations: (locations) =>\n request(\"/partner/v2/organization/locations\", { method: \"PUT\", body: JSON.stringify({ locations }) }),\n saveW9: (input) =>\n request(\"/partner/v2/organization/w9\", { method: \"PUT\", body: JSON.stringify(input) }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Bill Tasks dashboard: a pure, framework-neutral\n// aggregation shared by the React and Angular components. Hosts flatten their\n// own work items and get back per-section rows bucketed by age in days.\n\nexport type BillTasksAgingBucket = {\n id: string;\n label: string;\n /** Exclusive lower bound in days. The first bucket also admits day 0. */\n minDays: number;\n /** Inclusive upper bound in days; null means unbounded. */\n maxDays: number | null;\n};\n\nexport const BILL_TASKS_AGING_BUCKETS: BillTasksAgingBucket[] = [\n { id: \"1-30\", label: \"1-30 Days Ago\", minDays: 0, maxDays: 30 },\n { id: \"31-60\", label: \"31-60 Days Ago\", minDays: 30, maxDays: 60 },\n { id: \"61-90\", label: \"61-90 Days Ago\", minDays: 60, maxDays: 90 },\n { id: \"91-180\", label: \"91-180 Days Ago\", minDays: 90, maxDays: 180 },\n { id: \"181+\", label: \"181+ Days Ago\", minDays: 180, maxDays: null },\n];\n\nexport type BillTasksDashboardItem = {\n sectionId: string;\n rowId: string;\n rowLabel: string;\n ageDays: number;\n balanceDue?: number;\n /** Opaque bill reference echoed back in click-through payloads. */\n ref?: string;\n};\n\nexport type BillTasksDashboardRow = {\n id: string;\n label: string;\n /** One count per aging bucket, in bucket order. */\n counts: number[];\n total: number;\n /** Summed item balanceDue per bucket; optional for older count-only payloads. */\n balances?: number[];\n balanceTotal?: number;\n /** Collected item refs per aging bucket, in bucket order. */\n refs: string[][];\n};\n\nexport type BillTasksDashboardTone = \"violet\" | \"red\" | \"blue\" | \"green\" | \"amber\" | \"neutral\";\n\nexport type BillTasksDashboardSectionInput = {\n id: string;\n label: string;\n /** Shown under the section label as \"by {agingBasisLabel}\". */\n agingBasisLabel: string;\n tone: BillTasksDashboardTone;\n};\n\nexport type BillTasksDashboardSection = BillTasksDashboardSectionInput & {\n rows: BillTasksDashboardRow[];\n /** Per-bucket totals across the section's rows. */\n totals: number[];\n total: number;\n balanceTotals?: number[];\n balanceTotal?: number;\n empty: boolean;\n};\n\nexport type BillTasksDashboardData = {\n sections: BillTasksDashboardSection[];\n grandTotals: number[];\n grandTotal: number;\n /** Work-item sums, not deduplicated financial A/R across task categories. */\n grandBalanceTotals?: number[];\n grandBalanceTotal?: number;\n};\n\n/**\n * Bucket index for an item age: a bucket admits `minDays < ageDays <= maxDays`\n * (`maxDays: null` = unbounded) and the first bucket also admits day 0.\n * Ages beyond every bucket clamp into the last bucket.\n */\nexport function billTasksAgingBucketIndex(\n ageDays: number,\n buckets: BillTasksAgingBucket[] = BILL_TASKS_AGING_BUCKETS,\n): number {\n const days = Math.max(0, Math.floor(ageDays));\n const index = buckets.findIndex((bucket, position) =>\n (bucket.maxDays === null || days <= bucket.maxDays)\n && (days > bucket.minDays || position === 0));\n return index === -1 ? buckets.length - 1 : index;\n}\n\n/**\n * Aggregates flat work items into the Bill Tasks dashboard.\n * Sections render in the given order even when empty; rows appear in\n * first-seen item order within their section.\n */\nexport function buildBillTasksDashboard(\n items: BillTasksDashboardItem[],\n sections: BillTasksDashboardSectionInput[],\n buckets: BillTasksAgingBucket[] = BILL_TASKS_AGING_BUCKETS,\n): BillTasksDashboardData {\n const zeros = () => buckets.map(() => 0);\n const built = sections.map((section): BillTasksDashboardSection => ({\n ...section,\n rows: [],\n totals: zeros(),\n total: 0,\n balanceTotals: zeros(),\n balanceTotal: 0,\n empty: true,\n }));\n const sectionById = new Map(built.map((section) => [section.id, section]));\n const rowByKey = new Map<string, BillTasksDashboardRow>();\n const grandTotals = zeros();\n let grandTotal = 0;\n const grandBalanceTotals = zeros();\n let grandBalanceTotal = 0;\n\n for (const item of items) {\n const section = sectionById.get(item.sectionId);\n if (!section) continue;\n const key = `${item.sectionId}\\u0000${item.rowId}`;\n let row = rowByKey.get(key);\n if (!row) {\n row = {\n id: item.rowId,\n label: item.rowLabel,\n counts: zeros(),\n total: 0,\n balances: zeros(),\n balanceTotal: 0,\n refs: buckets.map(() => []),\n };\n rowByKey.set(key, row);\n section.rows.push(row);\n section.empty = false;\n }\n const bucketIndex = billTasksAgingBucketIndex(item.ageDays, buckets);\n const balance = Number.isFinite(item.balanceDue) ? item.balanceDue! : 0;\n row.counts[bucketIndex] = (row.counts[bucketIndex] ?? 0) + 1;\n row.total += 1;\n row.balances![bucketIndex] = (row.balances![bucketIndex] ?? 0) + balance;\n row.balanceTotal = (row.balanceTotal ?? 0) + balance;\n if (item.ref) row.refs[bucketIndex]?.push(item.ref);\n section.totals[bucketIndex] = (section.totals[bucketIndex] ?? 0) + 1;\n section.total += 1;\n section.balanceTotals![bucketIndex] = (section.balanceTotals![bucketIndex] ?? 0) + balance;\n section.balanceTotal = (section.balanceTotal ?? 0) + balance;\n grandTotals[bucketIndex] = (grandTotals[bucketIndex] ?? 0) + 1;\n grandTotal += 1;\n grandBalanceTotals[bucketIndex] = (grandBalanceTotals[bucketIndex] ?? 0) + balance;\n grandBalanceTotal += balance;\n }\n\n return { sections: built, grandTotals, grandTotal, grandBalanceTotals, grandBalanceTotal };\n}\n\n\n/** An unsigned RFA preparation draft. Signing and sending are separate operations. */\nexport type RfaCreateDraftInput = {\n claimId: string; patientId: string; renderingProviderId: string; employeeName: string; providerName: string;\n externalId?: string; claimsAdminId?: string;\n requestType?: \"new\" | \"resubmission_material_change\" | \"oral_authorization_confirmation\";\n reviewType?: \"prospective\" | \"concurrent\" | \"retrospective\"; expedited?: boolean;\n placeOfServiceCode?: string; providerNpi?: string; providerPhone?: string; providerFax?: string;\n claimNumber?: string; dateOfInjury?: string; rationale?: string; materialChange?: string;\n items: Array<{ externalId?: string; diagnosisCode: string; serviceDescription: string; procedureCode?: string;\n quantity?: number; units?: number; frequency?: string; duration?: string; requestedFrom?: string; requestedTo?: string; metadata?: Record<string, unknown> }>;\n metadata?: Record<string, unknown>;\n};\n/** Full replacement of editable request content; retained service rows keep their IDs. */\nexport type RfaUpdateDraftInput = Omit<RfaCreateDraftInput, \"externalId\" | \"claimId\" | \"patientId\" | \"renderingProviderId\" | \"items\"> & {\n expectedRevision: number;\n items: Array<Omit<RfaCreateDraftInput[\"items\"][number], \"externalId\"> & { id?: string }>;\n};\nexport type RfaRecord = {\n contentRevision: number; id: string; claimId: string; patientId: string; renderingProviderId: string; claimsAdminId: string | null;\n employeeName: string; providerName: string; claimNumber: string | null; status: string;\n requestType?: RfaCreateDraftInput[\"requestType\"];\n placeOfServiceCode?: string | null; providerNpi?: string | null; providerPhone?: string | null; providerFax?: string | null;\n dateOfInjury?: string | null; rationale?: string | null; materialChange?: string | null; metadata?: Record<string, unknown>;\n reviewType: string; expedited: boolean; createdAt: string | null; updatedAt: string | null;\n signedAt: string | null; submittedAt: string | null; receivedAt: string | null;\n decisionDueAt: string | null; decisionDeadlineBasis: string | null;\n incompleteReason: string | null; deferredReason: string | null; closedReason: string | null;\n readiness: { ready: boolean; missing: string[] };\n items: Array<{ id: string; diagnosisCode: string; serviceDescription: string; procedureCode: string | null;\n frequency?: string | null; duration?: string | null; requestedFrom?: string | null; requestedTo?: string | null; metadata?: Record<string, unknown>;\n outcome: string; quantity: number | null; units: number | null; authorizationNumber: string | null; decisionReason: string | null }>;\n documents: Array<{ id: string; documentType: string; filename: string; contentUrl: string; contentRevision: number | null; createdAt: string | null }>;\n transmissions: Array<{ id: string; purpose?: string; direction: string; channel: string; status: string; destination: string | null;\n occurredAt: string | null; receivedAt: string | null; proofDocumentId: string | null; providerMessageId: string | null }>;\n informationRequests: Array<{ id: string; requestText: string; requestedAt: string | null; dueAt: string | null; respondedAt: string | null }>;\n events: Array<{ id: string; type: string; occurredAt: string | null }>;\n};\nexport type RfaListQuery = { claimId?: string; renderingProviderId?: string; status?: string; createdFrom?: string; createdTo?: string; limit?: number; cursor?: string };\nexport type RfaListResult = { data: RfaRecord[]; nextCursor: string | null; summary: { total: number; byStatus: Record<string, number> } };\nexport type RfaSigningPreviewInput = { billingProviderId?: string; diagnosisDescriptions: Record<string, string> };\nexport type RfaSigningPreview = { id: string; contentHash: string; contentRevision: number; renderingProviderId: string; previewDocumentId: string; expiresAt: string };\nexport type RfaSignInput = { snapshotId: string; contentHash: string; renderingProviderId: string; physicianAuthorized: true; actorReference: string };\nexport type RfaFaxInput = { to: string; documentIds: string[]; nonBusinessDates?: string[] };\nexport type RfaUploadDocumentInput = { file: File; documentType: \"clinical_report\" | \"supporting_record\" | \"ur_response\" | \"imr_form\" | \"other\"; contentRevision: number };\nexport type RfaCreationClaim = { claimId: string; patientId: string; employeeName: string; claimNumber?: string; dateOfInjury?: string; claimsAdminId?: string };\nexport type RfaCreationProvider = { id: string; name: string; npi?: string };\nexport type RfaCreationContext = { claims: RfaCreationClaim[]; renderingProviders: RfaCreationProvider[]; nextCursor: string | null; renderingProvidersNextCursor: string | null };\nexport type RfaCreationContextQuery = { search?: string; cursor?: string; providerSearch?: string; providerCursor?: string; limit?: number; claimId?: string; renderingProviderId?: string };\nexport type RfaClient = {\n getCreationContext: (query?: RfaCreationContextQuery) => Promise<RfaCreationContext>;\n list: (query?: RfaListQuery) => Promise<RfaListResult>;\n get: (rfaId: string) => Promise<RfaRecord>;\n createDraft: (draft: RfaCreateDraftInput, idempotencyKey: string) => Promise<RfaRecord>;\n updateDraft: (rfaId: string, draft: RfaUpdateDraftInput, idempotencyKey: string) => Promise<RfaRecord>;\n getDocument: (rfaId: string, documentId: string) => Promise<Blob>;\n uploadDocument: (rfaId: string, input: RfaUploadDocumentInput, idempotencyKey: string) => Promise<RfaRecord>;\n prepareSigning: (rfaId: string, input: RfaSigningPreviewInput, idempotencyKey: string) => Promise<RfaSigningPreview>;\n sign: (rfaId: string, input: RfaSignInput, idempotencyKey: string) => Promise<RfaRecord>;\n previewPacket: (rfaId: string, documentIds: string[]) => Promise<Blob>;\n sendFax: (rfaId: string, input: RfaFaxInput, idempotencyKey: string) => Promise<RfaRecord>;\n refreshFaxes: (rfaId: string, idempotencyKey: string) => Promise<RfaRecord>;\n};\n/** Uses short-lived browser credentials. Never pass a partner API key. */\nexport function createRfaClient({ sessionEndpoint = DEFAULT_SESSION_ENDPOINT, getSession, apiBaseUrl = DEFAULT_API_BASE_URL, fetch: fetchOverride }: OrganizationClientOptions = {}): RfaClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n let pending: Promise<BillLifecycleSession> | null = null;\n const mint = (force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return Promise.resolve(session as BillLifecycleSession);\n if (pending) return pending;\n pending = (async () => {\n const value = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await responseError(response, \"The RFA session could not be created.\");\n return response.json();\n })();\n session = normalizeSession(value); return session;\n })().finally(() => { pending = null; });\n return pending;\n };\n const request = async (path: string, init: RequestInit = {}, browser = false) => {\n const perform = (active: BillLifecycleSession) => {\n const headers = new Headers(init.headers); headers.set(\"authorization\", `Bearer ${active.token}`);\n if (init.body && !(init.body instanceof FormData)) headers.set(\"content-type\", \"application/json\");\n return fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/${browser ? \"browser/\" : \"\"}rfas${path}`, { ...init, headers });\n };\n let response = await perform(await mint());\n if (response.status === 401) response = await perform(await mint(true));\n if (!response.ok) throw await responseError(response, \"The RFA request failed.\");\n return response;\n };\n const record = async (path: string, init?: RequestInit): Promise<RfaRecord> => {\n const body = await (await request(path, init)).json() as { data?: RfaRecord };\n if (!body.data?.id) throw new Error(\"The RFA response was invalid.\");\n return body.data;\n };\n const mutation = (body: unknown, key: string): RequestInit => {\n if (!key.trim()) throw new Error(\"An idempotency key is required.\");\n return { method: \"POST\", headers: { \"idempotency-key\": key }, body: JSON.stringify(body) };\n };\n const path = (id: string, suffix: string) => `/${encodeURIComponent(id)}/${suffix}`;\n return {\n getCreationContext: async (query = {}) => {\n const params = new URLSearchParams();\n for (const [name, value] of Object.entries(query)) if (value !== undefined && value !== \"\") params.set(name, String(value));\n const body = await (await request(`/creation-context${params.size ? `?${params}` : \"\"}`, {}, true)).json() as { data?: RfaCreationContext };\n if (!Array.isArray(body.data?.claims) || !Array.isArray(body.data?.renderingProviders)) throw new Error(\"The RFA creation context was invalid.\");\n return body.data;\n },\n list: async (query = {}) => {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) if (value !== undefined && value !== \"\") params.set(key, String(value));\n const body = await (await request(params.size ? `?${params}` : \"\")).json() as RfaListResult;\n if (!Array.isArray(body.data) || !body.summary) throw new Error(\"The RFA list response was invalid.\");\n return body;\n },\n get: (id) => record(`/${encodeURIComponent(id)}`),\n createDraft: (draft, idempotencyKey) => {\n if (!idempotencyKey.trim()) return Promise.reject(new Error(\"An idempotency key is required.\"));\n const unsigned = { ...draft } as RfaCreateDraftInput & { signedAt?: unknown }; delete unsigned.signedAt;\n unsigned.items = draft.items.map(item => { const copy = { ...item } as typeof item & { id?: unknown }; delete copy.id; return copy; });\n return record(\"\", { method: \"POST\", headers: { \"idempotency-key\": idempotencyKey }, body: JSON.stringify(unsigned) });\n },\n updateDraft: (id, draft, key) => {\n if (!Number.isInteger(draft.expectedRevision) || draft.expectedRevision < 1) return Promise.reject(new Error(\"A positive expected content revision is required.\"));\n const body = { ...draft } as RfaUpdateDraftInput & Record<string, unknown>;\n for (const field of [\"externalId\", \"claimId\", \"patientId\", \"renderingProviderId\", \"signedAt\"]) delete body[field];\n body.items = draft.items.map(item => { const copy = { ...item } as typeof item & { externalId?: unknown }; delete copy.externalId; return copy; });\n return record(path(id, \"draft\"), { ...mutation(body, key), method: \"PATCH\" });\n },\n uploadDocument: (id, input, key) => {\n if (!key.trim()) return Promise.reject(new Error(\"An idempotency key is required.\"));\n if (input.file.size < 1 || input.file.size > 25 * 1024 * 1024) return Promise.reject(new Error(\"Choose a PDF up to 25 MB.\"));\n const body = new FormData(); body.set(\"file\", input.file); body.set(\"documentType\", input.documentType); body.set(\"contentRevision\", String(input.contentRevision));\n return record(path(id, \"documents\"), { method: \"POST\", headers: { \"idempotency-key\": key }, body });\n },\n prepareSigning: async (id, input, key) => {\n const body = await (await request(path(id, \"signing-preview\"), mutation(input, key))).json() as { data: RfaSigningPreview };\n if (!body.data?.id || !body.data.contentHash || !body.data.previewDocumentId) throw new Error(\"The signing preview was invalid.\");\n return body.data;\n },\n sign: (id, input, key) => {\n if (input.physicianAuthorized !== true || !input.actorReference.trim()) return Promise.reject(new Error(\"Physician authorization and signer identity are required.\"));\n return record(path(id, \"sign\"), mutation(input, key));\n },\n previewPacket: async (id, documentIds) => (await request(path(id, \"packet\"), { method: \"POST\", body: JSON.stringify({ documentIds }) })).blob(),\n sendFax: (id, input, key) => record(path(id, \"fax\"), mutation(input, key)),\n refreshFaxes: (id, key) => record(path(id, \"fax/refresh\"), mutation({}, key)),\n getDocument: async (id, documentId) => (await request(`/${encodeURIComponent(id)}/documents/${encodeURIComponent(documentId)}`)).blob(),\n };\n}\n\nexport * from \"./rfa-lifecycle\";\nexport { createReportAutofillClient } from \"./report-autofill\";\nexport type { ReportAutofillClient, ReportAutofillField, ReportAutofillMatch, ReportAutofillResult } from \"./report-autofill\";\n"],"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OA,QAAO,KAAK,IAAI,WAAW,GAAG,EAAE,QAAQ,QAAQ,SAAS,EAAE,mBAAmB,IAAI,GAAG,KAAK,CAAC;AAAA,IACpG;AAAA,IACA,gBAAgB,OAAO,IAAI,OAAO,QAAQ;AACxC,YAAM,OAAO,OAAO,MAAM,QAAQ,KAAK,IAAI,iBAAiB,GAAG,SAAS,OAAO,GAAG,CAAC,GAAG,KAAK;AAC3F,UAAI,CAAC,KAAK,MAAM,MAAM,CAAC,KAAK,KAAK,eAAe,CAAC,KAAK,KAAK,kBAAmB,OAAM,IAAI,MAAM,kCAAkC;AAChI,aAAO,KAAK;AAAA,IACd;AAAA,IACA,MAAM,CAAC,IAAI,OAAO,QAAQ;AACxB,UAAI,MAAM,wBAAwB,QAAQ,CAAC,MAAM,eAAe,KAAK,EAAG,QAAO,QAAQ,OAAO,IAAI,MAAM,2DAA2D,CAAC;AACpK,aAAOA,QAAO,KAAK,IAAI,MAAM,GAAG,SAAS,OAAO,GAAG,CAAC;AAAA,IACtD;AAAA,IACA,eAAe,OAAO,IAAI,iBAAiB,MAAM,QAAQ,KAAK,IAAI,QAAQ,GAAG,EAAE,QAAQ,QAAQ,MAAM,KAAK,UAAU,EAAE,YAAY,CAAC,EAAE,CAAC,GAAG,KAAK;AAAA,IAC9I,SAAS,CAAC,IAAI,OAAO,QAAQA,QAAO,KAAK,IAAI,KAAK,GAAG,SAAS,OAAO,GAAG,CAAC;AAAA,IACzE,cAAc,CAAC,IAAI,QAAQA,QAAO,KAAK,IAAI,aAAa,GAAG,SAAS,CAAC,GAAG,GAAG,CAAC;AAAA,IAC5E,aAAa,OAAO,IAAI,gBAAgB,MAAM,QAAQ,IAAI,mBAAmB,EAAE,CAAC,cAAc,mBAAmB,UAAU,CAAC,EAAE,GAAG,KAAK;AAAA,EACxI;AACF;","names":["path","record","request","value","path","idempotencyKey"]}
|
|
1
|
+
{"version":3,"sources":["../src/claim-fees.ts","../src/rfa-directory.ts","../src/second-review-corrections.ts","../src/rfa-lifecycle.ts","../src/report-autofill.ts","../src/index.ts"],"sourcesContent":["import type { BillFeeQuoteInput, BillFeeQuoteBasis } from \"./index\";\n\n/** One patient's complete services for one provider/group. Dates are service dates, not publication dates. */\nexport type CaClaimFeeQuoteInput = {\n lines: Array<Omit<BillFeeQuoteInput, \"billingProviderId\" | \"payerId\" | \"physicianContext\"> & {\n id: string;\n serviceCounty?: string;\n physicianContext?: Omit<NonNullable<BillFeeQuoteInput[\"physicianContext\"]>, \"providerKind\"> & {\n providerKind: NonNullable<BillFeeQuoteInput[\"physicianContext\"]>[\"providerKind\"] | \"clinical_social_worker\";\n telehealthModality?: \"audio_video\" | \"audio_only\";\n cmsSpecialtyCode?: string;\n };\n }>;\n completeDateOfServiceContext: boolean;\n ordinaryMultipleSurgeryContext?: boolean;\n};\nexport type CaFeeCitation = { id: string; url: string; sha256?: string; effectiveFrom?: string; effectiveThrough?: string };\nexport type CaFeeCalculation = {\n method: \"rbrvs\" | \"therapy_mppr\"; locality: string; serviceZip?: string; serviceCounty?: string;\n setting: \"facility\" | \"nonfacility\"; units: number; conversionFactor: string; providerPercent: number;\n baseMaximumCents?: number; cmsIndicators?: Record<string, string>;\n sourceFiles?: Array<{ kind: string; filename: string }>;\n components: Array<{ name: string; rvu: string; gpci: string; payableUnits: number }>;\n rounding: string;\n};\nexport type CaClaimEditFinding = {\n type: string; lineIds: string[]; message: string; citationUrl: string;\n column1?: string; column2?: string; modifierIndicator?: number; code?: string; limit?: number;\n submittedUnits?: number; adjudicationIndicator?: number; scope?: \"line\" | \"patient_provider_date\";\n};\nexport type CaClaimFeeFinding = { code: string; lineIds: string[]; message: string; citationUrl?: string; edit?: CaClaimEditFinding };\nexport type CaClaimLineQuote = ({ status: \"priced\"; amountCents: number; scheduleMaximumCents: number;\n basis: BillFeeQuoteBasis | \"ca_ambulance\"; notes: string[];\n feeBreakdown?: { method: string; inputs: Array<{ label: string; value: string }>; steps: Array<{ label: string; value: string }> };\n} | { status: \"requires_review\" | \"not_separately_payable\"; reason: string }) & {\n provenance: CaFeeCitation[]; calculation?: CaFeeCalculation;\n};\nexport type CaClaimFeeQuoteResult = {\n status: \"priced\" | \"requires_review\" | \"not_separately_payable\";\n lines: Array<{ id: string; input: CaClaimFeeQuoteInput[\"lines\"][number]; quote: CaClaimLineQuote;\n assessment: CaClaimFeeQuoteResult[\"status\"]; findings: CaClaimFeeFinding[];\n paymentAdjustment?: { rule: \"ca_multiple_surgery\"; rank: number; percent: 100 | 50;\n unadjustedScheduleMaximumCents: number; scheduleMaximumCents: number; amountCents: number; citationUrl: string };\n }>;\n totals: { submittedChargeCents: number | null; pricedSubtotalCents: number;\n estimatedPayableCents: number | null; scheduleMaximumCents: number | null; reviewLineCount: number };\n claimEdits: Array<{ dateOfService: string; lineIds: string[]; status: \"evaluated\" | \"requires_review\" | \"source_unavailable\" | \"not_applicable\";\n reason?: string; findings: CaClaimEditFinding[]; provenance?: unknown;\n supportedDateRange?: { from: string; through: string }; supportedDateIntervals?: Array<{ from: string; through: string }>;\n }>;\n limitations: string[];\n};\n\nconst record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === \"object\" && !Array.isArray(v);\nconst strings = (v: unknown): v is string[] => Array.isArray(v) && v.every((x) => typeof x === \"string\");\nconst money = (v: unknown) => Number.isSafeInteger(v) && (v as number) >= 0;\nconst status = (v: unknown) => [\"priced\", \"requires_review\", \"not_separately_payable\"].includes(v as string);\nconst finding = (v: unknown) => record(v) && typeof v.message === \"string\" && strings(v.lineIds) && (v.citationUrl === undefined || typeof v.citationUrl === \"string\");\n/** Validate the transport before a browser displays an allowance. Unknown/partial results fail closed. */\nexport function parseCaClaimFeeQuote(value: unknown, input: CaClaimFeeQuoteInput): CaClaimFeeQuoteResult {\n const invalid = () => { throw new Error(\"Claim fee quote returned an invalid response.\"); };\n if (!record(value) || !status(value.status) || !Array.isArray(value.lines) || value.lines.length !== input.lines.length || !strings(value.limitations) || !record(value.totals) || !Array.isArray(value.claimEdits)) return invalid();\n const totals = value.totals;\n if (!money(totals.pricedSubtotalCents) || !money(totals.reviewLineCount) || [totals.submittedChargeCents, totals.estimatedPayableCents, totals.scheduleMaximumCents].some((v) => v !== null && !money(v))) return invalid();\n if (value.status === \"requires_review\" && totals.estimatedPayableCents !== null) return invalid();\n const expected = new Set(input.lines.map((line) => line.id));\n for (const line of value.lines) {\n if (!record(line) || typeof line.id !== \"string\" || !expected.delete(line.id) || !record(line.input) || typeof line.input.code !== \"string\" || line.input.id !== line.id || line.input.code !== input.lines.find((r) => r.id === line.id)?.code || line.input.dateOfService !== input.lines.find((r) => r.id === line.id)?.dateOfService || !status(line.assessment) || !record(line.quote) || !Array.isArray(line.findings) || !line.findings.every(finding)) return invalid();\n const quote = line.quote;\n if (!status(quote.status) || !Array.isArray(quote.provenance) || !quote.provenance.every((s) => record(s) && typeof s.id === \"string\" && typeof s.url === \"string\" && (s.effectiveFrom === undefined || typeof s.effectiveFrom === \"string\") && (s.effectiveThrough === undefined || typeof s.effectiveThrough === \"string\"))) return invalid();\n if (quote.status === \"priced\") {\n if (!money(quote.amountCents) || !money(quote.scheduleMaximumCents) || typeof quote.basis !== \"string\" || !strings(quote.notes)) return invalid();\n } else if (typeof quote.reason !== \"string\") return invalid();\n if (quote.calculation !== undefined) {\n const c = quote.calculation;\n if (!record(c) || typeof c.locality !== \"string\" || typeof c.conversionFactor !== \"string\" || !Number.isFinite(c.providerPercent) || ![\"facility\", \"nonfacility\"].includes(c.setting as string) || (c.sourceFiles !== undefined && (!Array.isArray(c.sourceFiles) || !c.sourceFiles.every((f) => record(f) && typeof f.kind === \"string\" && typeof f.filename === \"string\"))) || (c.cmsIndicators !== undefined && (!record(c.cmsIndicators) || !Object.values(c.cmsIndicators).every((v) => typeof v === \"string\"))) || !Array.isArray(c.components) || !c.components.every((r) => record(r) && typeof r.name === \"string\" && typeof r.rvu === \"string\" && typeof r.gpci === \"string\" && typeof r.payableUnits === \"number\")) return invalid();\n }\n if (quote.feeBreakdown !== undefined) {\n const b = quote.feeBreakdown;\n if (!record(b) || ![b.inputs, b.steps].every((rows) => Array.isArray(rows) && rows.every((r) => record(r) && typeof r.label === \"string\" && typeof r.value === \"string\"))) return invalid();\n }\n if (line.paymentAdjustment !== undefined) {\n const a = line.paymentAdjustment;\n if (!record(a) || !money(a.amountCents) || !money(a.scheduleMaximumCents) || !money(a.unadjustedScheduleMaximumCents) || typeof a.citationUrl !== \"string\" || ![100,50].includes(a.percent as number) || !money(a.rank)) return invalid();\n }\n }\n if (!value.claimEdits.every((edit) => record(edit) && typeof edit.dateOfService === \"string\" && strings(edit.lineIds) && [\"evaluated\", \"requires_review\", \"source_unavailable\", \"not_applicable\"].includes(edit.status as string) && Array.isArray(edit.findings) && edit.findings.every(finding) && (edit.reason === undefined || typeof edit.reason === \"string\"))) return invalid();\n return value as unknown as CaClaimFeeQuoteResult;\n}\n","import type { BillClaimsAdministratorDirectory } from \"./index\";\n\nexport type RfaAuthorizationDestinationOption = {\n method: \"fax\" | \"email\";\n destination: string;\n label: string;\n phone?: string;\n};\n\n/** Accept fax numbers only, never telephone notes, email addresses, or extensions. */\nexport function normalizeRfaFax(value: string): string | null {\n const input = value.trim();\n if (/^\\+[1-9]\\d{7,14}$/.test(input)) return input;\n if (!/^\\+?[\\d ().-]+$/.test(input)) return null;\n const digits = input.replace(/\\D/g, \"\");\n if (digits.length === 10 && !input.startsWith(\"+\")) return `+1${digits}`;\n return digits.length === 11 && digits.startsWith(\"1\") ? `+${digits}` : null;\n}\n\n/** Returns choices only. Selecting or transmitting a destination is a separate user action. */\nexport function rfaAuthorizationDestinations(directory: BillClaimsAdministratorDirectory | null): RfaAuthorizationDestinationOption[] {\n if (!directory || [\"adjuster_specific_required\", \"daisybill_unverified\", \"profile_not_published\"].includes(directory.authorizationStatus ?? \"\")) return [];\n return (directory.authorization ?? []).flatMap((contact) => {\n const common = { label: contact.location || contact.name || \"Authorization department\", ...(contact.phone ? { phone: contact.phone } : {}) };\n const options: RfaAuthorizationDestinationOption[] = [];\n const fax = contact.fax ? normalizeRfaFax(contact.fax) : null;\n if (fax && contact.method !== \"email\") options.push({ ...common, method: \"fax\", destination: fax });\n if (contact.email?.trim() && contact.method !== \"fax\") options.push({ ...common, method: \"email\", destination: contact.email.trim() });\n return options;\n });\n}\n\nexport function rfaAuthorizationGuidance(directory: BillClaimsAdministratorDirectory | null): string {\n switch (directory?.authorizationStatus) {\n case \"central_fax\": return \"Select the central authorization fax after confirming it applies to this claim.\";\n case \"central_email\": return \"Authorization is routed by email. Download the signed packet and record delivery after sending it through your email service.\";\n case \"claim_handling_location_routes\": return \"Choose the office handling this claim. Authorization destinations vary by office.\";\n case \"adjuster_specific_required\": return \"Obtain the authorization destination from the handling adjuster.\";\n case \"daisybill_unverified\": return \"The directory has not verified an authorization destination. Confirm it with the handling adjuster.\";\n case \"profile_not_published\": return \"No authorization destination is currently published. Confirm a current destination with the handling adjuster.\";\n default: return \"Select an authorization contact or enter a fax confirmed with the handling adjuster.\";\n }\n}\n","import type { SecondReviewLineInput } from \"./index\";\n\nexport type CorrectionDraft = {\n correctBilling: boolean;\n units: string;\n modifiers: string;\n charge: string;\n chargeReviewed: boolean;\n};\n\nexport function parseSecondReviewCorrection(draft: CorrectionDraft): SecondReviewLineInput[\"correction\"] {\n if (!draft.correctBilling) return undefined;\n const units = Number(draft.units);\n const charge = Number(draft.charge);\n const modifiers = draft.modifiers.trim().toUpperCase().split(/[\\s,]+/).filter(Boolean);\n if (!draft.units.trim() || !Number.isInteger(units) || units < 1 || units > 10_000) {\n throw new Error(\"Corrected units must be a whole number from 1 to 10,000.\");\n }\n if (modifiers.length > 4 || new Set(modifiers).size !== modifiers.length || modifiers.some((value) => !/^[A-Z0-9]{2}$/.test(value))) {\n throw new Error(\"Enter up to four unique two-character modifiers, separated by commas. Leave blank to remove modifiers.\");\n }\n if (!draft.charge.trim() || !Number.isFinite(charge) || charge < 0 || charge > 999_999.99 || Math.abs(charge * 100 - Math.round(charge * 100)) > 0.000001) {\n throw new Error(\"Enter the corrected charge in dollars and cents.\");\n }\n if (!draft.chargeReviewed) throw new Error(\"Confirm that you reviewed the corrected charge. It is not recalculated automatically.\");\n return { units, modifiers, charge };\n}\n","import type { BillLifecycleSession, OrganizationClientOptions, RfaRecord } from \"./index\";\n\nexport type RfaReceiptInput = {\n channel: \"fax\" | \"email\" | \"edi\" | \"portal\" | \"mail\" | \"manual\";\n receivedAt: string;\n proofDocumentId?: string;\n providerMessageId?: string;\n};\nexport type RfaInformationRequestInput = { requestedAt: string; requestText: string; dueAt?: string };\nexport type RfaInformationResponseInput = { respondedAt: string; responseDocumentIds: string[] };\nexport type RfaTreatmentDecisionInput = {\n itemId: string; outcome: \"approved\" | \"modified\" | \"denied\";\n authorizationNumber?: string; authorizedProcedureCode?: string; authorizedQuantity?: number; authorizedUnits?: number;\n effectiveFrom?: string; effectiveTo?: string; decisionReason?: string; reviewerName?: string; reviewerPhone?: string;\n};\nexport type RfaDecisionsInput = { decidedAt: string; responseDocumentId: string; imrDocumentId?: string; decisions: RfaTreatmentDecisionInput[] };\nexport type RfaFollowUp = {\n id: string; rfaId: string; claimId: string; responseDocumentId: string | null; responseFilename: string | null;\n kind: string; status: string; dueAt: string; assigneeReference: string | null; snoozedUntil: string | null;\n lastOutcome: string | null; lastNote: string | null; createdAt: string; updatedAt: string; resolvedAt: string | null;\n};\nexport type RfaFollowUpUpdate = {\n assigneeReference?: string | null; snoozedUntil?: string | null;\n outcome?: \"message_left\" | \"decision_pending\" | \"decision_issued\" | \"not_on_file\" | \"reviewed\";\n note?: string;\n responseReview?: { disposition: \"no_new_decision\"; noNewDecisionConfirmed: true } | { disposition: \"decisions_recorded\"; allDecisionsRecordedConfirmed: true };\n};\nexport type RfaFollowUpList = { data: RfaFollowUp[]; nextCursor: string | null };\nexport type RfaLifecycleClient = {\n recordReceipt(id: string, input: RfaReceiptInput, idempotencyKey: string): Promise<RfaRecord>;\n recordInformationRequest(id: string, input: RfaInformationRequestInput, idempotencyKey: string): Promise<RfaRecord>;\n recordInformationResponse(id: string, requestId: string, input: RfaInformationResponseInput, idempotencyKey: string): Promise<RfaRecord>;\n recordDecisions(id: string, input: RfaDecisionsInput, idempotencyKey: string): Promise<RfaRecord>;\n listFollowUps(query?: { claimId?: string; includeResolved?: boolean; limit?: number; cursor?: string }): Promise<RfaFollowUpList>;\n updateFollowUp(id: string, input: RfaFollowUpUpdate, idempotencyKey: string): Promise<RfaFollowUp>;\n clearSession(): void;\n};\n/** Records clinical workflow evidence. These methods never send faxes or reconcile notification queues. */\nexport function createRfaLifecycleClient({ sessionEndpoint = \"/api/mindbill/session\", getSession, apiBaseUrl = \"https://app.mindbill.org\", fetch: fetchOverride }: OrganizationClientOptions = {}): RfaLifecycleClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n let pending: Promise<BillLifecycleSession> | null = null;\n const failure = async (response: Response): Promise<Error> => {\n const body = await response.json().catch(() => null) as { detail?: unknown; message?: unknown } | null;\n const detail = body?.detail ?? body?.message;\n return new Error(typeof detail === \"string\" ? detail : `The RFA request failed (${response.status}).`);\n };\n const mint = (force = false): Promise<BillLifecycleSession> => {\n if (!force && session && (!session.expiresAt || Date.parse(session.expiresAt) > Date.now() + 30_000)) return Promise.resolve(session);\n if (pending) return pending;\n pending = (async () => {\n const value: unknown = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await failure(response);\n return response.json();\n })();\n const envelope = value as { session?: unknown; data?: unknown } | null;\n const candidate = (envelope?.session ?? envelope?.data ?? value) as BillLifecycleSession | null;\n if (!candidate || typeof candidate.token !== \"string\" || candidate.token.length < 8) throw new Error(\"The RFA session endpoint did not return a browser session token.\");\n session = { token: candidate.token, ...(typeof candidate.expiresAt === \"string\" ? { expiresAt: candidate.expiresAt } : {}), ...(typeof candidate.apiBaseUrl === \"string\" ? { apiBaseUrl: candidate.apiBaseUrl } : {}) };\n return session;\n })().finally(() => { pending = null; });\n return pending;\n };\n const request = async <T>(path: string, init: RequestInit = {}): Promise<T> => {\n const perform = (active: BillLifecycleSession) => {\n const headers = new Headers(init.headers); headers.set(\"authorization\", `Bearer ${active.token}`);\n if (init.body) headers.set(\"content-type\", \"application/json\");\n return fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/${path}`, { ...init, headers });\n };\n let response = await perform(await mint());\n if (response.status === 401) response = await perform(await mint(true));\n if (!response.ok) throw await failure(response);\n return response.json() as Promise<T>;\n };\n const mutate = async <T extends { id: string }>(path: string, input: unknown, key: string, method = \"POST\"): Promise<T> => {\n if (!key.trim()) throw new Error(\"An idempotency key is required.\");\n const result = await request<{ data: T }>(path, { method, headers: { \"idempotency-key\": key }, body: JSON.stringify(input) });\n if (!result.data?.id) throw new Error(\"The RFA response was invalid.\");\n return result.data;\n };\n const path = (id: string, suffix: string) => `rfas/${encodeURIComponent(id)}/${suffix}`;\n return {\n recordReceipt: (id, input, key) => {\n if (!input.proofDocumentId?.trim() && !input.providerMessageId?.trim()) return Promise.reject(new Error(\"Receipt requires a proof document or provider reference.\"));\n return mutate(path(id, \"transmissions\"), { ...input, direction: \"inbound\", status: \"received\", occurredAt: input.receivedAt }, key);\n },\n recordInformationRequest: (id, input, key) => mutate(path(id, \"information-requests\"), input, key),\n recordInformationResponse: (id, requestId, input, key) => mutate(path(id, `information-requests/${encodeURIComponent(requestId)}`), input, key),\n recordDecisions: (id, input, key) => mutate(path(id, \"decisions\"), input, key),\n listFollowUps: async (query = {}) => {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) if (value !== undefined) params.set(key, String(value));\n const result = await request<RfaFollowUpList>(`rfa-follow-ups${params.size ? `?${params}` : \"\"}`);\n if (!Array.isArray(result.data) || !(result.nextCursor === null || typeof result.nextCursor === \"string\")) throw new Error(\"The RFA follow-up response was invalid.\");\n return result;\n },\n updateFollowUp: (id, input, key) => mutate(`rfa-follow-ups/${encodeURIComponent(id)}`, input, key, \"PATCH\"),\n clearSession: () => { session = null; },\n };\n}\n","import type { BillLifecycleSession, OrganizationClientOptions } from \"./index\";\n\nexport type ReportAutofillField = { key: string; value: string; sourceText: string; confidence: \"high\" | \"medium\" };\nexport type ReportAutofillMatch = { status: \"matched\" | \"ambiguous\" | \"none\"; candidates: Array<{ id: string; name: string }>; selectedId?: string };\nexport type ReportAutofillResult = {\n model: \"gpt-5.6-luna\"; requiresReview: true; fields: ReportAutofillField[];\n matches: Record<\"patient\" | \"billingProvider\" | \"renderingProvider\" | \"serviceLocation\", ReportAutofillMatch>;\n warnings: string[];\n};\nexport type ReportAutofillClient = { analyze(report: File): Promise<ReportAutofillResult>; clearSession(): void };\n/** Available only by written agreement, with an organization-wide autofill:run session. Does not save a document or submit a bill. */\nexport function createReportAutofillClient({ sessionEndpoint = \"/api/mindbill/session\", getSession, apiBaseUrl = \"https://app.mindbill.org\", fetch: fetchOverride }: OrganizationClientOptions = {}): ReportAutofillClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n const error = async (response: Response) => {\n const body = await response.json().catch(() => null) as { detail?: unknown; message?: unknown } | null;\n return new Error(typeof body?.detail === \"string\" ? body.detail : typeof body?.message === \"string\" ? body.message : `Report analysis failed (${response.status}).`);\n };\n const mint = async (): Promise<BillLifecycleSession> => {\n if (session && (!session.expiresAt || Date.parse(session.expiresAt) > Date.now() + 30_000)) return session;\n const value: unknown = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await error(response);\n return response.json();\n })();\n const envelope = value as { session?: unknown; data?: unknown } | null;\n const candidate = (envelope?.session ?? envelope?.data ?? value) as BillLifecycleSession | null;\n if (!candidate || typeof candidate.token !== \"string\" || candidate.token.length < 8) throw new Error(\"The report session endpoint did not return a browser session token.\");\n session = candidate;\n return candidate;\n };\n return {\n clearSession: () => { session = null; },\n analyze: async report => {\n if (report.type !== \"application/pdf\") throw new Error(\"Choose a PDF report.\");\n if (!report.size || report.size > 25 * 1024 * 1024) throw new Error(\"Choose a non-empty PDF report no larger than 25 MB.\");\n const perform = async () => {\n const active = await mint(); const body = new FormData(); body.append(\"report\", report);\n return fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/report-autofill`, { method: \"POST\", headers: { authorization: `Bearer ${active.token}` }, body });\n };\n let response = await perform();\n if (response.status === 401) { session = null; response = await perform(); }\n if (!response.ok) throw await error(response);\n const envelope = await response.json() as { data?: ReportAutofillResult };\n const result = envelope.data;\n if (!result || result.requiresReview !== true || !Array.isArray(result.fields) || !Array.isArray(result.warnings) || !result.matches\n || result.fields.some(field => !field || typeof field.key !== \"string\" || typeof field.value !== \"string\" || typeof field.sourceText !== \"string\" || ![\"high\", \"medium\"].includes(field.confidence))\n || result.warnings.some(warning => typeof warning !== \"string\")\n || ([\"patient\", \"billingProvider\", \"renderingProvider\", \"serviceLocation\"] as const).some(kind => {\n const match = result.matches[kind];\n return !match || ![\"matched\", \"ambiguous\", \"none\"].includes(match.status) || !Array.isArray(match.candidates) || match.candidates.some(candidate => !candidate || typeof candidate.id !== \"string\" || typeof candidate.name !== \"string\");\n })) throw new Error(\"The report analysis response was invalid.\");\n return result;\n },\n };\n}\n","import { parseCaClaimFeeQuote, type CaClaimFeeQuoteInput, type CaClaimFeeQuoteResult } from \"./claim-fees\";\nexport type { CaClaimFeeQuoteInput, CaClaimFeeQuoteResult, CaClaimLineQuote, CaFeeCalculation, CaFeeCitation, CaClaimEditFinding, CaClaimFeeFinding } from \"./claim-fees\";\nexport { normalizeRfaFax, rfaAuthorizationDestinations, rfaAuthorizationGuidance } from \"./rfa-directory\";\nexport type { RfaAuthorizationDestinationOption } from \"./rfa-directory\";\nexport const DEFAULT_API_BASE_URL = \"https://app.mindbill.org\";\nexport const DEFAULT_SESSION_ENDPOINT = \"/api/mindbill/session\";\nexport { parseSecondReviewCorrection, type CorrectionDraft } from \"./second-review-corrections\";\n\nexport type BillReviewDocumentType =\n | \"final_report\"\n | \"letter_of_attestation\"\n | \"proof_of_service\"\n | \"form_122\"\n | \"return_to_work_voucher\"\n | \"w9\"\n | \"medical_records\"\n | \"appeal\"\n | \"other\";\n\nexport type BillReviewBillingProvider = {\n name: string;\n taxId: string;\n taxIdType?: \"EIN\" | \"SSN\";\n taxIdConfigured?: boolean;\n taxIdLast4?: string;\n npi: string;\n billType: \"Professional\" | \"Institutional\";\n phone?: string;\n billingStreet?: string;\n billingCity?: string;\n billingState?: string;\n billingZip?: string;\n};\n\nexport type BillReviewClinician = {\n /** Canonical opaque provider ID, when available. */\n id?: string;\n name: string;\n specialty: string;\n npi: string;\n taxonomy?: string;\n licenseNumber?: string;\n licenseState?: string;\n signaturePng?: string;\n signatureKey?: string;\n isQME?: boolean;\n isAME?: boolean;\n email?: string;\n active?: boolean;\n};\n\nexport type BillReviewLocation = {\n billingProviderId?: string;\n name: string;\n nickname?: string;\n street: string;\n city: string;\n state: string;\n zip: string;\n county?: string;\n posCode?: string;\n isPrimary?: boolean;\n active?: boolean;\n};\n\nexport type BillReviewLineItem = {\n id?: string;\n code: string;\n modifiers: string[];\n units: number;\n charge: number;\n feeSchedule?: number;\n serviceDate?: string | null;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n};\n\nexport type BillReviewAttachment = {\n id: string;\n filename: string;\n description?: string | null;\n documentType: string;\n reportType?: string | null;\n source?: string;\n addedAt?: string;\n contentUrl?: string;\n};\n\n/** One selectable payer (subpayor) under a claims administrator. */\nexport type BillReviewPayerOption = {\n id: string;\n label: string;\n /** Directory-provided default marker. Interactive forms still require an explicit choice. */\n default?: boolean;\n active?: boolean;\n aliases?: string[];\n hint?: string | null;\n affiliatedEntities?: string[];\n route?: string | null;\n optionType?: string | null;\n deliveryType?: string | null;\n clearinghouse?: string | null;\n payerId?: string | null;\n /** Original directory route when live delivery uses a replacement clearinghouse. */\n sourceClearinghouse?: string | null;\n /** Original directory payer ID when live delivery uses a replacement route. */\n sourcePayerId?: string | null;\n clearinghousePayerIds?: Record<string, string>;\n preferredClearinghouse?: string | null;\n};\n\nexport type BillReviewPayer = {\n id: string;\n name: string;\n hasElectronic?: boolean;\n states?: string[];\n confidence?: \"high\" | \"medium\" | \"directory\";\n recommended?: boolean;\n signals?: Array<{\n kind: \"name\" | \"claim_number\";\n state: \"match\" | \"warning\";\n label: string;\n }>;\n /** True when a bill for this claims administrator must name one of `payers`. */\n payerSelectionRequired?: boolean;\n /** Selectable payers (subpayors) under this claims administrator. */\n payers?: BillReviewPayerOption[];\n aliases?: string[];\n affiliatedEntities?: string[];\n claimNumberHint?: string | null;\n claimNumberPatterns?: BillClaimsAdministratorPattern[];\n route?: string | null;\n};\n\n/** A directory suggestion derived from host-provided evidence. Suggestions are never auto-applied. */\nexport type BillReviewPayerSuggestion = BillReviewPayer & {\n deterministic: boolean;\n reason: string;\n /** A uniquely proven routing payer under a multi-payer claims administrator. */\n selectedPayerId?: string;\n};\n\n/** Host-system evidence shown alongside claims-administrator suggestions. */\nexport type BillClaimsAdministratorSource = {\n source: \"eams\" | \"report\" | string;\n label: string;\n name: string;\n url?: string;\n};\n\n/**\n * The directory-marked default payer option, or null when none is marked.\n * Interactive forms should still require an explicit routing-payer choice.\n */\nexport function defaultBillReviewPayerOption(\n payer: Pick<BillReviewPayer, \"payerSelectionRequired\" | \"payers\">,\n): BillReviewPayerOption | null {\n if (!payer.payerSelectionRequired) return null;\n return payer.payers?.find((option) => option.default) ?? null;\n}\n\nexport type BillPostalPlace = { city: string; state: string };\nexport type BillDiagnosisCode = { code: string; description: string };\n\nexport type BillReviewFeatures = {\n authorizationNumber?: boolean;\n serviceDateRange?: boolean;\n wcabNumber?: boolean;\n codingPresets?: boolean;\n};\n\nexport type BillReviewClaimPatternStatus = {\n state: \"match\" | \"warning\" | \"unknown\";\n label: string;\n detail?: string;\n suggestion?: string;\n};\n\nexport type BillReviewData = {\n options?: Pick<OrganizationProfileData, \"billingProviders\" | \"renderingProviders\" | \"locations\">;\n bill: {\n id: string;\n billNumber: string | number;\n status: string;\n transmissionState?: string;\n billingMode: \"med_legal\" | \"professional\";\n dos: string;\n dosEnd?: string | null;\n authorizationNumber?: string | null;\n billingSnapshot?: {\n billingProvider?: BillReviewBillingProvider;\n renderingProvider?: BillReviewClinician;\n placeOfService?: BillReviewLocation;\n } | null;\n lineItems: BillReviewLineItem[];\n attachments: BillReviewAttachment[];\n totalCharge: number;\n totalPaid: number;\n balanceDue: number;\n };\n patient: {\n /** Canonical opaque patient ID, when available. */\n id?: string;\n name: string;\n firstName?: string;\n middleName?: string;\n lastName?: string;\n dob?: string;\n phone?: string;\n address?: {\n line1?: string;\n city?: string;\n state?: string;\n postalCode?: string;\n };\n };\n injury: {\n claimNumber?: string;\n employer?: string;\n doi?: string;\n injuryEndDate?: string;\n cumulativeTrauma?: boolean;\n adjNumber?: string;\n claimsAdminId?: string;\n claimsAdminName?: string;\n injuryDescription?: string;\n /** Diagnosis codes enriched with their human-readable ICD-10 descriptions. */\n diagnoses?: BillDiagnosisCode[];\n /** @deprecated Prefer diagnoses so users can understand each code. */\n diagnosisCodes?: string[];\n claimPatternStatus?: BillReviewClaimPatternStatus;\n };\n};\n\nexport type BillReviewSaveInput = {\n claimsAdminId: string;\n /** The chosen payer (subpayor) when the claims administrator requires payer selection. */\n payerId?: string;\n patientOverrides?: {\n firstName: string;\n middleName?: string;\n lastName: string;\n dob?: string;\n };\n injuryOverrides?: {\n claimNumber?: string;\n employer?: string;\n doi?: string;\n injuryEndDate?: string;\n cumulativeTrauma?: boolean;\n adjNumber?: string;\n };\n dos: string;\n dosEnd?: string | null;\n authorizationNumber?: string | null;\n billingProvider?: BillReviewBillingProvider;\n renderingProvider?: BillReviewClinician;\n placeOfService?: BillReviewLocation;\n lineItems: Array<{\n id?: string;\n code: string;\n modifiers: string[];\n units: number;\n charge?: number;\n serviceDate?: string | null;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n }>;\n};\n\nfunction pickDefined(\n source: object,\n keys: readonly string[],\n): Record<string, unknown> {\n const record = source as Record<string, unknown>;\n return Object.fromEntries(\n keys.flatMap((key) => record[key] === undefined ? [] : [[key, record[key]]]),\n );\n}\n\n/**\n * Removes read-only snapshot metadata before a review mutation is sent.\n * Lifecycle reads can include display-only fields such as entity IDs; the v2\n * write contract accepts only the values that should be frozen onto the bill.\n */\nexport function sanitizeBillReviewSaveInput(\n input: BillReviewSaveInput,\n): BillReviewSaveInput {\n return {\n claimsAdminId: input.claimsAdminId,\n ...(input.payerId !== undefined ? { payerId: input.payerId } : {}),\n ...(input.patientOverrides ? {\n patientOverrides: pickDefined(input.patientOverrides, [\n \"firstName\", \"middleName\", \"lastName\", \"dob\",\n ]) as NonNullable<BillReviewSaveInput[\"patientOverrides\"]>,\n } : {}),\n ...(input.injuryOverrides ? {\n injuryOverrides: pickDefined(input.injuryOverrides, [\n \"claimNumber\", \"employer\", \"doi\", \"injuryEndDate\",\n \"cumulativeTrauma\", \"adjNumber\",\n ]) as NonNullable<BillReviewSaveInput[\"injuryOverrides\"]>,\n } : {}),\n dos: input.dos,\n ...(input.dosEnd !== undefined ? { dosEnd: input.dosEnd } : {}),\n ...(input.authorizationNumber !== undefined\n ? { authorizationNumber: input.authorizationNumber }\n : {}),\n ...(input.billingProvider ? {\n billingProvider: pickDefined(input.billingProvider, [\n \"name\", \"taxId\", \"taxIdType\", \"taxIdConfigured\", \"npi\", \"billType\", \"phone\", \"billingStreet\",\n \"billingCity\", \"billingState\", \"billingZip\",\n ]) as BillReviewBillingProvider,\n } : {}),\n ...(input.renderingProvider ? {\n renderingProvider: pickDefined(input.renderingProvider, [\n \"name\", \"specialty\", \"npi\", \"taxonomy\", \"licenseNumber\",\n \"licenseState\", \"signaturePng\", \"signatureKey\", \"isQME\", \"isAME\",\n \"email\", \"active\",\n ]) as BillReviewClinician,\n } : {}),\n ...(input.placeOfService ? {\n placeOfService: pickDefined(input.placeOfService, [\n \"billingProviderId\", \"name\", \"nickname\", \"street\", \"city\", \"state\",\n \"zip\", \"county\", \"posCode\", \"isPrimary\", \"active\",\n ]) as BillReviewLocation,\n } : {}),\n lineItems: input.lineItems.map((line) => pickDefined(line, [\n \"id\", \"code\", \"modifiers\", \"units\", \"charge\", \"serviceDate\",\n \"serviceDateEnd\", \"diagnosisPointers\",\n ]) as BillReviewSaveInput[\"lineItems\"][number]),\n };\n}\n\nexport type BillSubmissionRoute = \"ebill\" | \"fax\" | \"mail\" | \"email\";\nexport type BillDeliveryOption = {\n route: BillSubmissionRoute;\n label: string;\n detail: string;\n fallback: boolean;\n confidence: string;\n payerName: string;\n target?: string;\n chKey?: string;\n payerId?: string;\n printAndMail?: boolean;\n costUsd?: number;\n};\nexport type BillDeliveryOptions = {\n payerName: string;\n recommended: BillDeliveryOption;\n options: BillDeliveryOption[];\n contacts: {\n faxNumber?: string | null;\n claimsEmail?: string | null;\n portalUrl?: string | null;\n mailingAddress?: string | null;\n adjusterName?: string | null;\n adjusterPhone?: string | null;\n adjusterEmail?: string | null;\n };\n};\nexport type BillActorInput = {\n /** Human-readable name shown for user-initiated audit history. */\n actorName?: string;\n};\n\nexport type AddBillNoteInput = BillActorInput & {\n note: string;\n};\n\nexport type SubmitBillInput = BillActorInput & {\n route: BillSubmissionRoute;\n destination?: {\n faxNumber?: string;\n email?: string;\n mailingAddress?: string;\n };\n attention?: string;\n subject?: string;\n note?: string;\n /** CC recipients for the email route (at most 10). */\n cc?: string[];\n};\nexport type BillLifecycleActionId =\n | \"resubmit\"\n | \"second_review\"\n | \"independent_bill_review\"\n | \"view_eor\"\n | \"post_payment\"\n | \"close\"\n | \"reopen\"\n | \"send_duplicate\"\n | \"report_bill_status\"\n | \"submit_new_bill\";\n\nexport type BillLifecycleAction = {\n id: BillLifecycleActionId;\n label: string;\n enabled: boolean;\n primary?: boolean;\n reason?: string;\n};\n\nexport type BillEorDocument = {\n id: string;\n filename: string;\n description: string | null;\n addedAt: string;\n contentUrl: string;\n};\n\nexport type BillActivityRecord = {\n id: string;\n type: string;\n createdAt: string;\n title?: string;\n description: string;\n actor: string | null;\n delivery: BillSubmissionRoute | null;\n amount: number | null;\n accepted: boolean | null;\n stcCategory: string | null;\n};\n\n/** One user-facing bill history row (Date / Action / User / Details).\n * Server-presented: the wording is authored by MindBill so every surface (MindBill\n * app, React, Angular, embeds) reads identically. */\nexport type BillHistoryEntry = {\n id: string;\n /** Immutable bill attempt that produced this event. Present on unified chain history. */\n attemptId?: string;\n /** ISO timestamp for ordering and the Date column. */\n date: string;\n /** Short Action label — \"Original Bill\", \"277 Accept\", \"Payment\", \"Note\", … */\n action: string;\n kind:\n | \"created\"\n | \"submission\"\n | \"ack\"\n | \"eor\"\n | \"payment\"\n | \"review\"\n | \"close\"\n | \"reopen\"\n | \"note\"\n | \"portal\"\n | \"task\"\n | \"system\";\n /** Who acted: a biller name, MindBill automation, or the responding clearinghouse. */\n actor: string | null;\n /** The one-line Details column. */\n summary: string;\n /** Drives row highlighting: submissions are pale blue, notes pale yellow. */\n tone: \"submission\" | \"note\" | \"neutral\" | \"problem\" | \"success\";\n amount?: number;\n /** Expandable content; absent → the row is not expandable. */\n details?: {\n rows?: Array<{ label: string; value: string }>;\n documents?: Array<{ id: string; filename: string }>;\n complianceDueDates?: Array<{ date: string; text: string }>;\n codes?: Array<{ code: string; text: string }>;\n text?: string;\n };\n};\n\n/** One immutable transmission attempt within a logical bill chain. */\nexport type BillAttemptSummary = {\n /** Unique transmission identity. Draft attempts fall back to the bill record ID. */\n id: string;\n /** Underlying bill record. Multiple transmissions may share this value. */\n billId?: string;\n submissionId?: string;\n billNumber?: string | number;\n label: string;\n deliveryLabel?: string;\n sentAt?: string;\n ackLabel?: string;\n ackAt?: string;\n status?: string;\n complianceLabel?: string;\n complianceAt?: string;\n /** The latest attempt that receives lifecycle mutations. */\n isCurrent: boolean;\n};\n\nexport type BillPaymentRecord = {\n id: string;\n method: \"check\" | \"eft\";\n checkNumber: string;\n status: string | null;\n depositDate: string | null;\n checkReceived: boolean | null;\n receivedDate: string | null;\n amount: number;\n principalAmount: number;\n feeAmount: number | null;\n feeReason: string | null;\n source: \"paper\" | \"835\" | \"portal\";\n postedAt: string;\n updatedAt: string | null;\n note: string | null;\n};\n\nexport type BillRemittanceSummary = {\n billedAmount: number;\n expectedAmount: number;\n payerAllowedAmount: number | null;\n payerReportedPaid: number | null;\n postedPrincipal: number;\n postedAdditional: number;\n totalPostedCash: number;\n balanceDue: number;\n denialReason: string | null;\n};\n\nexport type BillLifecycleDelivery = {\n payerName: string;\n contacts: BillDeliveryOptions[\"contacts\"];\n /**\n * Partner-safe directory details. `id` is an opaque MindBill directory ID;\n * Values are safe, partner-facing directory details; internal database identifiers are opaque.\n */\n directory?: BillClaimsAdministratorDirectory | null;\n};\n\nexport type BillClaimsAdministratorContact = {\n location?: string | null;\n method?: \"fax\" | \"email\";\n name?: string | null;\n phone?: string | null;\n email?: string | null;\n fax?: string | null;\n portalUrl?: string | null;\n address?: string | null;\n note?: string | null;\n};\n\nexport type BillClaimsAdministratorMailingAddress = {\n company?: string | null;\n address: string;\n notes?: string | null;\n submissionTypes?: string[];\n billTreatmentTypes?: string[];\n};\n\nexport type BillClaimsAdministratorPattern = {\n length?: number | string | null;\n pattern: string;\n example?: string | null;\n matches?: boolean | null;\n};\n\nexport type BillClaimsAdministratorPayer = {\n name: string;\n route?: string | null;\n aliases?: string[];\n hint?: string | null;\n affiliatedEntities?: string[];\n optionType?: string | null;\n deliveryType?: string | null;\n clearinghouse?: string | null;\n payerId?: string | null;\n sourceClearinghouse?: string | null;\n sourcePayerId?: string | null;\n clearinghousePayerIds?: Record<string, string>;\n preferredClearinghouse?: string | null;\n};\n\nexport type BillReviewPayerPage = {\n results: BillReviewPayer[];\n suggestions?: BillReviewPayerSuggestion[];\n total: number;\n nextOffset?: number;\n recommendedId?: string;\n};\n\nexport type BillReviewPayerListInput = {\n query?: string;\n claimNumber?: string;\n sourceClaimsAdministratorName?: string;\n employerName?: string;\n limit?: number;\n offset?: number;\n};\n\nexport type BillClaimsAdministratorAuthorizationStatus = \"central_fax\" | \"central_email\" | \"claim_handling_location_routes\" | \"adjuster_specific_required\" | \"daisybill_unverified\" | \"profile_not_published\";\n\nexport type BillClaimsAdministratorDirectory = {\n authorizationStatus?: BillClaimsAdministratorAuthorizationStatus;\n authorizationSource?: { url: string; observedAt: string };\n id?: string;\n name?: string;\n type?: string | null;\n description?: string | null;\n website?: string | null;\n aliases?: string[];\n affiliatedEntities?: string[];\n hours?: string | null;\n claimNumberHint?: string | null;\n billProcessingWorkflow?: string | null;\n billProcessingWorkflowNotes?: string | null;\n telephoneNumbers?: string[];\n emailAddresses?: string[];\n webPortals?: string[];\n payers?: BillClaimsAdministratorPayer[];\n authorizationNotice?: string | null;\n billReview?: BillClaimsAdministratorContact[];\n authorization?: BillClaimsAdministratorContact[];\n mailingAddresses?: BillClaimsAdministratorMailingAddress[];\n claimNumberPatterns?: BillClaimsAdministratorPattern[];\n};\n\n/** End-user-safe details explaining why the latest submission was rejected. */\nexport type BillRejectionIssue = {\n code?: string | null;\n description: string;\n /** Bill-submission field paths implicated by this issue. */\n fieldPaths?: string[];\n};\n\nexport type BillRejection = {\n reason: string;\n code?: string | null;\n issues?: BillRejectionIssue[];\n receivedAt?: string | null;\n source?: string | null;\n};\n\nexport type BillTeamNote = { id: string; body: string; author: string; createdAt: string; pinned: boolean };\n\nexport type BillCourtesyCopyInput = {\n to: string[];\n cc?: string[];\n subject: string;\n bodyText: string;\n includeCms1500?: boolean;\n documentIds?: string[];\n};\nexport type BillCourtesyCopyPreview = {\n filename: string; documentCount: number; packetHash: string; pdfBase64: string;\n environment: \"sandbox\" | \"live\";\n};\nexport type BillCourtesyCopyResult = { ok: boolean; sent: boolean; simulated?: boolean; dryRun?: boolean; messageId?: string };\n\n/** Historical financial balances are unavailable, not zero. */\nexport type HistoricalBillReviewData = Omit<BillReviewData, \"bill\"> & {\n bill: Omit<BillReviewData[\"bill\"], \"totalPaid\" | \"balanceDue\"> & {\n totalPaid: number | null;\n balanceDue: number | null;\n };\n};\nexport type BillSubmissionDetail = {\n attemptId: string;\n billId: string;\n source: \"submission_snapshot\" | \"bill_record\" | \"unavailable\";\n capturedAt?: string | null;\n detail: HistoricalBillReviewData | null;\n /** Exact retained files for this attempt; never regenerated from current bill values. */\n artifacts?: Array<{ id: string; label: string; kind: \"submitted_attachment\" | \"submitted_edi\"; contentType: string }>;\n};\n\nexport type BillLifecycleData = BillReviewData & {\n environment: \"sandbox\" | \"live\";\n lifecycle: {\n state: string;\n nativeStatus: string;\n submittedAt?: string | null;\n agingDays?: number | null;\n updatedAt?: string | null;\n actions: BillLifecycleAction[];\n };\n eors: BillEorDocument[];\n activity: BillActivityRecord[];\n /** Presented history rows. Optional: absent when the API\n * predates the presented-history rollout — fall back to `activity`. */\n history?: BillHistoryEntry[];\n /** Canonical team notes, shared with the MindBill app. Absent on older APIs. */\n notes?: BillTeamNote[];\n /** Immutable submissions that share this bill's unified history. */\n attempts?: BillAttemptSummary[];\n /** Per-attempt details. Older APIs may omit this; never substitute the current bill. */\n submissionDetails?: BillSubmissionDetail[];\n payments: BillPaymentRecord[];\n remittance: BillRemittanceSummary;\n delivery: BillLifecycleDelivery;\n rejection?: BillRejection | null;\n};\n\nexport type BillLifecycleSession = {\n token: string;\n expiresAt?: string;\n apiBaseUrl?: string;\n};\n\nexport type BillLifecycleSessionRequest = {\n signal: AbortSignal;\n};\n\nexport type BillLifecycleSessionProvider = (\n request: BillLifecycleSessionRequest,\n) => Promise<BillLifecycleSession>;\n\nexport type CloseBillInput = BillActorInput & { reason: string };\nexport type ReopenBillInput = BillActorInput & { reason: string };\nexport type PostBillPaymentInput = BillActorInput & {\n amount: number;\n penaltyAmount?: number;\n interestAmount?: number;\n method: \"check\" | \"eft\";\n checkNumber?: string;\n depositDate: string;\n note?: string;\n};\nexport type SecondReviewLineInput = {\n lineItemId: string;\n reason: string;\n /** SBR-1 box for this service line. Omitted leaves the box blank. */\n serviceAuthorized?: boolean;\n /** Absolute corrected values for this Second Review only; charge is explicitly reviewed, never inferred. */\n correction?: { units: number; modifiers: string[]; charge: number };\n};\n\nexport type SubmitSecondReviewInput = BillActorInput & {\n /** @deprecated Prefer `lineItems[].reason`; retained for older hosts. */\n reason?: string;\n /** @deprecated MindBill derives this from the payer response on the server. */\n payerClaimControlNumber?: string;\n disputedAmount?: number;\n attachmentIds: string[];\n route: BillSubmissionRoute;\n /** New PDFs to include with the Second Review. */\n documents?: BrowserBillSubmissionDocument[];\n destination?: SubmitBillInput[\"destination\"];\n attention?: string;\n subject?: string;\n note?: string;\n cc?: string[];\n /** Line-by-line SBR-1 selections, reasons, and authorization answers. */\n lineItems?: SecondReviewLineInput[];\n /** @deprecated Prefer `lineItems`; omitted = the whole bill. */\n lineItemIds?: string[];\n /** @deprecated Prefer `lineItems[].serviceAuthorized`. */\n serviceAuthorized?: boolean;\n};\n\nexport type ReportBillStatusId =\n | \"message_left\"\n | \"eor_pending\"\n | \"eor_sent\"\n | \"bill_not_on_file\"\n | \"forwarded\";\n\nexport type ReportBillStatusOption = {\n id: ReportBillStatusId;\n label: string;\n description: string;\n};\n\n/** The five supported outcomes of a bill payment-status phone call. */\nexport const REPORT_BILL_STATUS_OPTIONS: ReportBillStatusOption[] = [\n {\n id: \"message_left\",\n label: \"Message Left Requesting Bill Payment Status\",\n description: \"Claims Administrator/Bill Review representative unavailable.\",\n },\n {\n id: \"eor_pending\",\n label: \"Explanation of Review (EOR) Pending\",\n description: \"Claims Administrator/Bill Review reported the bill is still in process and an EOR has not been generated or sent.\",\n },\n {\n id: \"eor_sent\",\n label: \"Explanation of Review (EOR) Sent\",\n description: \"Claims Administrator/Bill Review reported sending an EOR to the provider.\",\n },\n {\n id: \"bill_not_on_file\",\n label: \"Bill Not On File\",\n description: \"Claims Administrator/Bill Review reported not receiving the bill.\",\n },\n {\n id: \"forwarded\",\n label: \"Bill Forwarded to Different Payer / Network\",\n description: \"Claims Administrator/Bill Review reported forwarding the bill to a different payer.\",\n },\n];\n\n/**\n * Outcome of a phone call to the Claims Administrator / Bill Review vendor\n * about an outstanding bill, recorded through the lifecycle actions endpoint.\n */\nexport type ReportBillStatusInput = BillActorInput & {\n status: ReportBillStatusId;\n company?: string;\n representativeName?: string;\n representativeRole?: string;\n phone?: string;\n callReference?: string;\n note?: string;\n};\n\n/**\n * Payload for the \"report_bill_status\" lifecycle action: records the outcome\n * of a phone call to the Claims Administrator / Bill Review vendor about an\n * outstanding bill. Posted through the generic lifecycle actions endpoint.\n */\nexport type ReportBillStatusActionInput = ReportBillStatusInput & {\n action: \"report_bill_status\";\n};\n\n/**\n * Payload for the \"send_duplicate\" lifecycle action. A duplicate is a fresh,\n * editable bill snapshot linked to the submitted original. The original stays\n * immutable; the biller must review the snapshot and explicitly confirm its\n * delivery route before this action is posted.\n */\nexport type SendDuplicateBillInput = ResubmitBillInput;\n\nexport type ReportBillStatusContacts = {\n claimsAdmin: {\n name: string;\n hoursOfOperation?: string;\n phones: Array<{ label: string; value: string }>;\n } | null;\n billReview: { name: string; phone?: string } | null;\n};\n\n/**\n * Partner-safe \"who to call\" summary for the Report Bill Status flow, derived\n * from the lifecycle delivery block (payer contacts + optional directory).\n */\nexport function reportBillStatusContacts(\n delivery: BillLifecycleDelivery,\n): ReportBillStatusContacts {\n const payerName = delivery.payerName?.trim();\n const directory = delivery.directory ?? null;\n const phones: Array<{ label: string; value: string }> = [];\n const adjusterPhone = delivery.contacts.adjusterPhone?.trim();\n if (adjusterPhone) {\n const adjusterName = delivery.contacts.adjusterName?.trim();\n phones.push({\n label: adjusterName ? `Adjuster (${adjusterName})` : \"Adjuster\",\n value: adjusterPhone,\n });\n }\n const hours = directory?.hours?.trim();\n const claimsAdmin = payerName\n ? {\n name: payerName,\n ...(hours ? { hoursOfOperation: hours } : {}),\n phones,\n }\n : null;\n const billReviewContact = (directory?.billReview ?? []).find(\n (contact) => contact.name?.trim() || contact.phone?.trim(),\n );\n const billReview = billReviewContact\n ? {\n name: billReviewContact.name?.trim() || \"Bill Review\",\n ...(billReviewContact.phone?.trim() ? { phone: billReviewContact.phone.trim() } : {}),\n }\n : null;\n return { claimsAdmin, billReview };\n}\n\n/**\n * Default Second Bill Review dispute reason for an invalid med-legal denial.\n * Prefilled (editable) in the SBR panel.\n */\nexport const SECOND_REVIEW_REASON_TEMPLATE =\n \"This is an appeal of the invalid denial of this med-legal bill; per LC §4622 and the OMFS/MLFS, payment is due as billed.\";\n\n/** Days allowed to request Second Review after service of the denial EOR. */\nexport const SECOND_REVIEW_WINDOW_DAYS = 90;\n\nexport type SecondReviewDeadline = {\n /** ISO date (yyyy-mm-dd) of the latest denial/EOR document. */\n eorDate: string;\n /** ISO date (yyyy-mm-dd) 90 days after the EOR date. */\n deadline: string;\n};\n\n/**\n * The 90-day Second Review window anchored on the latest EOR date, or null\n * when the lifecycle data provides no parseable denial/EOR date.\n */\nexport function secondReviewDeadline(\n eors: Array<Pick<BillEorDocument, \"addedAt\">>,\n): SecondReviewDeadline | null {\n const times = eors\n .map((eor) => Date.parse(eor.addedAt))\n .filter((time) => Number.isFinite(time));\n if (!times.length) return null;\n const eorTime = Math.max(...times);\n const isoDate = (time: number): string => new Date(time).toISOString().slice(0, 10);\n return {\n eorDate: isoDate(eorTime),\n deadline: isoDate(eorTime + SECOND_REVIEW_WINDOW_DAYS * 86_400_000),\n };\n}\n/**\n * A corrected immutable snapshot submitted as the next attempt on the same bill.\n * The logical bill ID remains stable; only the submission/control-number attempt advances.\n */\nexport type ResubmitBillInput = BillActorInput & {\n reason?: string;\n bill: BrowserBillCreateInput;\n /** Explicit delivery route confirmed by the biller for this new attempt. */\n submission?: Omit<SubmitBillInput, keyof BillActorInput>;\n documents?: BrowserBillSubmissionDocument[];\n};\n/**\n * \"Submit New Bill\" from a CLOSED bill: the same snapshot payload shape as a\n * resubmission, but the server creates a FRESH original bill linked to the closed\n * predecessor — the closed bill stays closed and keeps its record, and the\n * submissions ribbon/timeline chains both records.\n */\nexport type SubmitNewBillInput = ResubmitBillInput;\nexport type SandboxSimulationScenario = \"accepted\" | \"rejected\" | \"processed\" | \"denied\" | \"partial_payment\" | \"paid\";\nexport type SimulateSandboxBillInput = {\n scenario: SandboxSimulationScenario;\n amount?: number;\n reasonCode?: string;\n};\n\nexport type BrowserBillAddress = {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n postalCode: string;\n};\n\n/** Complete bill snapshot accepted by the browser create endpoint. */\nexport type BrowserBillCreateInput = {\n externalId?: string;\n billingMode?: \"med_legal\" | \"professional\";\n patient: {\n id?: string;\n externalId?: string;\n firstName: string;\n middleName?: string;\n lastName: string;\n dateOfBirth: string;\n ssn?: string;\n gender?: \"M\" | \"F\" | \"X\";\n phone?: string;\n address: BrowserBillAddress;\n };\n claim: {\n id?: string;\n externalId?: string;\n claimNumber: string;\n adjNumber?: string;\n employer: string;\n dateOfInjury: string;\n injuryState?: string;\n description?: string;\n claimsAdministrator: {\n id: string;\n name: string;\n /** The chosen payer (subpayor) when the claims administrator requires payer selection. */\n payerId?: string;\n };\n };\n service: { date: string; endDate?: string | null; authorizationNumber?: string | null };\n billingProvider: { id?: string; name: string; taxId: string; taxIdType?: \"EIN\" | \"SSN\"; npi: string; phone: string; address: BrowserBillAddress } | { savedProviderId: string } | { sourceBillId: string };\n renderingProvider: {\n name: string;\n specialty?: string;\n npi: string;\n taxonomy: string;\n licenseNumber?: string;\n licenseState?: string;\n isQme?: boolean;\n isAme?: boolean;\n };\n serviceLocation: { name?: string; address: BrowserBillAddress; placeOfServiceCode: string };\n diagnoses: string[];\n serviceLines: Array<{\n code: string;\n modifiers?: string[];\n units?: number;\n charge?: number;\n serviceDate?: string;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n /** Calculation context revalidated by the server before bill creation. */\n feeContext?: BillFeeContext;\n drug?: BilledDrug;\n /** Existing authorized RFA item linked to this service line. */\n rfaItemId?: string;\n }>;\n};\n\n/** Canonical immutable PDF snapshot sent with a bill submission. */\nexport type BrowserBillSubmissionDocument = {\n externalId?: string;\n filename: string;\n description?: string;\n documentType: BillReviewDocumentType;\n /** Opaque PWK report-type code selected by the component (for example OZ:J4). */\n reportTypeCode?: string;\n contentBase64: string;\n};\n\nexport type BrowserBillSubmissionInput = BillActorInput & {\n /** Usually omitted: MindBill stamps the customer from the server-issued session.\n * If supplied, it must match the session customer restriction. */\n customerExternalId?: string;\n bill: BrowserBillCreateInput;\n submission?: {\n route?: BillSubmissionRoute;\n destination?: SubmitBillInput[\"destination\"];\n attention?: string;\n subject?: string;\n note?: string;\n cc?: string[];\n };\n documents?: BrowserBillSubmissionDocument[];\n};\n\nexport type BrowserSubmittedBill = Record<string, unknown> & {\n id: string;\n customerExternalId?: string | null;\n externalId?: string | null;\n state?: string;\n};\n\nexport type BrowserBillSubmissionResult = {\n billId: string;\n bill: BrowserSubmittedBill;\n};\n\nexport type BillLifecycleClientOptions = {\n /** ID of an already-submitted bill. Bills are created only by the atomic server API. */\n billId: string;\n sessionEndpoint?: string | undefined;\n getSession?: BillLifecycleSessionProvider | undefined;\n apiBaseUrl?: string | undefined;\n fetch?: typeof globalThis.fetch | undefined;\n};\n\n/** Browser-session options for pre-submission reference-data lookups. */\nexport type BillReferenceClientOptions = Omit<BillLifecycleClientOptions, \"billId\">;\n\n/** Browser-session options for an atomic immutable bill submission. */\nexport type BillSubmissionClientOptions = BillReferenceClientOptions;\n\nexport type BillSubmissionClient = {\n submitBill: (\n input: BrowserBillSubmissionInput,\n options?: { idempotencyKey?: string },\n ) => Promise<BrowserBillSubmissionResult>;\n clearSession: () => void;\n};\n\n/** Input for the pre-submission delivery preview keyed on a payer-directory id. */\nexport type BillDeliveryPreviewInput = {\n claimsAdministratorId: string;\n /** Selected payer child when the administrator exposes multiple payer routes. */\n payerId?: string;\n /** Two-letter state; defaults to CA server-side. */\n injuryState?: string;\n};\n\nexport type BillProcedureCodeSearchInput = {\n query?: string;\n limit?: number;\n jurisdiction?: \"CA\" | \"NY\" | \"OWCP\";\n};\n\n/** Catalog membership does not imply that a fee is available for a service date. */\nexport type BillProcedureCodePage = {\n results: Array<{ code: string }>;\n total: number;\n limit: number;\n jurisdiction: \"CA\" | \"NY\" | \"OWCP\";\n catalogAsOf: string | null;\n};\n\nexport type BillFeeSource = {\n id: string;\n url: string;\n sha256?: string;\n effectiveFrom: string;\n effectiveThrough: string;\n};\n\n/** Drug identifiers and quantities printed on the professional claim. */\nexport type BilledDrug = {\n ndcNumber: string;\n metricQuantity: string;\n unitOfMeasure: \"UN\" | \"ML\" | \"GR\";\n administered?: {\n drugName: string;\n administeredAmount: string;\n doseUnit: \"mg\" | \"mcg\" | \"g\" | \"mL\" | \"units\";\n hcpcsCode: string;\n amountPerHcpcsUnit: string;\n amountPerNdcUnit: string;\n hcpcsUnitSource: string;\n productLabelSource: string;\n unitDefinitionsVerified: true;\n };\n};\n\n/** Minutes since midnight on the service date; end must follow start. */\nexport type CaAnesthesiaInterval = { startMinute: number; endMinute: number };\n/** Opaque references to the actual physician and service record. */\nexport type CaAnesthesiaEvent = { physicianRef: string; recordRef: string; minute: number };\nexport type CaAnesthesiaParticipation = CaAnesthesiaInterval & { physicianRef: string; recordRef: string };\nexport type CaAnesthesiaOptionalParticipation = CaAnesthesiaParticipation | { applicability: \"not_indicated\"; recordRef: string };\nexport type CaMedicalDirectionCase = {\n caseRef: string;\n anesthetistRole: \"crna\" | \"anesthesiologist_assistant\" | \"intern\" | \"resident\" | \"student_nurse_anesthetist\";\n qualificationRecordRef: string;\n procedure: \"cataract\" | \"iridectomy\" | \"other\";\n interval: CaAnesthesiaInterval;\n activities: {\n preAnestheticEvaluation: CaAnesthesiaEvent;\n prescribedPlan: CaAnesthesiaEvent;\n demandingProcedures: CaAnesthesiaParticipation[];\n induction: CaAnesthesiaOptionalParticipation;\n emergence: CaAnesthesiaOptionalParticipation;\n qualifiedAnesthetistProcedures: CaAnesthesiaEvent;\n frequentMonitoring: { recordRef: string; observations: CaAnesthesiaEvent[] };\n indicatedPostAnesthesiaCare: CaAnesthesiaEvent;\n };\n};\n/** All overlapping cases across all payers, including cases outside this bill. */\nexport type CaMedicalDirection = {\n physicianRef: string;\n groupPhysicianRefs: string[];\n billedCaseRef: string;\n rosterScope: \"all_overlapping_cases_all_payers\";\n rosterRecordRef: string;\n cases: CaMedicalDirectionCase[];\n physicalPresenceAndImmediateAvailability: CaAnesthesiaParticipation[];\n otherPatientServices: Array<{\n kind: \"emergency\" | \"labor_analgesia\" | \"obstetric_monitoring\" | \"receiving_patient\" | \"recovery_care\" | \"other\";\n interval: CaAnesthesiaInterval;\n recordRef: string;\n }>;\n};\nexport type CaMonitoredAnesthesiaCare = {\n medicallyNecessary: true;\n intraoperativePhysiologicalMonitoring: true;\n preparedForGeneralAnesthesiaOrAdverseReaction: true;\n perioperativeAnesthesiaCare: true;\n underlyingProcedureProvider: \"different_provider\" | \"same_provider\";\n underlyingProcedure: \"nerve_block_or_injection\" | \"other\";\n};\n/** Clinical facts supplement AA or QK; monitored care also requires QS. */\nexport type CaAnesthesiaContext = {\n providerKind: \"physician\";\n actualMinutes: number;\n placeOfService: string;\n completeSameDayServices: true;\n otherSameDayServices: boolean;\n codingRequirementsSatisfied: true;\n monitoredCare?: CaMonitoredAnesthesiaCare;\n} & ({ personallyPerformedAlone: true; medicalDirection?: never } | { personallyPerformedAlone: false; medicalDirection: CaMedicalDirection });\n\nexport type CaPadbContext = {\n providerKind: \"physician\";\n placeOfService: \"11\";\n productKind: \"injectable\";\n bundledOrPackaged: false;\n codingRequirementsSatisfied: true;\n completeSameDayServices: true;\n sameDayServices: Array<{ code: string; units: number }>;\n};\n\nexport type CaTherapyContext = {\n providerKind: \"physical_therapist\" | \"other\";\n personallyPerformed: boolean;\n hospitalPatient: boolean;\n incidentToPhysicianService: boolean;\n assistantInvolved: boolean;\n placeOfService: string;\n directOneOnOneMinutes: number;\n totalVisitMinutes: number;\n visitsOnDate: number;\n completeSameDayServices: boolean;\n otherSameDayServices: boolean;\n globalPeriodApplies: boolean;\n hpsaBonusEligible: boolean;\n };\n\n/** Documented interpretation and imaging-session facts; an omitted completeness fact remains unknown. */\nexport type CaProfessionalComponentContext = {\n interpretationLocation: \"same_as_patient_service\" | \"different_from_patient_service\";\n supervisionLevel?: \"general\" | \"direct\" | \"personal\";\n /** Actual session label, 1–64 letters/digits/._:-, beginning with a letter or digit. Never a patient identifier. */\n imagingSessionReference?: string;\n /** All imaging for this patient/provider group/date is included, including separately billed services. */\n completeSameDayImagingServices?: boolean;\n};\n\nexport type BillFeeQuoteInput = {\n drug?: BilledDrug;\n padbContext?: CaPadbContext;\n anesthesiaContext?: CaAnesthesiaContext;\n billingProviderId?: string;\n payerId?: string;\n code: string;\n dateOfService: string;\n chargeCents?: number;\n units?: number;\n modifiers?: string[];\n pages?: number;\n reportKind?: \"progress\" | \"permanent_stationary_pr3\" | \"permanent_stationary_pr4\";\n hasFeeAgreement?: boolean;\n serviceZip?: string;\n /** Explicit physical interpretation location for a professional component. */\n professionalComponentContext?: CaProfessionalComponentContext;\n /** California equipment pricing uses worker residence, independently of service location. */\n dmeposContext?: {\n residenceZip: string;\n /** Continuous rental month for this equipment item; only for applicable RR lines. */\n rentalMonth?: number;\n /** Actual prior payments for this item, including rentals; explicit zero means no prior payments. */\n priorPaymentsCents?: number;\n };\n /** Supply verified service facts; omitted context can require review. */\n physicianContext?: {\n providerKind: \"physician\" | \"physician_assistant\" | \"nurse_practitioner\" | \"clinical_nurse_specialist\" | \"other\";\n incidentToPhysicianService?: boolean;\n placeOfService: string;\n standaloneService: boolean;\n globalPeriodApplies: boolean;\n hpsaBonusEligible: boolean;\n };\n therapyContext?: CaTherapyContext;\n catalogContext?: {\n codingRequirementsSatisfied: boolean;\n statusIAlternative?: \"none\" | \"cpt\" | \"drug\";\n completeSurgicalPackage?: boolean;\n };\n prolongedServiceContext?: {\n totalMinutes: number;\n relatedEvaluationDate: string;\n ongoingPatientManagement: boolean;\n personallyPerformed: boolean;\n timeCountedInOtherServices: boolean;\n completeSameDayServices: boolean;\n sameDayServices: Array<{ code: string; units: number }>;\n };\n reportQualification?:\n | { kind: \"psychiatric_report\"; requestedBy: \"wcab\" | \"administrative_director\"; medicalLegalEvaluation: boolean; reportPayableUnderMedicalLegalSchedule: boolean }\n | { kind: \"consultation_report\"; requestedBy: \"wcab\" | \"administrative_director\" | \"qme\" | \"ame\"; medicalLegalEvaluation: boolean; reportPayableUnderMedicalLegalSchedule: boolean }\n | { kind: \"chart_notes\"; requestedBy: \"claims_administrator\"; writtenRequest: boolean }\n | { kind: \"duplicate_report\"; requestedBy: \"claims_administrator\"; writtenRequest: boolean; relatedToBilling: boolean; initialRequiredCopy: boolean };\n};\n\n/** Authoritative service, provider, payer and location fields come from the submitted bill. */\nexport type BillFeeContext = Omit<BillFeeQuoteInput, \"code\" | \"dateOfService\" | \"units\" | \"modifiers\" | \"chargeCents\" | \"billingProviderId\" | \"payerId\" | \"serviceZip\" | \"drug\">;\n\n/** Fee families returned by the California and practice-contract quote endpoint. */\nexport const BILL_FEE_QUOTE_BASES = [\n \"ca_report\", \"ca_physician_rbrvs\", \"ca_therapy_rbrvs\", \"ca_clfs\",\n \"ca_simple_dispensed_drug\", \"ca_dmepos\", \"ca_padb\", \"ca_anesthesia\", \"payer_contract\",\n] as const;\nexport type BillFeeQuoteBasis = typeof BILL_FEE_QUOTE_BASES[number];\n\nexport type BillFeeQuote =\n | {\n status: \"priced\";\n /** Total for the service line in cents, already accounting for units. */\n amountCents: number;\n scheduleMaximumCents: number;\n basis: BillFeeQuoteBasis;\n anesthesia?: { actualMinutes: number; baseUnits: number; timeUnitsTenths: number; conversionFactorCents: number; locality: string; medicalDirection?: { concurrentCases: number; baseReductionPercent: number; physicianPaymentPercent: 50 } };\n provenance: BillFeeSource[];\n notes: string[];\n }\n | { status: \"requires_review\" | \"not_separately_payable\"; reason: string; provenance: BillFeeSource[] };\n\nexport type BillReferenceClient = {\n listClaimsAdministrators: (input?: BillReviewPayerListInput) => Promise<BillReviewPayerPage>;\n searchClaimsAdministrators: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;\n getClaimsAdministratorDirectory: (id: string, injuryState?: string) => Promise<BillClaimsAdministratorDirectory>;\n searchDiagnosisCodes: (query: string, limit?: number, offset?: number) => Promise<BillDiagnosisCode[]>;\n searchProcedureCodes: (input?: BillProcedureCodeSearchInput) => Promise<BillProcedureCodePage>;\n quoteFee: (input: BillFeeQuoteInput) => Promise<BillFeeQuote>;\n quoteClaimFees: (input: CaClaimFeeQuoteInput) => Promise<CaClaimFeeQuoteResult>;\n lookupPostalCode: (postalCode: string) => Promise<BillPostalPlace | null>;\n /**\n * Delivery-route preview (recommended route + selectable options + payer\n * contacts) for a claims administrator BEFORE the bill exists — powers the\n * send-route picker shown at submit time.\n */\n getDeliveryPreview: (input: BillDeliveryPreviewInput) => Promise<BillDeliveryOptions>;\n clearSession: () => void;\n};\n\nexport type BillLifecycleClient = {\n getBillId: () => string;\n getLifecycle: (signal?: AbortSignal) => Promise<BillLifecycleData>;\n listClaimsAdministrators: (input?: BillReviewPayerListInput) => Promise<BillReviewPayerPage>;\n searchClaimsAdministrators: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;\n getClaimsAdministratorDirectory: (id: string, injuryState?: string) => Promise<BillClaimsAdministratorDirectory>;\n searchDiagnosisCodes: (query: string, limit?: number, offset?: number) => Promise<BillDiagnosisCode[]>;\n searchProcedureCodes: (input?: BillProcedureCodeSearchInput) => Promise<BillProcedureCodePage>;\n quoteFee: (input: BillFeeQuoteInput) => Promise<BillFeeQuote>;\n quoteClaimFees: (input: CaClaimFeeQuoteInput) => Promise<CaClaimFeeQuoteResult>;\n lookupPostalCode: (postalCode: string) => Promise<BillPostalPlace | null>;\n getDeliveryOptions: () => Promise<BillDeliveryOptions>;\n getDeliveryPreview: (input: BillDeliveryPreviewInput) => Promise<BillDeliveryOptions>;\n getAttachment: (attachmentId: string) => Promise<Blob>;\n getEor: (documentId: string) => Promise<Blob>;\n getPacket: () => Promise<Blob>;\n getSubmissionArtifact: (attemptId: string, artifactId: string) => Promise<Blob>;\n /** Prepare a self-filing packet. Does not file IBR or send anything to a payer. */\n prepareIbrPacket: () => Promise<Blob>;\n previewCourtesyCopy: (input: BillCourtesyCopyInput) => Promise<BillCourtesyCopyPreview>;\n /** Reuse the same key when retrying the same send after a network interruption. */\n sendCourtesyCopy: (input: BillCourtesyCopyInput & { packetHash: string }, idempotencyKey: string) => Promise<BillCourtesyCopyResult>;\n addNote: (input: AddBillNoteInput) => Promise<BillLifecycleData>;\n closeBill: (input: CloseBillInput) => Promise<BillLifecycleData>;\n reopenBill: (input: ReopenBillInput) => Promise<BillLifecycleData>;\n postPayment: (input: PostBillPaymentInput) => Promise<BillLifecycleData>;\n submitSecondReview: (input: SubmitSecondReviewInput) => Promise<BillLifecycleData>;\n resubmitBill: (input: ResubmitBillInput) => Promise<BillLifecycleData>;\n submitNewBill: (input: SubmitNewBillInput) => Promise<BillLifecycleData>;\n sendDuplicateBill: (input: SendDuplicateBillInput) => Promise<BillLifecycleData>;\n reportBillStatus: (input: ReportBillStatusInput) => Promise<BillLifecycleData>;\n simulateSandbox: (input: SimulateSandboxBillInput) => Promise<BillLifecycleData>;\n clearSession: () => void;\n};\n\nasync function responseError(response: Response, fallback: string): Promise<Error> {\n const body: unknown = await response.json().catch(() => null);\n const detail = body && typeof body === \"object\"\n ? (body as { detail?: unknown; message?: unknown; error?: unknown }).detail\n ?? (body as { message?: unknown }).message\n ?? (body as { error?: unknown }).error\n : null;\n return new Error(typeof detail === \"string\" ? detail : fallback);\n}\n\nfunction isSessionFresh(session: BillLifecycleSession | null): boolean {\n if (!session) return false;\n if (!session.expiresAt) return true;\n const expiresAt = new Date(session.expiresAt).getTime();\n return Number.isFinite(expiresAt) && expiresAt > Date.now() + 30_000;\n}\n\nfunction normalizeSession(value: unknown): BillLifecycleSession {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing session endpoint returned an invalid response.\");\n }\n const candidate = value as { token?: unknown; expiresAt?: unknown; apiBaseUrl?: unknown; session?: unknown; data?: unknown };\n const nested = candidate.session ?? candidate.data;\n const session = nested && typeof nested === \"object\" ? nested as typeof candidate : candidate;\n if (typeof session.token !== \"string\" || session.token.length < 8) {\n throw new Error(\"The billing session endpoint did not return a browser session token.\");\n }\n return {\n token: session.token,\n ...(typeof session.expiresAt === \"string\" ? { expiresAt: session.expiresAt } : {}),\n ...(typeof session.apiBaseUrl === \"string\" ? { apiBaseUrl: session.apiBaseUrl } : {}),\n };\n}\n\nfunction normalizeLifecycle(value: unknown): BillLifecycleData {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n const data = value as Partial<BillLifecycleData>;\n if (\n ![\"sandbox\", \"live\"].includes(data.environment ?? \"\")\n || !data.bill\n || !data.patient\n || !data.injury\n || !data.lifecycle\n || !Array.isArray(data.lifecycle.actions)\n || !Array.isArray(data.eors)\n || !Array.isArray(data.activity)\n || !Array.isArray(data.payments)\n || !data.remittance\n || typeof data.remittance !== \"object\"\n || !data.delivery\n || typeof data.delivery !== \"object\"\n || !data.delivery.contacts\n || typeof data.delivery.contacts !== \"object\"\n || (data.rejection != null && (\n typeof data.rejection !== \"object\"\n || typeof data.rejection.reason !== \"string\"\n || (data.rejection.issues != null && (\n !Array.isArray(data.rejection.issues)\n || data.rejection.issues.some((issue) => (\n !issue\n || typeof issue !== \"object\"\n || typeof issue.description !== \"string\"\n || (issue.code != null && typeof issue.code !== \"string\")\n ))\n ))\n ))\n ) {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n return data as BillLifecycleData;\n}\n\nfunction normalizeDeliveryOptions(value: unknown): BillDeliveryOptions {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n const data = value as Partial<BillDeliveryOptions>;\n if (\n typeof data.payerName !== \"string\"\n || !data.recommended\n || typeof data.recommended !== \"object\"\n || ![\"ebill\", \"fax\", \"mail\", \"email\"].includes(data.recommended.route ?? \"\")\n || !Array.isArray(data.options)\n || !data.contacts\n ) {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n return data as BillDeliveryOptions;\n}\n\nfunction idempotencyKey(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") return globalThis.crypto.randomUUID();\n return `mb-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Browser-safe client for one atomic create-and-submit operation.\n *\n * The browser session is short-lived and origin-bound. The host application\n * never needs the Partner API document schema or a long-lived API key.\n */\nexport function createBillSubmissionClient({\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillSubmissionClientOptions = {}): BillSubmissionClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const submitBill = async (\n input: BrowserBillSubmissionInput,\n options: { idempotencyKey?: string } = {},\n ): Promise<BrowserBillSubmissionResult> => {\n const controller = new AbortController();\n const requestIdempotencyKey = options.idempotencyKey ?? idempotencyKey();\n let browserSession = await mintSession(controller.signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n return fetcher(`${base}/partner/v2/bills`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${current.token}`,\n \"content-type\": \"application/json\",\n \"idempotency-key\": requestIdempotencyKey,\n },\n body: JSON.stringify(input),\n signal: controller.signal,\n });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(controller.signal, true);\n response = await perform(browserSession);\n }\n if (!response.ok) throw await responseError(response, \"The bill could not be submitted.\");\n const body: unknown = await response.json().catch(() => null);\n const envelope = body && typeof body === \"object\" && \"data\" in body\n ? (body as { data?: unknown }).data\n : body;\n if (!envelope || typeof envelope !== \"object\" || typeof (envelope as { id?: unknown }).id !== \"string\") {\n throw new Error(\"The billing service submitted the bill but returned an invalid bill ID.\");\n }\n const bill = envelope as BrowserSubmittedBill;\n return { billId: bill.id, bill };\n };\n\n return {\n submitBill,\n clearSession() { session = null; sessionRequest = null; },\n };\n}\n\n/** Browser-safe, framework-neutral client for an already-submitted bill. */\nexport function createBillLifecycleClient({\n billId,\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillLifecycleClientOptions): BillLifecycleClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n const currentBillId = billId.trim();\n if (!currentBillId) throw new Error(\"billId is required for the submitted-bill lifecycle client.\");\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const request = async (path: string, init: RequestInit = {}, providedSignal?: AbortSignal): Promise<Response> => {\n const controller = providedSignal ? null : new AbortController();\n const signal = providedSignal ?? controller?.signal;\n if (!signal) throw new Error(\"An AbortSignal could not be created.\");\n let browserSession = await mintSession(signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n const headers = new Headers(init.headers);\n headers.set(\"authorization\", `Bearer ${current.token}`);\n return fetcher(`${base}${path}`, { ...init, headers, signal });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(signal, true);\n response = await perform(browserSession);\n }\n return response;\n };\n\n const billPath = (suffix = \"\"): string =>\n `/partner/v2/bills/${encodeURIComponent(currentBillId)}${suffix}`;\n\n const loadLifecycle = async (signal?: AbortSignal) => {\n const response = await request(billPath(\"/lifecycle\"), {}, signal);\n if (!response.ok) throw await responseError(response, \"Bill lifecycle could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n\n const listClaimsAdministrators = async (input: BillReviewPayerListInput = {}): Promise<BillReviewPayerPage> => {\n const params = new URLSearchParams();\n if (input.query?.trim()) params.set(\"q\", input.query.trim());\n if (input.claimNumber?.trim()) params.set(\"claimNumber\", input.claimNumber.trim());\n if (input.sourceClaimsAdministratorName?.trim()) params.set(\"sourceClaimsAdministratorName\", input.sourceClaimsAdministratorName.trim());\n if (input.employerName?.trim()) params.set(\"employerName\", input.employerName.trim());\n const limit = Math.max(1, Math.min(100, Math.floor(input.limit ?? 50)));\n const offset = Math.max(0, Math.floor(input.offset ?? 0));\n params.set(\"limit\", String(limit));\n if (offset) params.set(\"offset\", String(offset));\n const response = await request(`/partner/v2/claims-administrators?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator search is unavailable.\");\n const body = await response.json() as { results?: unknown; suggestions?: unknown; total?: unknown; nextOffset?: unknown; recommendedId?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Claims administrator search returned an invalid response.\");\n const normalizePayer = (value: unknown): BillReviewPayer | null => {\n if (!value || typeof value !== \"object\") return null;\n const payer = value as Record<string, unknown>;\n if (typeof payer.id !== \"string\" || typeof payer.name !== \"string\") return null;\n const payers = Array.isArray(payer.payers) ? payer.payers.flatMap((option): BillReviewPayerOption[] => {\n if (!option || typeof option !== \"object\") return [];\n const candidate = option as Record<string, unknown>;\n const id = typeof candidate.id === \"string\" ? candidate.id : typeof candidate.key === \"string\" ? candidate.key : null;\n if (!id || typeof candidate.label !== \"string\") return [];\n return [{\n id,\n label: candidate.label,\n ...(typeof candidate.default === \"boolean\" ? { default: candidate.default } : {}),\n ...(typeof candidate.active === \"boolean\" ? { active: candidate.active } : {}),\n ...(Array.isArray(candidate.aliases) ? { aliases: candidate.aliases.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof candidate.hint === \"string\" ? { hint: candidate.hint } : {}),\n ...(Array.isArray(candidate.affiliatedEntities) ? { affiliatedEntities: candidate.affiliatedEntities.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof candidate.route === \"string\" ? { route: candidate.route } : {}),\n ...(typeof candidate.optionType === \"string\" ? { optionType: candidate.optionType } : {}),\n ...(typeof candidate.deliveryType === \"string\" ? { deliveryType: candidate.deliveryType } : {}),\n ...(typeof candidate.clearinghouse === \"string\" ? { clearinghouse: candidate.clearinghouse } : {}),\n ...(typeof candidate.payerId === \"string\" ? { payerId: candidate.payerId } : {}),\n ...(typeof candidate.sourceClearinghouse === \"string\" ? { sourceClearinghouse: candidate.sourceClearinghouse } : {}),\n ...(typeof candidate.sourcePayerId === \"string\" ? { sourcePayerId: candidate.sourcePayerId } : {}),\n ...(candidate.clearinghousePayerIds && typeof candidate.clearinghousePayerIds === \"object\" && !Array.isArray(candidate.clearinghousePayerIds)\n ? { clearinghousePayerIds: Object.fromEntries(Object.entries(candidate.clearinghousePayerIds).filter((entry): entry is [string, string] => typeof entry[1] === \"string\")) }\n : {}),\n ...(typeof candidate.preferredClearinghouse === \"string\" ? { preferredClearinghouse: candidate.preferredClearinghouse } : {}),\n }];\n }) : undefined;\n const claimNumberPatterns = Array.isArray(payer.claimNumberPatterns) ? payer.claimNumberPatterns.flatMap((value): BillClaimsAdministratorPattern[] => {\n if (!value || typeof value !== \"object\") return [];\n const pattern = value as Record<string, unknown>;\n if (typeof pattern.pattern !== \"string\") return [];\n return [{\n pattern: pattern.pattern,\n ...(typeof pattern.length === \"string\" || typeof pattern.length === \"number\" ? { length: pattern.length } : {}),\n ...(typeof pattern.example === \"string\" ? { example: pattern.example } : {}),\n ...(typeof pattern.matches === \"boolean\" || pattern.matches === null ? { matches: pattern.matches as boolean | null } : {}),\n }];\n }) : undefined;\n return {\n id: payer.id,\n name: payer.name,\n ...(typeof payer.hasElectronic === \"boolean\" ? { hasElectronic: payer.hasElectronic } : {}),\n ...(Array.isArray(payer.states) ? { states: payer.states.filter((state): state is string => typeof state === \"string\") } : {}),\n ...([\"high\", \"medium\", \"directory\"].includes(String(payer.confidence)) ? { confidence: payer.confidence as NonNullable<BillReviewPayer[\"confidence\"]> } : {}),\n ...(typeof payer.recommended === \"boolean\" ? { recommended: payer.recommended } : {}),\n ...(typeof payer.payerSelectionRequired === \"boolean\" ? { payerSelectionRequired: payer.payerSelectionRequired } : {}),\n ...(payers ? { payers } : {}),\n ...(Array.isArray(payer.aliases) ? { aliases: payer.aliases.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(Array.isArray(payer.affiliatedEntities) ? { affiliatedEntities: payer.affiliatedEntities.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof payer.claimNumberHint === \"string\" ? { claimNumberHint: payer.claimNumberHint } : {}),\n ...(claimNumberPatterns ? { claimNumberPatterns } : {}),\n ...(typeof payer.route === \"string\" ? { route: payer.route } : {}),\n ...(Array.isArray(payer.signals) ? { signals: payer.signals.flatMap((signal) => {\n if (!signal || typeof signal !== \"object\") return [];\n const candidate = signal as Record<string, unknown>;\n if (![\"name\", \"claim_number\"].includes(String(candidate.kind)) || ![\"match\", \"warning\"].includes(String(candidate.state)) || typeof candidate.label !== \"string\") return [];\n return [{ kind: candidate.kind as \"name\" | \"claim_number\", state: candidate.state as \"match\" | \"warning\", label: candidate.label }];\n }) } : {}),\n };\n };\n const results = body.results.flatMap((value): BillReviewPayer[] => {\n const payer = normalizePayer(value);\n return payer ? [payer] : [];\n });\n const suggestions = Array.isArray(body.suggestions) ? body.suggestions.flatMap((value): BillReviewPayerSuggestion[] => {\n const payer = normalizePayer(value);\n if (!payer || !value || typeof value !== \"object\") return [];\n const suggestion = value as Record<string, unknown>;\n if (typeof suggestion.deterministic !== \"boolean\" || typeof suggestion.reason !== \"string\") return [];\n return [{ ...payer, deterministic: suggestion.deterministic, reason: suggestion.reason, ...(typeof suggestion.selectedPayerId === \"string\" ? { selectedPayerId: suggestion.selectedPayerId } : {}) }];\n }) : [];\n const total = typeof body.total === \"number\" && Number.isFinite(body.total) ? Math.max(results.length, Math.floor(body.total)) : offset + results.length;\n return {\n results,\n ...(suggestions.length ? { suggestions } : {}),\n total,\n ...(typeof body.nextOffset === \"number\" && Number.isFinite(body.nextOffset) ? { nextOffset: Math.floor(body.nextOffset) } : {}),\n ...(typeof body.recommendedId === \"string\" ? { recommendedId: body.recommendedId } : {}),\n };\n };\n\n const searchClaimsAdministrators = async (query: string, claimNumber?: string): Promise<BillReviewPayer[]> =>\n (await listClaimsAdministrators({ query, ...(claimNumber ? { claimNumber } : {}) })).results;\n\n const getClaimsAdministratorDirectory = async (id: string, injuryState?: string): Promise<BillClaimsAdministratorDirectory> => {\n const params = new URLSearchParams();\n if (injuryState?.trim()) params.set(\"injuryState\", injuryState.trim());\n const response = await request(`/partner/v2/claims-administrators/${encodeURIComponent(id)}${params.size ? `?${params}` : \"\"}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator details are unavailable.\");\n const body = await response.json() as { data?: unknown };\n if (!body.data || typeof body.data !== \"object\") throw new Error(\"Claims administrator details returned an invalid response.\");\n return body.data as BillClaimsAdministratorDirectory;\n };\n\n const searchDiagnosisCodes = async (query: string, limit = 30, offset = 0): Promise<BillDiagnosisCode[]> => {\n const params = new URLSearchParams({ q: query.trim(), limit: String(Math.max(1, Math.min(100, limit))) });\n if (offset > 0) params.set(\"offset\", String(Math.max(0, Math.floor(offset))));\n const response = await request(`/partner/v2/diagnosis-codes?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Diagnosis-code search is unavailable.\");\n const body = await response.json() as { results?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Diagnosis-code search returned an invalid response.\");\n return body.results.flatMap((value): BillDiagnosisCode[] => {\n if (!value || typeof value !== \"object\") return [];\n const candidate = value as { code?: unknown; description?: unknown };\n return typeof candidate.code === \"string\" && typeof candidate.description === \"string\"\n ? [{ code: candidate.code, description: candidate.description }]\n : [];\n });\n };\n\n const searchProcedureCodes = async (input: BillProcedureCodeSearchInput = {}): Promise<BillProcedureCodePage> => {\n const limit = Number.isFinite(input.limit) ? Math.max(1, Math.min(100, Math.floor(input.limit!))) : 30;\n const params = new URLSearchParams({ q: input.query?.trim() ?? \"\", limit: String(limit), jurisdiction: input.jurisdiction?.trim().toUpperCase() || \"CA\" });\n const response = await request(`/partner/v2/procedure-codes?${params}`);\n if (!response.ok) throw await responseError(response, \"Procedure-code search is unavailable.\");\n const body = await response.json() as Partial<BillProcedureCodePage>;\n if (!Array.isArray(body.results) || typeof body.total !== \"number\" || !Number.isFinite(body.total) || body.total < 0 || typeof body.limit !== \"number\" || !Number.isFinite(body.limit) || body.limit < 1 || ![\"CA\", \"NY\", \"OWCP\"].includes(body.jurisdiction ?? \"\") || !(body.catalogAsOf === null || typeof body.catalogAsOf === \"string\")) {\n throw new Error(\"Procedure-code search returned an invalid response.\");\n }\n return {\n results: body.results.flatMap((entry) => entry && typeof entry.code === \"string\" && entry.code.trim() ? [{ code: entry.code }] : []),\n total: body.total,\n limit: body.limit,\n jurisdiction: body.jurisdiction!,\n catalogAsOf: body.catalogAsOf,\n };\n };\n\n const quoteClaimFees = async (input: CaClaimFeeQuoteInput): Promise<CaClaimFeeQuoteResult> => {\n const response = await request(\"/partner/v2/fee-quotes/ca/claim\", {\n method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify(input),\n });\n if (!response.ok) throw await responseError(response, \"Claim fee pricing is unavailable.\");\n const body = await response.json() as { data?: unknown };\n return parseCaClaimFeeQuote(body.data, input);\n };\n\n const quoteFee = async (input: BillFeeQuoteInput): Promise<BillFeeQuote> => {\n const response = await request(\"/partner/v2/fee-quotes\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n });\n if (!response.ok) throw await responseError(response, \"Fee-schedule pricing is unavailable.\");\n const body = await response.json() as { data?: BillFeeQuote };\n const quote = body.data;\n if (!quote || !Array.isArray(quote.provenance)) throw new Error(\"Fee quote returned an invalid response.\");\n if (quote.status === \"priced\") {\n if (!Number.isSafeInteger(quote.amountCents) || quote.amountCents < 0 || !Number.isSafeInteger(quote.scheduleMaximumCents) || quote.scheduleMaximumCents < 0 || !BILL_FEE_QUOTE_BASES.includes(quote.basis) || !Array.isArray(quote.notes) || quote.notes.some((note) => typeof note !== \"string\")) throw new Error(\"Fee quote returned an invalid response.\");\n } else if ((quote.status !== \"requires_review\" && quote.status !== \"not_separately_payable\") || typeof quote.reason !== \"string\") {\n throw new Error(\"Fee quote returned an invalid response.\");\n }\n return quote;\n };\n\n const lookupPostalCode = async (postalCode: string): Promise<BillPostalPlace | null> => {\n const params = new URLSearchParams({ postalCode: postalCode.trim() });\n const response = await request(`/partner/v2/postal-codes?${params.toString()}`);\n if (response.status === 404) return null;\n if (!response.ok) throw await responseError(response, \"ZIP lookup is unavailable.\");\n const body = await response.json() as { city?: unknown; state?: unknown };\n if (typeof body.city !== \"string\" || typeof body.state !== \"string\") {\n throw new Error(\"ZIP lookup returned an invalid response.\");\n }\n return { city: body.city, state: body.state };\n };\n\n const mutation = async (path: string, init: RequestInit, fallback: string) => {\n const headers = new Headers(init.headers);\n headers.set(\"idempotency-key\", idempotencyKey());\n const response = await request(path, { ...init, headers });\n if (!response.ok) throw await responseError(response, fallback);\n return response;\n };\n const action = async (input: Record<string, unknown>, fallback: string): Promise<BillLifecycleData> => {\n const response = await mutation(billPath(\"/actions\"), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, fallback);\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n const simulateSandbox = async (input: SimulateSandboxBillInput): Promise<BillLifecycleData> => {\n await mutation(`/partner/v2/sandbox/bills/${encodeURIComponent(currentBillId)}/simulate`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, \"Sandbox lifecycle could not be simulated.\");\n return loadLifecycle();\n };\n return {\n getBillId() { return currentBillId; },\n clearSession() { session = null; sessionRequest = null; },\n getLifecycle: loadLifecycle,\n listClaimsAdministrators,\n searchClaimsAdministrators,\n getClaimsAdministratorDirectory,\n searchDiagnosisCodes,\n searchProcedureCodes,\n quoteFee,\n quoteClaimFees,\n lookupPostalCode,\n async getDeliveryOptions() {\n const response = await request(billPath(\"/delivery-options\"));\n if (!response.ok) throw await responseError(response, \"Delivery options could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getDeliveryPreview(input) {\n const params = new URLSearchParams({ claimsAdministratorId: input.claimsAdministratorId.trim() });\n if (input.payerId?.trim()) params.set(\"payerId\", input.payerId.trim());\n if (input.injuryState?.trim()) params.set(\"injuryState\", input.injuryState.trim());\n const response = await request(`/partner/v2/delivery-preview?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Delivery routes could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getAttachment(attachmentId) {\n const response = await request(billPath(`/documents/${encodeURIComponent(attachmentId)}`));\n if (!response.ok) throw await responseError(response, \"Document could not be opened.\");\n return response.blob();\n },\n async getEor(documentId) {\n const response = await request(billPath(`/eors/${encodeURIComponent(documentId)}`));\n if (!response.ok) throw await responseError(response, \"EOR could not be opened.\");\n return response.blob();\n },\n async getPacket() {\n const response = await request(billPath(\"/packet\"));\n if (!response.ok) throw await responseError(response, \"Submission packet could not be downloaded.\");\n return response.blob();\n },\n async getSubmissionArtifact(attemptId, artifactId) {\n const response = await request(billPath(`/submissions/${encodeURIComponent(attemptId)}/artifacts/${encodeURIComponent(artifactId)}`));\n if (!response.ok) throw await responseError(response, \"The retained submission file could not be downloaded.\");\n return response.blob();\n },\n async prepareIbrPacket() {\n const prepared = await mutation(billPath(\"/actions\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ action: \"independent_bill_review\" }),\n }, \"IBR packet could not be prepared.\");\n const body = await prepared.json() as { packetUrl?: unknown };\n // Never forward the browser bearer token to an arbitrary response URL.\n if (typeof body.packetUrl !== \"string\" || !/^\\/partner\\/v2\\/(?:browser\\/)?bills\\/[A-Za-z0-9_-]+\\/ibr-packet$/.test(body.packetUrl)) throw new Error(\"The billing service returned an invalid IBR packet path.\");\n // The server may resolve a root bill to its current linked bill.\n const response = await request(body.packetUrl);\n if (!response.ok) throw await responseError(response, \"IBR packet could not be downloaded.\");\n return response.blob();\n },\n async previewCourtesyCopy(input) {\n const response = await request(billPath(\"/courtesy-forward\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ ...input, mode: \"preview\" }),\n });\n if (!response.ok) throw await responseError(response, \"Courtesy copy could not be previewed.\");\n return response.json() as Promise<BillCourtesyCopyPreview>;\n },\n async sendCourtesyCopy(input, key) {\n if (!key.trim() || key.length > 255) throw new Error(\"A stable idempotency key is required to send a courtesy copy.\");\n const response = await request(billPath(\"/courtesy-forward\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\", \"idempotency-key\": key },\n body: JSON.stringify({ ...input, mode: \"send\" }),\n });\n if (!response.ok) throw await responseError(response, \"Courtesy copy could not be sent. Retry with the same key to check the result safely.\");\n return response.json() as Promise<BillCourtesyCopyResult>;\n },\n addNote(input) { return action({ action: \"add_note\", ...input }, \"Note could not be added.\"); },\n closeBill(input) { return action({ action: \"close\", ...input }, \"Bill could not be closed.\"); },\n reopenBill(input) { return action({ action: \"reopen\", ...input }, \"Bill could not be reopened.\"); },\n postPayment(input) { return action({ action: \"post_payment\", penaltyAmount: 0, interestAmount: 0, ...input, checkNumber: input.checkNumber ?? \"\" }, \"Payment could not be posted.\"); },\n submitSecondReview(input) { return action({ action: \"second_review\", ...input }, \"Second Review could not be submitted.\"); },\n resubmitBill(input) { return action({ action: \"resubmit\", ...input }, \"Bill could not be resubmitted.\"); },\n submitNewBill(input) { return action({ action: \"submit_new_bill\", ...input }, \"The new bill could not be submitted.\"); },\n sendDuplicateBill(input) { return action({ action: \"send_duplicate\", ...input }, \"Duplicate bill could not be sent.\"); },\n reportBillStatus(input) { return action({ action: \"report_bill_status\", ...input }, \"Bill status could not be reported.\"); },\n simulateSandbox,\n };\n}\n\n/**\n * Browser-safe client for reference data needed before a bill exists.\n *\n * Partners can pass the same short-lived session provider used by the submitted-bill\n * lifecycle without inventing a draft bill or exposing payer directory credentials.\n */\nexport function createBillReferenceClient(\n options: BillReferenceClientOptions = {},\n): BillReferenceClient {\n const lifecycle = createBillLifecycleClient({\n ...options,\n billId: \"pre-submission-reference-data\",\n });\n return {\n listClaimsAdministrators: lifecycle.listClaimsAdministrators,\n searchClaimsAdministrators: lifecycle.searchClaimsAdministrators,\n getClaimsAdministratorDirectory: lifecycle.getClaimsAdministratorDirectory,\n searchDiagnosisCodes: lifecycle.searchDiagnosisCodes,\n searchProcedureCodes: lifecycle.searchProcedureCodes,\n quoteFee: lifecycle.quoteFee,\n quoteClaimFees: lifecycle.quoteClaimFees,\n lookupPostalCode: lifecycle.lookupPostalCode,\n getDeliveryPreview: lifecycle.getDeliveryPreview,\n clearSession: lifecycle.clearSession,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Organization profile client (INC-1470): backs the embeddable\n// OrganizationOnboarding / BillingSettings components. Requires a browser\n// session minted with organization:manage for administrative operations.\n// Read-only saved billing profiles need only an org-wide bills:create session.\n\n/** Convert masked profile state to a write without clearing an unchanged saved SSN. */\nexport function organizationTaxIdWrite<T extends { taxId?: string; taxIdType?: \"EIN\" | \"SSN\"; taxIdLast4?: string; taxIdConfigured?: boolean }>(value: T): Omit<T, \"taxIdLast4\" | \"taxIdConfigured\"> {\n const input = { ...value };\n delete input.taxIdLast4;\n delete input.taxIdConfigured;\n if (value.taxIdType === \"SSN\" && value.taxIdConfigured && !value.taxId?.trim()) delete input.taxId;\n return input;\n}\n\nexport type OrganizationPracticeIdentity = {\n name?: string; legalName?: string; taxId?: string; npi?: string;\n taxIdType?: \"EIN\" | \"SSN\";\n /** Read-only metadata. Saved SSNs are never returned in taxId. */\n taxIdLast4?: string; taxIdConfigured?: boolean;\n phone?: string; email?: string; website?: string;\n};\n\nexport type OrganizationBillingProviderInput = {\n id?: string; externalId?: string; name: string; taxId?: string; npi: string;\n taxIdType?: \"EIN\" | \"SSN\";\n /** Read-only metadata; omit taxId on updates to preserve a saved SSN. */\n taxIdLast4?: string; taxIdConfigured?: boolean;\n billType?: \"Professional\" | \"Institutional\"; phone?: string;\n billingStreet?: string; billingCity?: string; billingState?: string; billingZip?: string;\n};\n\nexport type OrganizationLocationInput = {\n id?: string; externalId?: string; name: string; street: string; city: string;\n state: string; zip: string; nickname?: string; posCode?: string;\n isPrimary?: boolean; active?: boolean;\n};\n\nexport type OrganizationRenderingProviderInput = {\n id?: string; externalId?: string; name: string; npi: string; specialty?: string;\n taxonomy?: string; licenseNumber?: string; licenseState?: string;\n isQME?: boolean; isAME?: boolean; email?: string; active?: boolean;\n};\n\nexport type OrganizationChecklistItem = { id: string; label: string; complete: boolean };\n\nexport type OrganizationProfileData = {\n organizationId: string;\n practiceIdentity: OrganizationPracticeIdentity;\n billingProviders: Array<OrganizationBillingProviderInput & { id: string }>;\n /** Optional for compatibility with older organization-profile responses. */\n renderingProviders?: Array<OrganizationRenderingProviderInput & { id: string }>;\n locations: Array<OrganizationLocationInput & { id: string }>;\n w9: { filename: string; addDate: string; taxYear?: number } | null;\n onboarding: { status: string | null; complete: boolean; checklist: OrganizationChecklistItem[] };\n};\n\nexport type OrganizationClientOptions = {\n sessionEndpoint?: string;\n getSession?: BillLifecycleSessionProvider;\n apiBaseUrl?: string;\n fetch?: typeof globalThis.fetch;\n};\n\nexport type OrganizationTeamRole = \"admin\" | \"manager\" | \"biller\" | \"payments\" | \"viewer\";\nexport type OrganizationTeamMember = {\n id: string; email: string; name: string; role: string; active: boolean;\n createdAt: string; canManage: boolean;\n};\nexport type OrganizationTeam = {\n members: OrganizationTeamMember[];\n roles: Array<{ id: OrganizationTeamRole; label: string; permissions: string[] }>;\n capabilities: { canManage: boolean; canAdd: boolean };\n identityDomain: \"mindbill\";\n};\nexport type OrganizationClaimsAdministratorInput = {\n name: string; fax?: string; email?: string; mailingAddress?: string; notes?: string;\n};\nexport type OrganizationClaimsAdministrator = {\n id: string; name: string; fax: string | null; email: string | null;\n mailingAddress: string | null; notes: string | null; submissionMethod: string;\n active: boolean; createdAt: string;\n};\n\nexport type OrganizationClient = {\n /** Requires explicit team:manage; organization:manage alone does not grant team access. */\n getTeam: () => Promise<OrganizationTeam>;\n updateTeamMember: (id: string, input: { role?: OrganizationTeamRole; active?: boolean }) => Promise<OrganizationTeamMember>;\n getClaimsAdministrators: () => Promise<OrganizationClaimsAdministrator[]>;\n createClaimsAdministrator: (input: OrganizationClaimsAdministratorInput) => Promise<OrganizationClaimsAdministrator>;\n updateClaimsAdministrator: (id: string, input: OrganizationClaimsAdministratorInput) => Promise<OrganizationClaimsAdministrator>;\n deleteClaimsAdministrator: (id: string) => Promise<{ id: string; deleted: true }>;\n\n getOrganization: () => Promise<OrganizationProfileData>;\n /** Masked saved profiles for bill entry; requires org-wide bills:create. */\n getBillingProfile: () => Promise<OrganizationProfileData>;\n saveBillingProfile: (input: {\n practiceIdentity?: OrganizationPracticeIdentity;\n billingProviders?: OrganizationBillingProviderInput[];\n renderingProviders?: OrganizationRenderingProviderInput[];\n }) => Promise<OrganizationProfileData>;\n saveLocations: (locations: OrganizationLocationInput[]) => Promise<OrganizationProfileData>;\n saveW9: (input: { filename: string; contentBase64: string; taxYear?: number }) => Promise<OrganizationProfileData>;\n};\n\nexport function createOrganizationClient({\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: OrganizationClientOptions = {}): OrganizationClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n\n const mintSession = async (force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n const pending = getSession\n ? getSession({ signal: new AbortController().signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The organization session could not be created.\");\n return response.json();\n });\n session = normalizeSession(await Promise.resolve(pending));\n return session;\n };\n\n const request = async <T = OrganizationProfileData>(path: string, init: RequestInit = {}): Promise<T> => {\n let current = await mintSession();\n const perform = (active: BillLifecycleSession) => {\n const base = (active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n const headers = new Headers(init.headers);\n headers.set(\"authorization\", `Bearer ${active.token}`);\n if (init.body) headers.set(\"content-type\", \"application/json\");\n return fetcher(`${base}${path}`, { ...init, headers });\n };\n let response = await perform(current);\n if (response.status === 401) {\n current = await mintSession(true);\n response = await perform(current);\n }\n if (!response.ok) throw await responseError(response, \"The organization request failed.\");\n const body = (await response.json()) as { data?: T };\n if (!body.data || typeof body.data !== \"object\") {\n throw new Error(\"The organization response was invalid.\");\n }\n return body.data;\n };\n\n return {\n getTeam: () => request<OrganizationTeam>(\"/partner/v2/organization/team\"),\n updateTeamMember: (id, input) => request<OrganizationTeamMember>(`/partner/v2/organization/team/${encodeURIComponent(id)}`, { method: \"PATCH\", body: JSON.stringify(input) }),\n getClaimsAdministrators: () => request<OrganizationClaimsAdministrator[]>(\"/partner/v2/organization/claims-administrators\"),\n createClaimsAdministrator: (input) => request<OrganizationClaimsAdministrator>(\"/partner/v2/organization/claims-administrators\", { method: \"POST\", body: JSON.stringify(input) }),\n updateClaimsAdministrator: (id, input) => request<OrganizationClaimsAdministrator>(`/partner/v2/organization/claims-administrators/${encodeURIComponent(id)}`, { method: \"PATCH\", body: JSON.stringify(input) }),\n deleteClaimsAdministrator: (id) => request<{ id: string; deleted: true }>(`/partner/v2/organization/claims-administrators/${encodeURIComponent(id)}`, { method: \"DELETE\" }),\n getOrganization: () => request(\"/partner/v2/organization\"),\n getBillingProfile: () => request(\"/partner/v2/organization/billing-profile\"),\n saveBillingProfile: (input) =>\n request(\"/partner/v2/organization/billing-profile\", { method: \"PUT\", body: JSON.stringify({\n ...input,\n ...(input.practiceIdentity ? { practiceIdentity: organizationTaxIdWrite(input.practiceIdentity) } : {}),\n ...(input.billingProviders ? { billingProviders: input.billingProviders.map(organizationTaxIdWrite) } : {}),\n }) }),\n saveLocations: (locations) =>\n request(\"/partner/v2/organization/locations\", { method: \"PUT\", body: JSON.stringify({ locations }) }),\n saveW9: (input) =>\n request(\"/partner/v2/organization/w9\", { method: \"PUT\", body: JSON.stringify(input) }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Bill Tasks dashboard: a pure, framework-neutral\n// aggregation shared by the React and Angular components. Hosts flatten their\n// own work items and get back per-section rows bucketed by age in days.\n\nexport type BillTasksAgingBucket = {\n id: string;\n label: string;\n /** Exclusive lower bound in days. The first bucket also admits day 0. */\n minDays: number;\n /** Inclusive upper bound in days; null means unbounded. */\n maxDays: number | null;\n};\n\nexport const BILL_TASKS_AGING_BUCKETS: BillTasksAgingBucket[] = [\n { id: \"1-30\", label: \"1-30 Days Ago\", minDays: 0, maxDays: 30 },\n { id: \"31-60\", label: \"31-60 Days Ago\", minDays: 30, maxDays: 60 },\n { id: \"61-90\", label: \"61-90 Days Ago\", minDays: 60, maxDays: 90 },\n { id: \"91-180\", label: \"91-180 Days Ago\", minDays: 90, maxDays: 180 },\n { id: \"181+\", label: \"181+ Days Ago\", minDays: 180, maxDays: null },\n];\n\nexport type BillTasksDashboardItem = {\n sectionId: string;\n rowId: string;\n rowLabel: string;\n ageDays: number;\n balanceDue?: number;\n /** Opaque bill reference echoed back in click-through payloads. */\n ref?: string;\n};\n\nexport type BillTasksDashboardRow = {\n id: string;\n label: string;\n /** One count per aging bucket, in bucket order. */\n counts: number[];\n total: number;\n /** Summed item balanceDue per bucket; optional for older count-only payloads. */\n balances?: number[];\n balanceTotal?: number;\n /** Collected item refs per aging bucket, in bucket order. */\n refs: string[][];\n};\n\nexport type BillTasksDashboardTone = \"violet\" | \"red\" | \"blue\" | \"green\" | \"amber\" | \"neutral\";\n\nexport type BillTasksDashboardSectionInput = {\n id: string;\n label: string;\n /** Shown under the section label as \"by {agingBasisLabel}\". */\n agingBasisLabel: string;\n tone: BillTasksDashboardTone;\n};\n\nexport type BillTasksDashboardSection = BillTasksDashboardSectionInput & {\n rows: BillTasksDashboardRow[];\n /** Per-bucket totals across the section's rows. */\n totals: number[];\n total: number;\n balanceTotals?: number[];\n balanceTotal?: number;\n empty: boolean;\n};\n\nexport type BillTasksDashboardData = {\n sections: BillTasksDashboardSection[];\n grandTotals: number[];\n grandTotal: number;\n /** Work-item sums, not deduplicated financial A/R across task categories. */\n grandBalanceTotals?: number[];\n grandBalanceTotal?: number;\n};\n\n/**\n * Bucket index for an item age: a bucket admits `minDays < ageDays <= maxDays`\n * (`maxDays: null` = unbounded) and the first bucket also admits day 0.\n * Ages beyond every bucket clamp into the last bucket.\n */\nexport function billTasksAgingBucketIndex(\n ageDays: number,\n buckets: BillTasksAgingBucket[] = BILL_TASKS_AGING_BUCKETS,\n): number {\n const days = Math.max(0, Math.floor(ageDays));\n const index = buckets.findIndex((bucket, position) =>\n (bucket.maxDays === null || days <= bucket.maxDays)\n && (days > bucket.minDays || position === 0));\n return index === -1 ? buckets.length - 1 : index;\n}\n\n/**\n * Aggregates flat work items into the Bill Tasks dashboard.\n * Sections render in the given order even when empty; rows appear in\n * first-seen item order within their section.\n */\nexport function buildBillTasksDashboard(\n items: BillTasksDashboardItem[],\n sections: BillTasksDashboardSectionInput[],\n buckets: BillTasksAgingBucket[] = BILL_TASKS_AGING_BUCKETS,\n): BillTasksDashboardData {\n const zeros = () => buckets.map(() => 0);\n const built = sections.map((section): BillTasksDashboardSection => ({\n ...section,\n rows: [],\n totals: zeros(),\n total: 0,\n balanceTotals: zeros(),\n balanceTotal: 0,\n empty: true,\n }));\n const sectionById = new Map(built.map((section) => [section.id, section]));\n const rowByKey = new Map<string, BillTasksDashboardRow>();\n const grandTotals = zeros();\n let grandTotal = 0;\n const grandBalanceTotals = zeros();\n let grandBalanceTotal = 0;\n\n for (const item of items) {\n const section = sectionById.get(item.sectionId);\n if (!section) continue;\n const key = `${item.sectionId}\\u0000${item.rowId}`;\n let row = rowByKey.get(key);\n if (!row) {\n row = {\n id: item.rowId,\n label: item.rowLabel,\n counts: zeros(),\n total: 0,\n balances: zeros(),\n balanceTotal: 0,\n refs: buckets.map(() => []),\n };\n rowByKey.set(key, row);\n section.rows.push(row);\n section.empty = false;\n }\n const bucketIndex = billTasksAgingBucketIndex(item.ageDays, buckets);\n const balance = Number.isFinite(item.balanceDue) ? item.balanceDue! : 0;\n row.counts[bucketIndex] = (row.counts[bucketIndex] ?? 0) + 1;\n row.total += 1;\n row.balances![bucketIndex] = (row.balances![bucketIndex] ?? 0) + balance;\n row.balanceTotal = (row.balanceTotal ?? 0) + balance;\n if (item.ref) row.refs[bucketIndex]?.push(item.ref);\n section.totals[bucketIndex] = (section.totals[bucketIndex] ?? 0) + 1;\n section.total += 1;\n section.balanceTotals![bucketIndex] = (section.balanceTotals![bucketIndex] ?? 0) + balance;\n section.balanceTotal = (section.balanceTotal ?? 0) + balance;\n grandTotals[bucketIndex] = (grandTotals[bucketIndex] ?? 0) + 1;\n grandTotal += 1;\n grandBalanceTotals[bucketIndex] = (grandBalanceTotals[bucketIndex] ?? 0) + balance;\n grandBalanceTotal += balance;\n }\n\n return { sections: built, grandTotals, grandTotal, grandBalanceTotals, grandBalanceTotal };\n}\n\n\n/** An unsigned RFA preparation draft. Signing and sending are separate operations. */\nexport type RfaCreateDraftInput = {\n claimId: string; patientId: string; renderingProviderId: string; employeeName: string; providerName: string;\n externalId?: string; claimsAdminId?: string;\n requestType?: \"new\" | \"resubmission_material_change\" | \"oral_authorization_confirmation\";\n reviewType?: \"prospective\" | \"concurrent\" | \"retrospective\"; expedited?: boolean;\n placeOfServiceCode?: string; providerNpi?: string; providerPhone?: string; providerFax?: string;\n claimNumber?: string; dateOfInjury?: string; rationale?: string; materialChange?: string;\n items: Array<{ externalId?: string; diagnosisCode: string; serviceDescription: string; procedureCode?: string;\n quantity?: number; units?: number; frequency?: string; duration?: string; requestedFrom?: string; requestedTo?: string; metadata?: Record<string, unknown> }>;\n metadata?: Record<string, unknown>;\n};\n/** Full replacement of editable request content; retained service rows keep their IDs. */\nexport type RfaUpdateDraftInput = Omit<RfaCreateDraftInput, \"externalId\" | \"claimId\" | \"patientId\" | \"renderingProviderId\" | \"items\"> & {\n expectedRevision: number;\n items: Array<Omit<RfaCreateDraftInput[\"items\"][number], \"externalId\"> & { id?: string }>;\n};\nexport type RfaRecord = {\n contentRevision: number; id: string; claimId: string; patientId: string; renderingProviderId: string; claimsAdminId: string | null;\n employeeName: string; providerName: string; claimNumber: string | null; status: string;\n requestType?: RfaCreateDraftInput[\"requestType\"];\n placeOfServiceCode?: string | null; providerNpi?: string | null; providerPhone?: string | null; providerFax?: string | null;\n dateOfInjury?: string | null; rationale?: string | null; materialChange?: string | null; metadata?: Record<string, unknown>;\n reviewType: string; expedited: boolean; createdAt: string | null; updatedAt: string | null;\n signedAt: string | null; submittedAt: string | null; receivedAt: string | null;\n decisionDueAt: string | null; decisionDeadlineBasis: string | null;\n incompleteReason: string | null; deferredReason: string | null; closedReason: string | null;\n readiness: { ready: boolean; missing: string[] };\n items: Array<{ id: string; diagnosisCode: string; serviceDescription: string; procedureCode: string | null;\n frequency?: string | null; duration?: string | null; requestedFrom?: string | null; requestedTo?: string | null; metadata?: Record<string, unknown>;\n outcome: string; quantity: number | null; units: number | null; authorizationNumber: string | null; decisionReason: string | null }>;\n documents: Array<{ id: string; documentType: string; filename: string; contentUrl: string; contentRevision: number | null; createdAt: string | null }>;\n transmissions: Array<{ id: string; purpose?: string; direction: string; channel: string; status: string; destination: string | null;\n occurredAt: string | null; receivedAt: string | null; proofDocumentId: string | null; providerMessageId: string | null }>;\n informationRequests: Array<{ id: string; requestText: string; requestedAt: string | null; dueAt: string | null; respondedAt: string | null }>;\n events: Array<{ id: string; type: string; occurredAt: string | null }>;\n};\nexport type RfaListQuery = { claimId?: string; renderingProviderId?: string; status?: string; createdFrom?: string; createdTo?: string; limit?: number; cursor?: string };\nexport type RfaListResult = { data: RfaRecord[]; nextCursor: string | null; summary: { total: number; byStatus: Record<string, number> } };\nexport type RfaSigningPreviewInput = { billingProviderId?: string; diagnosisDescriptions: Record<string, string> };\nexport type RfaSigningPreview = { id: string; contentHash: string; contentRevision: number; renderingProviderId: string; previewDocumentId: string; expiresAt: string };\nexport type RfaSignInput = { snapshotId: string; contentHash: string; renderingProviderId: string; physicianAuthorized: true; actorReference: string };\nexport type RfaFaxInput = { to: string; documentIds: string[]; nonBusinessDates?: string[] };\nexport type RfaUploadDocumentInput = { file: File; documentType: \"clinical_report\" | \"supporting_record\" | \"ur_response\" | \"imr_form\" | \"other\"; contentRevision: number };\nexport type RfaCreationClaim = { claimId: string; patientId: string; employeeName: string; claimNumber?: string; dateOfInjury?: string; claimsAdminId?: string };\nexport type RfaCreationProvider = { id: string; name: string; npi?: string };\nexport type RfaCreationContext = { claims: RfaCreationClaim[]; renderingProviders: RfaCreationProvider[]; nextCursor: string | null; renderingProvidersNextCursor: string | null };\nexport type RfaCreationContextQuery = { search?: string; cursor?: string; providerSearch?: string; providerCursor?: string; limit?: number; claimId?: string; renderingProviderId?: string };\nexport type RfaClient = {\n getCreationContext: (query?: RfaCreationContextQuery) => Promise<RfaCreationContext>;\n list: (query?: RfaListQuery) => Promise<RfaListResult>;\n get: (rfaId: string) => Promise<RfaRecord>;\n createDraft: (draft: RfaCreateDraftInput, idempotencyKey: string) => Promise<RfaRecord>;\n updateDraft: (rfaId: string, draft: RfaUpdateDraftInput, idempotencyKey: string) => Promise<RfaRecord>;\n getDocument: (rfaId: string, documentId: string) => Promise<Blob>;\n uploadDocument: (rfaId: string, input: RfaUploadDocumentInput, idempotencyKey: string) => Promise<RfaRecord>;\n prepareSigning: (rfaId: string, input: RfaSigningPreviewInput, idempotencyKey: string) => Promise<RfaSigningPreview>;\n sign: (rfaId: string, input: RfaSignInput, idempotencyKey: string) => Promise<RfaRecord>;\n previewPacket: (rfaId: string, documentIds: string[]) => Promise<Blob>;\n sendFax: (rfaId: string, input: RfaFaxInput, idempotencyKey: string) => Promise<RfaRecord>;\n refreshFaxes: (rfaId: string, idempotencyKey: string) => Promise<RfaRecord>;\n};\n/** Uses short-lived browser credentials. Never pass a partner API key. */\nexport function createRfaClient({ sessionEndpoint = DEFAULT_SESSION_ENDPOINT, getSession, apiBaseUrl = DEFAULT_API_BASE_URL, fetch: fetchOverride }: OrganizationClientOptions = {}): RfaClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n let session: BillLifecycleSession | null = null;\n let pending: Promise<BillLifecycleSession> | null = null;\n const mint = (force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return Promise.resolve(session as BillLifecycleSession);\n if (pending) return pending;\n pending = (async () => {\n const value = getSession ? await getSession({ signal: new AbortController().signal }) : await (async () => {\n const response = await fetcher(sessionEndpoint, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: \"{}\" });\n if (!response.ok) throw await responseError(response, \"The RFA session could not be created.\");\n return response.json();\n })();\n session = normalizeSession(value); return session;\n })().finally(() => { pending = null; });\n return pending;\n };\n const request = async (path: string, init: RequestInit = {}, browser = false) => {\n const perform = (active: BillLifecycleSession) => {\n const headers = new Headers(init.headers); headers.set(\"authorization\", `Bearer ${active.token}`);\n if (init.body && !(init.body instanceof FormData)) headers.set(\"content-type\", \"application/json\");\n return fetcher(`${(active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\")}/partner/v2/${browser ? \"browser/\" : \"\"}rfas${path}`, { ...init, headers });\n };\n let response = await perform(await mint());\n if (response.status === 401) response = await perform(await mint(true));\n if (!response.ok) throw await responseError(response, \"The RFA request failed.\");\n return response;\n };\n const record = async (path: string, init?: RequestInit): Promise<RfaRecord> => {\n const body = await (await request(path, init)).json() as { data?: RfaRecord };\n if (!body.data?.id) throw new Error(\"The RFA response was invalid.\");\n return body.data;\n };\n const mutation = (body: unknown, key: string): RequestInit => {\n if (!key.trim()) throw new Error(\"An idempotency key is required.\");\n return { method: \"POST\", headers: { \"idempotency-key\": key }, body: JSON.stringify(body) };\n };\n const path = (id: string, suffix: string) => `/${encodeURIComponent(id)}/${suffix}`;\n return {\n getCreationContext: async (query = {}) => {\n const params = new URLSearchParams();\n for (const [name, value] of Object.entries(query)) if (value !== undefined && value !== \"\") params.set(name, String(value));\n const body = await (await request(`/creation-context${params.size ? `?${params}` : \"\"}`, {}, true)).json() as { data?: RfaCreationContext };\n if (!Array.isArray(body.data?.claims) || !Array.isArray(body.data?.renderingProviders)) throw new Error(\"The RFA creation context was invalid.\");\n return body.data;\n },\n list: async (query = {}) => {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) if (value !== undefined && value !== \"\") params.set(key, String(value));\n const body = await (await request(params.size ? `?${params}` : \"\")).json() as RfaListResult;\n if (!Array.isArray(body.data) || !body.summary) throw new Error(\"The RFA list response was invalid.\");\n return body;\n },\n get: (id) => record(`/${encodeURIComponent(id)}`),\n createDraft: (draft, idempotencyKey) => {\n if (!idempotencyKey.trim()) return Promise.reject(new Error(\"An idempotency key is required.\"));\n const unsigned = { ...draft } as RfaCreateDraftInput & { signedAt?: unknown }; delete unsigned.signedAt;\n unsigned.items = draft.items.map(item => { const copy = { ...item } as typeof item & { id?: unknown }; delete copy.id; return copy; });\n return record(\"\", { method: \"POST\", headers: { \"idempotency-key\": idempotencyKey }, body: JSON.stringify(unsigned) });\n },\n updateDraft: (id, draft, key) => {\n if (!Number.isInteger(draft.expectedRevision) || draft.expectedRevision < 1) return Promise.reject(new Error(\"A positive expected content revision is required.\"));\n const body = { ...draft } as RfaUpdateDraftInput & Record<string, unknown>;\n for (const field of [\"externalId\", \"claimId\", \"patientId\", \"renderingProviderId\", \"signedAt\"]) delete body[field];\n body.items = draft.items.map(item => { const copy = { ...item } as typeof item & { externalId?: unknown }; delete copy.externalId; return copy; });\n return record(path(id, \"draft\"), { ...mutation(body, key), method: \"PATCH\" });\n },\n uploadDocument: (id, input, key) => {\n if (!key.trim()) return Promise.reject(new Error(\"An idempotency key is required.\"));\n if (input.file.size < 1 || input.file.size > 25 * 1024 * 1024) return Promise.reject(new Error(\"Choose a PDF up to 25 MB.\"));\n const body = new FormData(); body.set(\"file\", input.file); body.set(\"documentType\", input.documentType); body.set(\"contentRevision\", String(input.contentRevision));\n return record(path(id, \"documents\"), { method: \"POST\", headers: { \"idempotency-key\": key }, body });\n },\n prepareSigning: async (id, input, key) => {\n const body = await (await request(path(id, \"signing-preview\"), mutation(input, key))).json() as { data: RfaSigningPreview };\n if (!body.data?.id || !body.data.contentHash || !body.data.previewDocumentId) throw new Error(\"The signing preview was invalid.\");\n return body.data;\n },\n sign: (id, input, key) => {\n if (input.physicianAuthorized !== true || !input.actorReference.trim()) return Promise.reject(new Error(\"Physician authorization and signer identity are required.\"));\n return record(path(id, \"sign\"), mutation(input, key));\n },\n previewPacket: async (id, documentIds) => (await request(path(id, \"packet\"), { method: \"POST\", body: JSON.stringify({ documentIds }) })).blob(),\n sendFax: (id, input, key) => record(path(id, \"fax\"), mutation(input, key)),\n refreshFaxes: (id, key) => record(path(id, \"fax/refresh\"), mutation({}, key)),\n getDocument: async (id, documentId) => (await request(`/${encodeURIComponent(id)}/documents/${encodeURIComponent(documentId)}`)).blob(),\n };\n}\n\nexport * from \"./rfa-lifecycle\";\nexport { createReportAutofillClient } from \"./report-autofill\";\nexport type { ReportAutofillClient, ReportAutofillField, ReportAutofillMatch, ReportAutofillResult } from \"./report-autofill\";\n"],"mappings":";AAqDA,IAAM,SAAS,CAAC,MAA6C,CAAC,CAAC,KAAK,OAAO,MAAM,YAAY,CAAC,MAAM,QAAQ,CAAC;AAC7G,IAAM,UAAU,CAAC,MAA8B,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,OAAO,MAAM,QAAQ;AACvG,IAAM,QAAQ,CAAC,MAAe,OAAO,cAAc,CAAC,KAAM,KAAgB;AAC1E,IAAM,SAAS,CAAC,MAAe,CAAC,UAAU,mBAAmB,wBAAwB,EAAE,SAAS,CAAW;AAC3G,IAAM,UAAU,CAAC,MAAe,OAAO,CAAC,KAAK,OAAO,EAAE,YAAY,YAAY,QAAQ,EAAE,OAAO,MAAM,EAAE,gBAAgB,UAAa,OAAO,EAAE,gBAAgB;AAEtJ,SAAS,qBAAqB,OAAgB,OAAoD;AACvG,QAAM,UAAU,MAAM;AAAE,UAAM,IAAI,MAAM,+CAA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