@mindbill/browser 0.27.0 → 0.28.0
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 +27 -2
- package/dist/index.js +16 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -4,6 +4,9 @@ type BillReviewDocumentType = "final_report" | "letter_of_attestation" | "proof_
|
|
|
4
4
|
type BillReviewBillingProvider = {
|
|
5
5
|
name: string;
|
|
6
6
|
taxId: string;
|
|
7
|
+
taxIdType?: "EIN" | "SSN";
|
|
8
|
+
taxIdConfigured?: boolean;
|
|
9
|
+
taxIdLast4?: string;
|
|
7
10
|
npi: string;
|
|
8
11
|
billType: "Professional" | "Institutional";
|
|
9
12
|
phone?: string;
|
|
@@ -713,9 +716,14 @@ type BrowserBillCreateInput = {
|
|
|
713
716
|
billingProvider: {
|
|
714
717
|
name: string;
|
|
715
718
|
taxId: string;
|
|
719
|
+
taxIdType?: "EIN" | "SSN";
|
|
716
720
|
npi: string;
|
|
717
721
|
phone: string;
|
|
718
722
|
address: BrowserBillAddress;
|
|
723
|
+
} | {
|
|
724
|
+
savedProviderId: string;
|
|
725
|
+
} | {
|
|
726
|
+
sourceBillId: string;
|
|
719
727
|
};
|
|
720
728
|
renderingProvider: {
|
|
721
729
|
name: string;
|
|
@@ -855,11 +863,22 @@ declare function createBillLifecycleClient({ billId, sessionEndpoint, getSession
|
|
|
855
863
|
* lifecycle without inventing a draft bill or exposing payer directory credentials.
|
|
856
864
|
*/
|
|
857
865
|
declare function createBillReferenceClient(options?: BillReferenceClientOptions): BillReferenceClient;
|
|
866
|
+
/** Convert masked profile state to a write without clearing an unchanged saved SSN. */
|
|
867
|
+
declare function organizationTaxIdWrite<T extends {
|
|
868
|
+
taxId?: string;
|
|
869
|
+
taxIdType?: "EIN" | "SSN";
|
|
870
|
+
taxIdLast4?: string;
|
|
871
|
+
taxIdConfigured?: boolean;
|
|
872
|
+
}>(value: T): Omit<T, "taxIdLast4" | "taxIdConfigured">;
|
|
858
873
|
type OrganizationPracticeIdentity = {
|
|
859
874
|
name?: string;
|
|
860
875
|
legalName?: string;
|
|
861
876
|
taxId?: string;
|
|
862
877
|
npi?: string;
|
|
878
|
+
taxIdType?: "EIN" | "SSN";
|
|
879
|
+
/** Read-only metadata. Saved SSNs are never returned in taxId. */
|
|
880
|
+
taxIdLast4?: string;
|
|
881
|
+
taxIdConfigured?: boolean;
|
|
863
882
|
phone?: string;
|
|
864
883
|
email?: string;
|
|
865
884
|
website?: string;
|
|
@@ -868,8 +887,12 @@ type OrganizationBillingProviderInput = {
|
|
|
868
887
|
id?: string;
|
|
869
888
|
externalId?: string;
|
|
870
889
|
name: string;
|
|
871
|
-
taxId
|
|
890
|
+
taxId?: string;
|
|
872
891
|
npi: string;
|
|
892
|
+
taxIdType?: "EIN" | "SSN";
|
|
893
|
+
/** Read-only metadata; omit taxId on updates to preserve a saved SSN. */
|
|
894
|
+
taxIdLast4?: string;
|
|
895
|
+
taxIdConfigured?: boolean;
|
|
873
896
|
billType?: "Professional" | "Institutional";
|
|
874
897
|
phone?: string;
|
|
875
898
|
billingStreet?: string;
|
|
@@ -941,6 +964,8 @@ type OrganizationClientOptions = {
|
|
|
941
964
|
};
|
|
942
965
|
type OrganizationClient = {
|
|
943
966
|
getOrganization: () => Promise<OrganizationProfileData>;
|
|
967
|
+
/** Masked saved profiles for bill entry; requires org-wide bills:create. */
|
|
968
|
+
getBillingProfile: () => Promise<OrganizationProfileData>;
|
|
944
969
|
saveBillingProfile: (input: {
|
|
945
970
|
practiceIdentity?: OrganizationPracticeIdentity;
|
|
946
971
|
billingProviders?: OrganizationBillingProviderInput[];
|
|
@@ -1022,4 +1047,4 @@ declare function billTasksAgingBucketIndex(ageDays: number, buckets?: BillTasksA
|
|
|
1022
1047
|
*/
|
|
1023
1048
|
declare function buildBillTasksDashboard(items: BillTasksDashboardItem[], sections: BillTasksDashboardSectionInput[], buckets?: BillTasksAgingBucket[]): BillTasksDashboardData;
|
|
1024
1049
|
|
|
1025
|
-
export { type AddBillNoteInput, BILL_TASKS_AGING_BUCKETS, type BillActivityRecord, type BillActorInput, type BillAttemptSummary, type BillClaimsAdministratorContact, type BillClaimsAdministratorDirectory, type BillClaimsAdministratorMailingAddress, type BillClaimsAdministratorPattern, type BillClaimsAdministratorPayer, type BillClaimsAdministratorSource, type BillDeliveryOption, type BillDeliveryOptions, type BillDeliveryPreviewInput, type BillDiagnosisCode, type BillEorDocument, 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 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 BillSubmissionRoute, type BillTasksAgingBucket, type BillTasksDashboardData, type BillTasksDashboardItem, type BillTasksDashboardRow, type BillTasksDashboardSection, type BillTasksDashboardSectionInput, type BillTasksDashboardTone, type BrowserBillAddress, type BrowserBillCreateInput, type BrowserBillSubmissionDocument, type BrowserBillSubmissionInput, type BrowserBillSubmissionResult, type BrowserSubmittedBill, type CloseBillInput, DEFAULT_API_BASE_URL, DEFAULT_SESSION_ENDPOINT, type OrganizationBillingProviderInput, type OrganizationChecklistItem, type OrganizationClient, type OrganizationClientOptions, type OrganizationLocationInput, type OrganizationPracticeIdentity, type OrganizationProfileData, type OrganizationRenderingProviderInput, type PostBillPaymentInput, REPORT_BILL_STATUS_OPTIONS, type ReopenBillInput, type ReportBillStatusActionInput, type ReportBillStatusContacts, type ReportBillStatusId, type ReportBillStatusInput, type ReportBillStatusOption, type ResubmitBillInput, 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, defaultBillReviewPayerOption, reportBillStatusContacts, sanitizeBillReviewSaveInput, secondReviewDeadline };
|
|
1050
|
+
export { type AddBillNoteInput, BILL_TASKS_AGING_BUCKETS, type BillActivityRecord, type BillActorInput, type BillAttemptSummary, type BillClaimsAdministratorContact, type BillClaimsAdministratorDirectory, type BillClaimsAdministratorMailingAddress, type BillClaimsAdministratorPattern, type BillClaimsAdministratorPayer, type BillClaimsAdministratorSource, type BillDeliveryOption, type BillDeliveryOptions, type BillDeliveryPreviewInput, type BillDiagnosisCode, type BillEorDocument, 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 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 BillSubmissionRoute, type BillTasksAgingBucket, type BillTasksDashboardData, type BillTasksDashboardItem, type BillTasksDashboardRow, type BillTasksDashboardSection, type BillTasksDashboardSectionInput, type BillTasksDashboardTone, type BrowserBillAddress, type BrowserBillCreateInput, type BrowserBillSubmissionDocument, type BrowserBillSubmissionInput, type BrowserBillSubmissionResult, type BrowserSubmittedBill, type CloseBillInput, DEFAULT_API_BASE_URL, DEFAULT_SESSION_ENDPOINT, type OrganizationBillingProviderInput, type OrganizationChecklistItem, type OrganizationClient, type OrganizationClientOptions, type OrganizationLocationInput, type OrganizationPracticeIdentity, type OrganizationProfileData, type OrganizationRenderingProviderInput, type PostBillPaymentInput, REPORT_BILL_STATUS_OPTIONS, type ReopenBillInput, type ReportBillStatusActionInput, type ReportBillStatusContacts, type ReportBillStatusId, type ReportBillStatusInput, type ReportBillStatusOption, type ResubmitBillInput, 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, defaultBillReviewPayerOption, organizationTaxIdWrite, reportBillStatusContacts, sanitizeBillReviewSaveInput, secondReviewDeadline };
|
package/dist/index.js
CHANGED
|
@@ -40,6 +40,8 @@ function sanitizeBillReviewSaveInput(input) {
|
|
|
40
40
|
billingProvider: pickDefined(input.billingProvider, [
|
|
41
41
|
"name",
|
|
42
42
|
"taxId",
|
|
43
|
+
"taxIdType",
|
|
44
|
+
"taxIdConfigured",
|
|
43
45
|
"npi",
|
|
44
46
|
"billType",
|
|
45
47
|
"phone",
|
|
@@ -585,6 +587,13 @@ function createBillReferenceClient(options = {}) {
|
|
|
585
587
|
clearSession: lifecycle.clearSession
|
|
586
588
|
};
|
|
587
589
|
}
|
|
590
|
+
function organizationTaxIdWrite(value) {
|
|
591
|
+
const input = { ...value };
|
|
592
|
+
delete input.taxIdLast4;
|
|
593
|
+
delete input.taxIdConfigured;
|
|
594
|
+
if (value.taxIdType === "SSN" && value.taxIdConfigured && !value.taxId?.trim()) delete input.taxId;
|
|
595
|
+
return input;
|
|
596
|
+
}
|
|
588
597
|
function createOrganizationClient({
|
|
589
598
|
sessionEndpoint = DEFAULT_SESSION_ENDPOINT,
|
|
590
599
|
getSession,
|
|
@@ -631,7 +640,12 @@ function createOrganizationClient({
|
|
|
631
640
|
};
|
|
632
641
|
return {
|
|
633
642
|
getOrganization: () => request("/partner/v2/browser/organization"),
|
|
634
|
-
|
|
643
|
+
getBillingProfile: () => request("/partner/v2/browser/organization/billing-profile"),
|
|
644
|
+
saveBillingProfile: (input) => request("/partner/v2/browser/organization/billing-profile", { method: "PUT", body: JSON.stringify({
|
|
645
|
+
...input,
|
|
646
|
+
...input.practiceIdentity ? { practiceIdentity: organizationTaxIdWrite(input.practiceIdentity) } : {},
|
|
647
|
+
...input.billingProviders ? { billingProviders: input.billingProviders.map(organizationTaxIdWrite) } : {}
|
|
648
|
+
}) }),
|
|
635
649
|
saveLocations: (locations) => request("/partner/v2/browser/organization/locations", { method: "PUT", body: JSON.stringify({ locations }) }),
|
|
636
650
|
saveW9: (input) => request("/partner/v2/browser/organization/w9", { method: "PUT", body: JSON.stringify(input) })
|
|
637
651
|
};
|
|
@@ -716,6 +730,7 @@ export {
|
|
|
716
730
|
createBillSubmissionClient,
|
|
717
731
|
createOrganizationClient,
|
|
718
732
|
defaultBillReviewPayerOption,
|
|
733
|
+
organizationTaxIdWrite,
|
|
719
734
|
reportBillStatusContacts,
|
|
720
735
|
sanitizeBillReviewSaveInput,
|
|
721
736
|
secondReviewDeadline
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export const DEFAULT_API_BASE_URL = \"https://app.mindbill.org\";\nexport const DEFAULT_SESSION_ENDPOINT = \"/api/mindbill/session\";\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 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 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 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 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\", \"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 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 BillClaimsAdministratorDirectory = {\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 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 /** Immutable submissions that share this bill's unified history. */\n attempts?: BillAttemptSummary[];\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};\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: { name: string; taxId: string; npi: string; phone: string; address: BrowserBillAddress };\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 }>;\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 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 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 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 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 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 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/browser/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/browser/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/browser/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/browser/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/browser/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 lookupPostalCode = async (postalCode: string): Promise<BillPostalPlace | null> => {\n const params = new URLSearchParams({ postalCode: postalCode.trim() });\n const response = await request(`/partner/v2/browser/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 const response = await mutation(billPath(\"/simulate\"), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, \"Sandbox lifecycle could not be simulated.\");\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\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 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/browser/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 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 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 the OPTIONAL organization:manage permission; sessions\n// without it are rejected by the API and nothing else changes.\n\nexport type OrganizationPracticeIdentity = {\n name?: string; legalName?: string; taxId?: string; npi?: string;\n phone?: string; email?: string; website?: string;\n};\n\nexport type OrganizationBillingProviderInput = {\n id?: string; externalId?: string; name: string; taxId: string; npi: string;\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 OrganizationClient = {\n getOrganization: () => 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 (path: string, init: RequestInit = {}): Promise<OrganizationProfileData> => {\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?: OrganizationProfileData };\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 getOrganization: () => request(\"/partner/v2/browser/organization\"),\n saveBillingProfile: (input) =>\n request(\"/partner/v2/browser/organization/billing-profile\", { method: \"PUT\", body: JSON.stringify(input) }),\n saveLocations: (locations) =>\n request(\"/partner/v2/browser/organization/locations\", { method: \"PUT\", body: JSON.stringify({ locations }) }),\n saveW9: (input) =>\n request(\"/partner/v2/browser/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"],"mappings":";AAAO,IAAM,uBAAuB;AAC7B,IAAM,2BAA2B;AA+IjC,SAAS,6BACd,OAC8B;AAC9B,MAAI,CAAC,MAAM,uBAAwB,QAAO;AAC1C,SAAO,MAAM,QAAQ,KAAK,CAAC,WAAW,OAAO,OAAO,KAAK;AAC3D;AA4GA,SAAS,YACP,QACA,MACyB;AACzB,QAAM,SAAS;AACf,SAAO,OAAO;AAAA,IACZ,KAAK,QAAQ,CAAC,QAAQ,OAAO,GAAG,MAAM,SAAY,CAAC,IAAI,CAAC,CAAC,KAAK,OAAO,GAAG,CAAC,CAAC,CAAC;AAAA,EAC7E;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AAmB,WAAW,KAAK,KAAK;AAC3E,yBAAqB;AAAA,EACvB;AAEA,SAAO,EAAE,UAAU,OAAO,aAAa,YAAY,oBAAoB,kBAAkB;AAC3F;","names":["request","value"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export const DEFAULT_API_BASE_URL = \"https://app.mindbill.org\";\nexport const DEFAULT_SESSION_ENDPOINT = \"/api/mindbill/session\";\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 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 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 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 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 BillClaimsAdministratorDirectory = {\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 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 /** Immutable submissions that share this bill's unified history. */\n attempts?: BillAttemptSummary[];\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};\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: { 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 }>;\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 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 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 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 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 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 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/browser/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/browser/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/browser/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/browser/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/browser/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 lookupPostalCode = async (postalCode: string): Promise<BillPostalPlace | null> => {\n const params = new URLSearchParams({ postalCode: postalCode.trim() });\n const response = await request(`/partner/v2/browser/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 const response = await mutation(billPath(\"/simulate\"), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, \"Sandbox lifecycle could not be simulated.\");\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\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 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/browser/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 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 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 OrganizationClient = {\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 (path: string, init: RequestInit = {}): Promise<OrganizationProfileData> => {\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?: OrganizationProfileData };\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 getOrganization: () => request(\"/partner/v2/browser/organization\"),\n getBillingProfile: () => request(\"/partner/v2/browser/organization/billing-profile\"),\n saveBillingProfile: (input) =>\n request(\"/partner/v2/browser/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/browser/organization/locations\", { method: \"PUT\", body: JSON.stringify({ locations }) }),\n saveW9: (input) =>\n request(\"/partner/v2/browser/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"],"mappings":";AAAO,IAAM,uBAAuB;AAC7B,IAAM,2BAA2B;AAkJjC,SAAS,6BACd,OAC8B;AAC9B,MAAI,CAAC,MAAM,uBAAwB,QAAO;AAC1C,SAAO,MAAM,QAAQ,KAAK,CAAC,WAAW,OAAO,OAAO,KAAK;AAC3D;AA4GA,SAAS,YACP,QACA,MACyB;AACzB,QAAM,SAAS;AACf,SAAO,OAAO;AAAA,IACZ,KAAK,QAAQ,CAAC,QAAQ,OAAO,GAAG,MAAM,SAAY,CAAC,IAAI,CAAC,CAAC,KAAK,OAAO,GAAG,CAAC,CAAC,CAAC;AAAA,EAC7E;AACF;AAOO,SAAS,4BACd,OACqB;AACrB,SAAO;AAAA,IACL,eAAe,MAAM;AAAA,IACrB,GAAI,MAAM,YAAY,SAA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