@mindbill/browser 0.29.1 → 0.31.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 CHANGED
@@ -1,5 +1,15 @@
1
+ type CorrectionDraft = {
2
+ correctBilling: boolean;
3
+ units: string;
4
+ modifiers: string;
5
+ charge: string;
6
+ chargeReviewed: boolean;
7
+ };
8
+ declare function parseSecondReviewCorrection(draft: CorrectionDraft): SecondReviewLineInput["correction"];
9
+
1
10
  declare const DEFAULT_API_BASE_URL = "https://app.mindbill.org";
2
11
  declare const DEFAULT_SESSION_ENDPOINT = "/api/mindbill/session";
12
+
3
13
  type BillReviewDocumentType = "final_report" | "letter_of_attestation" | "proof_of_service" | "form_122" | "return_to_work_voucher" | "w9" | "medical_records" | "appeal" | "other";
4
14
  type BillReviewBillingProvider = {
5
15
  name: string;
@@ -540,6 +550,13 @@ type BillSubmissionDetail = {
540
550
  source: "submission_snapshot" | "bill_record" | "unavailable";
541
551
  capturedAt?: string | null;
542
552
  detail: HistoricalBillReviewData | null;
553
+ /** Exact retained files for this attempt; never regenerated from current bill values. */
554
+ artifacts?: Array<{
555
+ id: string;
556
+ label: string;
557
+ kind: "submitted_attachment" | "submitted_edi";
558
+ contentType: string;
559
+ }>;
543
560
  };
544
561
  type BillLifecycleData = BillReviewData & {
545
562
  environment: "sandbox" | "live";
@@ -802,6 +819,8 @@ type BrowserBillCreateInput = {
802
819
  serviceDate?: string;
803
820
  serviceDateEnd?: string | null;
804
821
  diagnosisPointers?: number[];
822
+ /** Existing authorized RFA item linked to this service line. */
823
+ rfaItemId?: string;
805
824
  }>;
806
825
  };
807
826
  /** Canonical immutable PDF snapshot sent with a bill submission. */
@@ -861,11 +880,104 @@ type BillDeliveryPreviewInput = {
861
880
  /** Two-letter state; defaults to CA server-side. */
862
881
  injuryState?: string;
863
882
  };
883
+ type BillProcedureCodeSearchInput = {
884
+ query?: string;
885
+ limit?: number;
886
+ jurisdiction?: "CA" | "NY" | "OWCP";
887
+ };
888
+ /** Catalog membership does not imply that a fee is available for a service date. */
889
+ type BillProcedureCodePage = {
890
+ results: Array<{
891
+ code: string;
892
+ }>;
893
+ total: number;
894
+ limit: number;
895
+ jurisdiction: "CA" | "NY" | "OWCP";
896
+ catalogAsOf: string | null;
897
+ };
898
+ type BillFeeSource = {
899
+ id: string;
900
+ url: string;
901
+ sha256?: string;
902
+ effectiveFrom: string;
903
+ effectiveThrough: string;
904
+ };
905
+ type BillFeeQuoteInput = {
906
+ code: string;
907
+ dateOfService: string;
908
+ chargeCents?: number;
909
+ units?: number;
910
+ modifiers?: string[];
911
+ pages?: number;
912
+ reportKind?: "progress" | "permanent_stationary_pr3" | "permanent_stationary_pr4";
913
+ hasFeeAgreement?: boolean;
914
+ serviceZip?: string;
915
+ /** Supply verified service facts; omitted context can require review. */
916
+ physicianContext?: {
917
+ providerKind: "physician" | "physician_assistant" | "nurse_practitioner" | "clinical_nurse_specialist" | "other";
918
+ incidentToPhysicianService?: boolean;
919
+ placeOfService: string;
920
+ standaloneService: boolean;
921
+ globalPeriodApplies: boolean;
922
+ hpsaBonusEligible: boolean;
923
+ };
924
+ therapyContext?: {
925
+ providerKind: "physical_therapist" | "other";
926
+ personallyPerformed: boolean;
927
+ hospitalPatient: boolean;
928
+ incidentToPhysicianService: boolean;
929
+ assistantInvolved: boolean;
930
+ placeOfService: string;
931
+ directOneOnOneMinutes: number;
932
+ totalVisitMinutes: number;
933
+ visitsOnDate: number;
934
+ completeSameDayServices: boolean;
935
+ otherSameDayServices: boolean;
936
+ globalPeriodApplies: boolean;
937
+ hpsaBonusEligible: boolean;
938
+ };
939
+ reportQualification?: {
940
+ kind: "psychiatric_report";
941
+ requestedBy: "wcab" | "administrative_director";
942
+ medicalLegalEvaluation: boolean;
943
+ reportPayableUnderMedicalLegalSchedule: boolean;
944
+ } | {
945
+ kind: "consultation_report";
946
+ requestedBy: "wcab" | "administrative_director" | "qme" | "ame";
947
+ medicalLegalEvaluation: boolean;
948
+ reportPayableUnderMedicalLegalSchedule: boolean;
949
+ } | {
950
+ kind: "chart_notes";
951
+ requestedBy: "claims_administrator";
952
+ writtenRequest: boolean;
953
+ } | {
954
+ kind: "duplicate_report";
955
+ requestedBy: "claims_administrator";
956
+ writtenRequest: boolean;
957
+ relatedToBilling: boolean;
958
+ initialRequiredCopy: boolean;
959
+ };
960
+ };
961
+ type BillFeeQuote = {
962
+ status: "priced";
963
+ /** Total for the service line in cents, already accounting for units. */
964
+ amountCents: number;
965
+ scheduleMaximumCents: number;
966
+ basis: "ca_report" | "ca_physician_rbrvs" | "ca_therapy_rbrvs";
967
+ provenance: BillFeeSource[];
968
+ notes: string[];
969
+ } | {
970
+ status: "requires_review" | "not_separately_payable";
971
+ reason: string;
972
+ provenance: BillFeeSource[];
973
+ };
864
974
  type BillReferenceClient = {
865
975
  listClaimsAdministrators: (input?: BillReviewPayerListInput) => Promise<BillReviewPayerPage>;
866
976
  searchClaimsAdministrators: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;
867
977
  getClaimsAdministratorDirectory: (id: string, injuryState?: string) => Promise<BillClaimsAdministratorDirectory>;
868
978
  searchDiagnosisCodes: (query: string, limit?: number, offset?: number) => Promise<BillDiagnosisCode[]>;
979
+ searchProcedureCodes: (input?: BillProcedureCodeSearchInput) => Promise<BillProcedureCodePage>;
980
+ quoteFee: (input: BillFeeQuoteInput) => Promise<BillFeeQuote>;
869
981
  lookupPostalCode: (postalCode: string) => Promise<BillPostalPlace | null>;
870
982
  /**
871
983
  * Delivery-route preview (recommended route + selectable options + payer
@@ -882,12 +994,17 @@ type BillLifecycleClient = {
882
994
  searchClaimsAdministrators: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;
883
995
  getClaimsAdministratorDirectory: (id: string, injuryState?: string) => Promise<BillClaimsAdministratorDirectory>;
884
996
  searchDiagnosisCodes: (query: string, limit?: number, offset?: number) => Promise<BillDiagnosisCode[]>;
997
+ searchProcedureCodes: (input?: BillProcedureCodeSearchInput) => Promise<BillProcedureCodePage>;
998
+ quoteFee: (input: BillFeeQuoteInput) => Promise<BillFeeQuote>;
885
999
  lookupPostalCode: (postalCode: string) => Promise<BillPostalPlace | null>;
886
1000
  getDeliveryOptions: () => Promise<BillDeliveryOptions>;
887
1001
  getDeliveryPreview: (input: BillDeliveryPreviewInput) => Promise<BillDeliveryOptions>;
888
1002
  getAttachment: (attachmentId: string) => Promise<Blob>;
889
1003
  getEor: (documentId: string) => Promise<Blob>;
890
1004
  getPacket: () => Promise<Blob>;
1005
+ getSubmissionArtifact: (attemptId: string, artifactId: string) => Promise<Blob>;
1006
+ /** Prepare a self-filing packet. Does not file IBR or send anything to a payer. */
1007
+ prepareIbrPacket: () => Promise<Blob>;
891
1008
  previewCourtesyCopy: (input: BillCourtesyCopyInput) => Promise<BillCourtesyCopyPreview>;
892
1009
  /** Reuse the same key when retrying the same send after a network interruption. */
893
1010
  sendCourtesyCopy: (input: BillCourtesyCopyInput & {
@@ -1105,4 +1222,4 @@ declare function billTasksAgingBucketIndex(ageDays: number, buckets?: BillTasksA
1105
1222
  */
1106
1223
  declare function buildBillTasksDashboard(items: BillTasksDashboardItem[], sections: BillTasksDashboardSectionInput[], buckets?: BillTasksAgingBucket[]): BillTasksDashboardData;
1107
1224
 
1108
- 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 BillCourtesyCopyInput, type BillCourtesyCopyPreview, type BillCourtesyCopyResult, 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 BillSubmissionDetail, type BillSubmissionRoute, type BillTasksAgingBucket, type BillTasksDashboardData, type BillTasksDashboardItem, type BillTasksDashboardRow, type BillTasksDashboardSection, type BillTasksDashboardSectionInput, type BillTasksDashboardTone, type BillTeamNote, type BrowserBillAddress, type BrowserBillCreateInput, type BrowserBillSubmissionDocument, type BrowserBillSubmissionInput, type BrowserBillSubmissionResult, type BrowserSubmittedBill, type CloseBillInput, DEFAULT_API_BASE_URL, DEFAULT_SESSION_ENDPOINT, type HistoricalBillReviewData, 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 };
1225
+ 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 BillCourtesyCopyInput, type BillCourtesyCopyPreview, type BillCourtesyCopyResult, type BillDeliveryOption, type BillDeliveryOptions, type BillDeliveryPreviewInput, type BillDiagnosisCode, type BillEorDocument, type BillFeeQuote, type BillFeeQuoteInput, type BillFeeSource, type BillHistoryEntry, type BillLifecycleAction, type BillLifecycleActionId, type BillLifecycleClient, type BillLifecycleClientOptions, type BillLifecycleData, type BillLifecycleDelivery, type BillLifecycleSession, type BillLifecycleSessionProvider, type BillLifecycleSessionRequest, type BillPaymentRecord, type BillPostalPlace, type BillProcedureCodePage, type BillProcedureCodeSearchInput, type BillReferenceClient, type BillReferenceClientOptions, type BillRejection, type BillRejectionIssue, type BillRemittanceSummary, type BillReviewAttachment, type BillReviewBillingProvider, type BillReviewClaimPatternStatus, type BillReviewClinician, type BillReviewData, type BillReviewDocumentType, type BillReviewFeatures, type BillReviewLineItem, type BillReviewLocation, type BillReviewPayer, type BillReviewPayerListInput, type BillReviewPayerOption, type BillReviewPayerPage, type BillReviewPayerSuggestion, type BillReviewSaveInput, type BillSubmissionClient, type BillSubmissionClientOptions, type BillSubmissionDetail, type BillSubmissionRoute, type BillTasksAgingBucket, type BillTasksDashboardData, type BillTasksDashboardItem, type BillTasksDashboardRow, type BillTasksDashboardSection, type BillTasksDashboardSectionInput, type BillTasksDashboardTone, type BillTeamNote, type BrowserBillAddress, type BrowserBillCreateInput, type BrowserBillSubmissionDocument, type BrowserBillSubmissionInput, type BrowserBillSubmissionResult, type BrowserSubmittedBill, type CloseBillInput, type CorrectionDraft, DEFAULT_API_BASE_URL, DEFAULT_SESSION_ENDPOINT, type HistoricalBillReviewData, 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, parseSecondReviewCorrection, reportBillStatusContacts, sanitizeBillReviewSaveInput, secondReviewDeadline };
package/dist/index.js CHANGED
@@ -1,3 +1,22 @@
1
+ // src/second-review-corrections.ts
2
+ function parseSecondReviewCorrection(draft) {
3
+ if (!draft.correctBilling) return void 0;
4
+ const units = Number(draft.units);
5
+ const charge = Number(draft.charge);
6
+ const modifiers = draft.modifiers.trim().toUpperCase().split(/[\s,]+/).filter(Boolean);
7
+ if (!draft.units.trim() || !Number.isInteger(units) || units < 1 || units > 1e4) {
8
+ throw new Error("Corrected units must be a whole number from 1 to 10,000.");
9
+ }
10
+ if (modifiers.length > 4 || new Set(modifiers).size !== modifiers.length || modifiers.some((value) => !/^[A-Z0-9]{2}$/.test(value))) {
11
+ throw new Error("Enter up to four unique two-character modifiers, separated by commas. Leave blank to remove modifiers.");
12
+ }
13
+ if (!draft.charge.trim() || !Number.isFinite(charge) || charge < 0 || charge > 999999.99 || Math.abs(charge * 100 - Math.round(charge * 100)) > 1e-6) {
14
+ throw new Error("Enter the corrected charge in dollars and cents.");
15
+ }
16
+ if (!draft.chargeReviewed) throw new Error("Confirm that you reviewed the corrected charge. It is not recalculated automatically.");
17
+ return { units, modifiers, charge };
18
+ }
19
+
1
20
  // src/index.ts
2
21
  var DEFAULT_API_BASE_URL = "https://app.mindbill.org";
3
22
  var DEFAULT_SESSION_ENDPOINT = "/api/mindbill/session";
@@ -462,6 +481,40 @@ function createBillLifecycleClient({
462
481
  return typeof candidate.code === "string" && typeof candidate.description === "string" ? [{ code: candidate.code, description: candidate.description }] : [];
463
482
  });
464
483
  };
484
+ const searchProcedureCodes = async (input = {}) => {
485
+ const limit = Number.isFinite(input.limit) ? Math.max(1, Math.min(100, Math.floor(input.limit))) : 30;
486
+ const params = new URLSearchParams({ q: input.query?.trim() ?? "", limit: String(limit), jurisdiction: input.jurisdiction?.trim().toUpperCase() || "CA" });
487
+ const response = await request(`/partner/v2/procedure-codes?${params}`);
488
+ if (!response.ok) throw await responseError(response, "Procedure-code search is unavailable.");
489
+ const body = await response.json();
490
+ if (!Array.isArray(body.results) || typeof body.total !== "number" || !Number.isFinite(body.total) || body.total < 0 || typeof body.limit !== "number" || !Number.isFinite(body.limit) || body.limit < 1 || !["CA", "NY", "OWCP"].includes(body.jurisdiction ?? "") || !(body.catalogAsOf === null || typeof body.catalogAsOf === "string")) {
491
+ throw new Error("Procedure-code search returned an invalid response.");
492
+ }
493
+ return {
494
+ results: body.results.flatMap((entry) => entry && typeof entry.code === "string" && entry.code.trim() ? [{ code: entry.code }] : []),
495
+ total: body.total,
496
+ limit: body.limit,
497
+ jurisdiction: body.jurisdiction,
498
+ catalogAsOf: body.catalogAsOf
499
+ };
500
+ };
501
+ const quoteFee = async (input) => {
502
+ const response = await request("/partner/v2/fee-quotes", {
503
+ method: "POST",
504
+ headers: { "content-type": "application/json" },
505
+ body: JSON.stringify(input)
506
+ });
507
+ if (!response.ok) throw await responseError(response, "Fee-schedule pricing is unavailable.");
508
+ const body = await response.json();
509
+ const quote = body.data;
510
+ if (!quote || !Array.isArray(quote.provenance)) throw new Error("Fee quote returned an invalid response.");
511
+ if (quote.status === "priced") {
512
+ if (!Number.isSafeInteger(quote.amountCents) || quote.amountCents < 0 || !Number.isSafeInteger(quote.scheduleMaximumCents) || quote.scheduleMaximumCents < 0 || !["ca_report", "ca_physician_rbrvs", "ca_therapy_rbrvs"].includes(quote.basis) || !Array.isArray(quote.notes) || quote.notes.some((note) => typeof note !== "string")) throw new Error("Fee quote returned an invalid response.");
513
+ } else if (quote.status !== "requires_review" && quote.status !== "not_separately_payable" || typeof quote.reason !== "string") {
514
+ throw new Error("Fee quote returned an invalid response.");
515
+ }
516
+ return quote;
517
+ };
465
518
  const lookupPostalCode = async (postalCode) => {
466
519
  const params = new URLSearchParams({ postalCode: postalCode.trim() });
467
520
  const response = await request(`/partner/v2/postal-codes?${params.toString()}`);
@@ -510,6 +563,8 @@ function createBillLifecycleClient({
510
563
  searchClaimsAdministrators,
511
564
  getClaimsAdministratorDirectory,
512
565
  searchDiagnosisCodes,
566
+ searchProcedureCodes,
567
+ quoteFee,
513
568
  lookupPostalCode,
514
569
  async getDeliveryOptions() {
515
570
  const response = await request(billPath("/delivery-options"));
@@ -541,6 +596,23 @@ function createBillLifecycleClient({
541
596
  if (!response.ok) throw await responseError(response, "Submission packet could not be downloaded.");
542
597
  return response.blob();
543
598
  },
599
+ async getSubmissionArtifact(attemptId, artifactId) {
600
+ const response = await request(billPath(`/submissions/${encodeURIComponent(attemptId)}/artifacts/${encodeURIComponent(artifactId)}`));
601
+ if (!response.ok) throw await responseError(response, "The retained submission file could not be downloaded.");
602
+ return response.blob();
603
+ },
604
+ async prepareIbrPacket() {
605
+ const prepared = await mutation(billPath("/actions"), {
606
+ method: "POST",
607
+ headers: { "content-type": "application/json" },
608
+ body: JSON.stringify({ action: "independent_bill_review" })
609
+ }, "IBR packet could not be prepared.");
610
+ const body = await prepared.json();
611
+ if (typeof body.packetUrl !== "string" || !/^\/partner\/v2\/(?:browser\/)?bills\/[A-Za-z0-9_-]+\/ibr-packet$/.test(body.packetUrl)) throw new Error("The billing service returned an invalid IBR packet path.");
612
+ const response = await request(body.packetUrl);
613
+ if (!response.ok) throw await responseError(response, "IBR packet could not be downloaded.");
614
+ return response.blob();
615
+ },
544
616
  async previewCourtesyCopy(input) {
545
617
  const response = await request(billPath("/courtesy-forward"), {
546
618
  method: "POST",
@@ -600,6 +672,8 @@ function createBillReferenceClient(options = {}) {
600
672
  searchClaimsAdministrators: lifecycle.searchClaimsAdministrators,
601
673
  getClaimsAdministratorDirectory: lifecycle.getClaimsAdministratorDirectory,
602
674
  searchDiagnosisCodes: lifecycle.searchDiagnosisCodes,
675
+ searchProcedureCodes: lifecycle.searchProcedureCodes,
676
+ quoteFee: lifecycle.quoteFee,
603
677
  lookupPostalCode: lifecycle.lookupPostalCode,
604
678
  getDeliveryPreview: lifecycle.getDeliveryPreview,
605
679
  clearSession: lifecycle.clearSession
@@ -749,6 +823,7 @@ export {
749
823
  createOrganizationClient,
750
824
  defaultBillReviewPayerOption,
751
825
  organizationTaxIdWrite,
826
+ parseSecondReviewCorrection,
752
827
  reportBillStatusContacts,
753
828
  sanitizeBillReviewSaveInput,
754
829
  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 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 BillTeamNote = { id: string; body: string; author: string; createdAt: string; pinned: boolean };\n\nexport type BillCourtesyCopyInput = {\n to: string[];\n cc?: string[];\n subject: string;\n bodyText: string;\n includeCms1500?: boolean;\n documentIds?: string[];\n};\nexport type BillCourtesyCopyPreview = {\n filename: string; documentCount: number; packetHash: string; pdfBase64: string;\n environment: \"sandbox\" | \"live\";\n};\nexport type BillCourtesyCopyResult = { ok: boolean; sent: boolean; simulated?: boolean; dryRun?: boolean; messageId?: string };\n\n/** Historical financial balances are unavailable, not zero. */\nexport type HistoricalBillReviewData = Omit<BillReviewData, \"bill\"> & {\n bill: Omit<BillReviewData[\"bill\"], \"totalPaid\" | \"balanceDue\"> & {\n totalPaid: number | null;\n balanceDue: number | null;\n };\n};\nexport type BillSubmissionDetail = {\n attemptId: string;\n billId: string;\n source: \"submission_snapshot\" | \"bill_record\" | \"unavailable\";\n capturedAt?: string | null;\n detail: HistoricalBillReviewData | null;\n};\n\nexport type BillLifecycleData = BillReviewData & {\n environment: \"sandbox\" | \"live\";\n lifecycle: {\n state: string;\n nativeStatus: string;\n submittedAt?: string | null;\n agingDays?: number | null;\n updatedAt?: string | null;\n actions: BillLifecycleAction[];\n };\n eors: BillEorDocument[];\n activity: BillActivityRecord[];\n /** Presented history rows. Optional: absent when the API\n * predates the presented-history rollout — fall back to `activity`. */\n history?: BillHistoryEntry[];\n /** Canonical team notes, shared with the MindBill app. Absent on older APIs. */\n notes?: BillTeamNote[];\n /** Immutable submissions that share this bill's unified history. */\n attempts?: BillAttemptSummary[];\n /** Per-attempt details. Older APIs may omit this; never substitute the current bill. */\n submissionDetails?: BillSubmissionDetail[];\n payments: BillPaymentRecord[];\n remittance: BillRemittanceSummary;\n delivery: BillLifecycleDelivery;\n rejection?: BillRejection | null;\n};\n\nexport type BillLifecycleSession = {\n token: string;\n expiresAt?: string;\n apiBaseUrl?: string;\n};\n\nexport type BillLifecycleSessionRequest = {\n signal: AbortSignal;\n};\n\nexport type BillLifecycleSessionProvider = (\n request: BillLifecycleSessionRequest,\n) => Promise<BillLifecycleSession>;\n\nexport type CloseBillInput = BillActorInput & { reason: string };\nexport type ReopenBillInput = BillActorInput & { reason: string };\nexport type PostBillPaymentInput = BillActorInput & {\n amount: number;\n penaltyAmount?: number;\n interestAmount?: number;\n method: \"check\" | \"eft\";\n checkNumber?: string;\n depositDate: string;\n note?: string;\n};\nexport type SecondReviewLineInput = {\n lineItemId: string;\n reason: string;\n /** SBR-1 box for this service line. Omitted leaves the box blank. */\n serviceAuthorized?: boolean;\n /** Absolute corrected values for this Second Review only; charge is explicitly reviewed, never inferred. */\n correction?: { units: number; modifiers: string[]; charge: number };\n};\n\nexport type SubmitSecondReviewInput = BillActorInput & {\n /** @deprecated Prefer `lineItems[].reason`; retained for older hosts. */\n reason?: string;\n /** @deprecated MindBill derives this from the payer response on the server. */\n payerClaimControlNumber?: string;\n disputedAmount?: number;\n attachmentIds: string[];\n route: BillSubmissionRoute;\n /** New PDFs to include with the Second Review. */\n documents?: BrowserBillSubmissionDocument[];\n destination?: SubmitBillInput[\"destination\"];\n attention?: string;\n subject?: string;\n note?: string;\n cc?: string[];\n /** Line-by-line SBR-1 selections, reasons, and authorization answers. */\n lineItems?: SecondReviewLineInput[];\n /** @deprecated Prefer `lineItems`; omitted = the whole bill. */\n lineItemIds?: string[];\n /** @deprecated Prefer `lineItems[].serviceAuthorized`. */\n serviceAuthorized?: boolean;\n};\n\nexport type ReportBillStatusId =\n | \"message_left\"\n | \"eor_pending\"\n | \"eor_sent\"\n | \"bill_not_on_file\"\n | \"forwarded\";\n\nexport type ReportBillStatusOption = {\n id: ReportBillStatusId;\n label: string;\n description: string;\n};\n\n/** The five supported outcomes of a bill payment-status phone call. */\nexport const REPORT_BILL_STATUS_OPTIONS: ReportBillStatusOption[] = [\n {\n id: \"message_left\",\n label: \"Message Left Requesting Bill Payment Status\",\n description: \"Claims Administrator/Bill Review representative unavailable.\",\n },\n {\n id: \"eor_pending\",\n label: \"Explanation of Review (EOR) Pending\",\n description: \"Claims Administrator/Bill Review reported the bill is still in process and an EOR has not been generated or sent.\",\n },\n {\n id: \"eor_sent\",\n label: \"Explanation of Review (EOR) Sent\",\n description: \"Claims Administrator/Bill Review reported sending an EOR to the provider.\",\n },\n {\n id: \"bill_not_on_file\",\n label: \"Bill Not On File\",\n description: \"Claims Administrator/Bill Review reported not receiving the bill.\",\n },\n {\n id: \"forwarded\",\n label: \"Bill Forwarded to Different Payer / Network\",\n description: \"Claims Administrator/Bill Review reported forwarding the bill to a different payer.\",\n },\n];\n\n/**\n * Outcome of a phone call to the Claims Administrator / Bill Review vendor\n * about an outstanding bill, recorded through the lifecycle actions endpoint.\n */\nexport type ReportBillStatusInput = BillActorInput & {\n status: ReportBillStatusId;\n company?: string;\n representativeName?: string;\n representativeRole?: string;\n phone?: string;\n callReference?: string;\n note?: string;\n};\n\n/**\n * Payload for the \"report_bill_status\" lifecycle action: records the outcome\n * of a phone call to the Claims Administrator / Bill Review vendor about an\n * outstanding bill. Posted through the generic lifecycle actions endpoint.\n */\nexport type ReportBillStatusActionInput = ReportBillStatusInput & {\n action: \"report_bill_status\";\n};\n\n/**\n * Payload for the \"send_duplicate\" lifecycle action. A duplicate is a fresh,\n * editable bill snapshot linked to the submitted original. The original stays\n * immutable; the biller must review the snapshot and explicitly confirm its\n * delivery route before this action is posted.\n */\nexport type SendDuplicateBillInput = ResubmitBillInput;\n\nexport type ReportBillStatusContacts = {\n claimsAdmin: {\n name: string;\n hoursOfOperation?: string;\n phones: Array<{ label: string; value: string }>;\n } | null;\n billReview: { name: string; phone?: string } | null;\n};\n\n/**\n * Partner-safe \"who to call\" summary for the Report Bill Status flow, derived\n * from the lifecycle delivery block (payer contacts + optional directory).\n */\nexport function reportBillStatusContacts(\n delivery: BillLifecycleDelivery,\n): ReportBillStatusContacts {\n const payerName = delivery.payerName?.trim();\n const directory = delivery.directory ?? null;\n const phones: Array<{ label: string; value: string }> = [];\n const adjusterPhone = delivery.contacts.adjusterPhone?.trim();\n if (adjusterPhone) {\n const adjusterName = delivery.contacts.adjusterName?.trim();\n phones.push({\n label: adjusterName ? `Adjuster (${adjusterName})` : \"Adjuster\",\n value: adjusterPhone,\n });\n }\n const hours = directory?.hours?.trim();\n const claimsAdmin = payerName\n ? {\n name: payerName,\n ...(hours ? { hoursOfOperation: hours } : {}),\n phones,\n }\n : null;\n const billReviewContact = (directory?.billReview ?? []).find(\n (contact) => contact.name?.trim() || contact.phone?.trim(),\n );\n const billReview = billReviewContact\n ? {\n name: billReviewContact.name?.trim() || \"Bill Review\",\n ...(billReviewContact.phone?.trim() ? { phone: billReviewContact.phone.trim() } : {}),\n }\n : null;\n return { claimsAdmin, billReview };\n}\n\n/**\n * Default Second Bill Review dispute reason for an invalid med-legal denial.\n * Prefilled (editable) in the SBR panel.\n */\nexport const SECOND_REVIEW_REASON_TEMPLATE =\n \"This is an appeal of the invalid denial of this med-legal bill; per LC §4622 and the OMFS/MLFS, payment is due as billed.\";\n\n/** Days allowed to request Second Review after service of the denial EOR. */\nexport const SECOND_REVIEW_WINDOW_DAYS = 90;\n\nexport type SecondReviewDeadline = {\n /** ISO date (yyyy-mm-dd) of the latest denial/EOR document. */\n eorDate: string;\n /** ISO date (yyyy-mm-dd) 90 days after the EOR date. */\n deadline: string;\n};\n\n/**\n * The 90-day Second Review window anchored on the latest EOR date, or null\n * when the lifecycle data provides no parseable denial/EOR date.\n */\nexport function secondReviewDeadline(\n eors: Array<Pick<BillEorDocument, \"addedAt\">>,\n): SecondReviewDeadline | null {\n const times = eors\n .map((eor) => Date.parse(eor.addedAt))\n .filter((time) => Number.isFinite(time));\n if (!times.length) return null;\n const eorTime = Math.max(...times);\n const isoDate = (time: number): string => new Date(time).toISOString().slice(0, 10);\n return {\n eorDate: isoDate(eorTime),\n deadline: isoDate(eorTime + SECOND_REVIEW_WINDOW_DAYS * 86_400_000),\n };\n}\n/**\n * A corrected immutable snapshot submitted as the next attempt on the same bill.\n * The logical bill ID remains stable; only the submission/control-number attempt advances.\n */\nexport type ResubmitBillInput = BillActorInput & {\n reason?: string;\n bill: BrowserBillCreateInput;\n /** Explicit delivery route confirmed by the biller for this new attempt. */\n submission?: Omit<SubmitBillInput, keyof BillActorInput>;\n documents?: BrowserBillSubmissionDocument[];\n};\n/**\n * \"Submit New Bill\" from a CLOSED bill: the same snapshot payload shape as a\n * resubmission, but the server creates a FRESH original bill linked to the closed\n * predecessor — the closed bill stays closed and keeps its record, and the\n * submissions ribbon/timeline chains both records.\n */\nexport type SubmitNewBillInput = ResubmitBillInput;\nexport type SandboxSimulationScenario = \"accepted\" | \"rejected\" | \"processed\" | \"denied\" | \"partial_payment\" | \"paid\";\nexport type SimulateSandboxBillInput = {\n scenario: SandboxSimulationScenario;\n amount?: number;\n reasonCode?: string;\n};\n\nexport type BrowserBillAddress = {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n postalCode: string;\n};\n\n/** Complete bill snapshot accepted by the browser create endpoint. */\nexport type BrowserBillCreateInput = {\n externalId?: string;\n billingMode?: \"med_legal\" | \"professional\";\n patient: {\n id?: string;\n externalId?: string;\n firstName: string;\n middleName?: string;\n lastName: string;\n dateOfBirth: string;\n ssn?: string;\n gender?: \"M\" | \"F\" | \"X\";\n phone?: string;\n address: BrowserBillAddress;\n };\n claim: {\n id?: string;\n externalId?: string;\n claimNumber: string;\n adjNumber?: string;\n employer: string;\n dateOfInjury: string;\n injuryState?: string;\n description?: string;\n claimsAdministrator: {\n id: string;\n name: string;\n /** The chosen payer (subpayor) when the claims administrator requires payer selection. */\n payerId?: string;\n };\n };\n service: { date: string; endDate?: string | null; authorizationNumber?: string | null };\n billingProvider: { 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 previewCourtesyCopy: (input: BillCourtesyCopyInput) => Promise<BillCourtesyCopyPreview>;\n /** Reuse the same key when retrying the same send after a network interruption. */\n sendCourtesyCopy: (input: BillCourtesyCopyInput & { packetHash: string }, idempotencyKey: string) => Promise<BillCourtesyCopyResult>;\n addNote: (input: AddBillNoteInput) => Promise<BillLifecycleData>;\n closeBill: (input: CloseBillInput) => Promise<BillLifecycleData>;\n reopenBill: (input: ReopenBillInput) => Promise<BillLifecycleData>;\n postPayment: (input: PostBillPaymentInput) => Promise<BillLifecycleData>;\n submitSecondReview: (input: SubmitSecondReviewInput) => Promise<BillLifecycleData>;\n resubmitBill: (input: ResubmitBillInput) => Promise<BillLifecycleData>;\n submitNewBill: (input: SubmitNewBillInput) => Promise<BillLifecycleData>;\n sendDuplicateBill: (input: SendDuplicateBillInput) => Promise<BillLifecycleData>;\n reportBillStatus: (input: ReportBillStatusInput) => Promise<BillLifecycleData>;\n simulateSandbox: (input: SimulateSandboxBillInput) => Promise<BillLifecycleData>;\n clearSession: () => void;\n};\n\nasync function responseError(response: Response, fallback: string): Promise<Error> {\n const body: unknown = await response.json().catch(() => null);\n const detail = body && typeof body === \"object\"\n ? (body as { detail?: unknown; message?: unknown; error?: unknown }).detail\n ?? (body as { message?: unknown }).message\n ?? (body as { error?: unknown }).error\n : null;\n return new Error(typeof detail === \"string\" ? detail : fallback);\n}\n\nfunction isSessionFresh(session: BillLifecycleSession | null): boolean {\n if (!session) return false;\n if (!session.expiresAt) return true;\n const expiresAt = new Date(session.expiresAt).getTime();\n return Number.isFinite(expiresAt) && expiresAt > Date.now() + 30_000;\n}\n\nfunction normalizeSession(value: unknown): BillLifecycleSession {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing session endpoint returned an invalid response.\");\n }\n const candidate = value as { token?: unknown; expiresAt?: unknown; apiBaseUrl?: unknown; session?: unknown; data?: unknown };\n const nested = candidate.session ?? candidate.data;\n const session = nested && typeof nested === \"object\" ? nested as typeof candidate : candidate;\n if (typeof session.token !== \"string\" || session.token.length < 8) {\n throw new Error(\"The billing session endpoint did not return a browser session token.\");\n }\n return {\n token: session.token,\n ...(typeof session.expiresAt === \"string\" ? { expiresAt: session.expiresAt } : {}),\n ...(typeof session.apiBaseUrl === \"string\" ? { apiBaseUrl: session.apiBaseUrl } : {}),\n };\n}\n\nfunction normalizeLifecycle(value: unknown): BillLifecycleData {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n const data = value as Partial<BillLifecycleData>;\n if (\n ![\"sandbox\", \"live\"].includes(data.environment ?? \"\")\n || !data.bill\n || !data.patient\n || !data.injury\n || !data.lifecycle\n || !Array.isArray(data.lifecycle.actions)\n || !Array.isArray(data.eors)\n || !Array.isArray(data.activity)\n || !Array.isArray(data.payments)\n || !data.remittance\n || typeof data.remittance !== \"object\"\n || !data.delivery\n || typeof data.delivery !== \"object\"\n || !data.delivery.contacts\n || typeof data.delivery.contacts !== \"object\"\n || (data.rejection != null && (\n typeof data.rejection !== \"object\"\n || typeof data.rejection.reason !== \"string\"\n || (data.rejection.issues != null && (\n !Array.isArray(data.rejection.issues)\n || data.rejection.issues.some((issue) => (\n !issue\n || typeof issue !== \"object\"\n || typeof issue.description !== \"string\"\n || (issue.code != null && typeof issue.code !== \"string\")\n ))\n ))\n ))\n ) {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n return data as BillLifecycleData;\n}\n\nfunction normalizeDeliveryOptions(value: unknown): BillDeliveryOptions {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n const data = value as Partial<BillDeliveryOptions>;\n if (\n typeof data.payerName !== \"string\"\n || !data.recommended\n || typeof data.recommended !== \"object\"\n || ![\"ebill\", \"fax\", \"mail\", \"email\"].includes(data.recommended.route ?? \"\")\n || !Array.isArray(data.options)\n || !data.contacts\n ) {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n return data as BillDeliveryOptions;\n}\n\nfunction idempotencyKey(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") return globalThis.crypto.randomUUID();\n return `mb-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Browser-safe client for one atomic create-and-submit operation.\n *\n * The browser session is short-lived and origin-bound. The host application\n * never needs the Partner API document schema or a long-lived API key.\n */\nexport function createBillSubmissionClient({\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillSubmissionClientOptions = {}): BillSubmissionClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const submitBill = async (\n input: BrowserBillSubmissionInput,\n options: { idempotencyKey?: string } = {},\n ): Promise<BrowserBillSubmissionResult> => {\n const controller = new AbortController();\n const requestIdempotencyKey = options.idempotencyKey ?? idempotencyKey();\n let browserSession = await mintSession(controller.signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n return fetcher(`${base}/partner/v2/bills`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${current.token}`,\n \"content-type\": \"application/json\",\n \"idempotency-key\": requestIdempotencyKey,\n },\n body: JSON.stringify(input),\n signal: controller.signal,\n });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(controller.signal, true);\n response = await perform(browserSession);\n }\n if (!response.ok) throw await responseError(response, \"The bill could not be submitted.\");\n const body: unknown = await response.json().catch(() => null);\n const envelope = body && typeof body === \"object\" && \"data\" in body\n ? (body as { data?: unknown }).data\n : body;\n if (!envelope || typeof envelope !== \"object\" || typeof (envelope as { id?: unknown }).id !== \"string\") {\n throw new Error(\"The billing service submitted the bill but returned an invalid bill ID.\");\n }\n const bill = envelope as BrowserSubmittedBill;\n return { billId: bill.id, bill };\n };\n\n return {\n submitBill,\n clearSession() { session = null; sessionRequest = null; },\n };\n}\n\n/** Browser-safe, framework-neutral client for an already-submitted bill. */\nexport function createBillLifecycleClient({\n billId,\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillLifecycleClientOptions): BillLifecycleClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n const currentBillId = billId.trim();\n if (!currentBillId) throw new Error(\"billId is required for the submitted-bill lifecycle client.\");\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const request = async (path: string, init: RequestInit = {}, providedSignal?: AbortSignal): Promise<Response> => {\n const controller = providedSignal ? null : new AbortController();\n const signal = providedSignal ?? controller?.signal;\n if (!signal) throw new Error(\"An AbortSignal could not be created.\");\n let browserSession = await mintSession(signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n const headers = new Headers(init.headers);\n headers.set(\"authorization\", `Bearer ${current.token}`);\n return fetcher(`${base}${path}`, { ...init, headers, signal });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(signal, true);\n response = await perform(browserSession);\n }\n return response;\n };\n\n const billPath = (suffix = \"\"): string =>\n `/partner/v2/bills/${encodeURIComponent(currentBillId)}${suffix}`;\n\n const loadLifecycle = async (signal?: AbortSignal) => {\n const response = await request(billPath(\"/lifecycle\"), {}, signal);\n if (!response.ok) throw await responseError(response, \"Bill lifecycle could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n\n const listClaimsAdministrators = async (input: BillReviewPayerListInput = {}): Promise<BillReviewPayerPage> => {\n const params = new URLSearchParams();\n if (input.query?.trim()) params.set(\"q\", input.query.trim());\n if (input.claimNumber?.trim()) params.set(\"claimNumber\", input.claimNumber.trim());\n if (input.sourceClaimsAdministratorName?.trim()) params.set(\"sourceClaimsAdministratorName\", input.sourceClaimsAdministratorName.trim());\n if (input.employerName?.trim()) params.set(\"employerName\", input.employerName.trim());\n const limit = Math.max(1, Math.min(100, Math.floor(input.limit ?? 50)));\n const offset = Math.max(0, Math.floor(input.offset ?? 0));\n params.set(\"limit\", String(limit));\n if (offset) params.set(\"offset\", String(offset));\n const response = await request(`/partner/v2/claims-administrators?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator search is unavailable.\");\n const body = await response.json() as { results?: unknown; suggestions?: unknown; total?: unknown; nextOffset?: unknown; recommendedId?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Claims administrator search returned an invalid response.\");\n const normalizePayer = (value: unknown): BillReviewPayer | null => {\n if (!value || typeof value !== \"object\") return null;\n const payer = value as Record<string, unknown>;\n if (typeof payer.id !== \"string\" || typeof payer.name !== \"string\") return null;\n const payers = Array.isArray(payer.payers) ? payer.payers.flatMap((option): BillReviewPayerOption[] => {\n if (!option || typeof option !== \"object\") return [];\n const candidate = option as Record<string, unknown>;\n const id = typeof candidate.id === \"string\" ? candidate.id : typeof candidate.key === \"string\" ? candidate.key : null;\n if (!id || typeof candidate.label !== \"string\") return [];\n return [{\n id,\n label: candidate.label,\n ...(typeof candidate.default === \"boolean\" ? { default: candidate.default } : {}),\n ...(typeof candidate.active === \"boolean\" ? { active: candidate.active } : {}),\n ...(Array.isArray(candidate.aliases) ? { aliases: candidate.aliases.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof candidate.hint === \"string\" ? { hint: candidate.hint } : {}),\n ...(Array.isArray(candidate.affiliatedEntities) ? { affiliatedEntities: candidate.affiliatedEntities.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof candidate.route === \"string\" ? { route: candidate.route } : {}),\n ...(typeof candidate.optionType === \"string\" ? { optionType: candidate.optionType } : {}),\n ...(typeof candidate.deliveryType === \"string\" ? { deliveryType: candidate.deliveryType } : {}),\n ...(typeof candidate.clearinghouse === \"string\" ? { clearinghouse: candidate.clearinghouse } : {}),\n ...(typeof candidate.payerId === \"string\" ? { payerId: candidate.payerId } : {}),\n ...(typeof candidate.sourceClearinghouse === \"string\" ? { sourceClearinghouse: candidate.sourceClearinghouse } : {}),\n ...(typeof candidate.sourcePayerId === \"string\" ? { sourcePayerId: candidate.sourcePayerId } : {}),\n ...(candidate.clearinghousePayerIds && typeof candidate.clearinghousePayerIds === \"object\" && !Array.isArray(candidate.clearinghousePayerIds)\n ? { clearinghousePayerIds: Object.fromEntries(Object.entries(candidate.clearinghousePayerIds).filter((entry): entry is [string, string] => typeof entry[1] === \"string\")) }\n : {}),\n ...(typeof candidate.preferredClearinghouse === \"string\" ? { preferredClearinghouse: candidate.preferredClearinghouse } : {}),\n }];\n }) : undefined;\n const claimNumberPatterns = Array.isArray(payer.claimNumberPatterns) ? payer.claimNumberPatterns.flatMap((value): BillClaimsAdministratorPattern[] => {\n if (!value || typeof value !== \"object\") return [];\n const pattern = value as Record<string, unknown>;\n if (typeof pattern.pattern !== \"string\") return [];\n return [{\n pattern: pattern.pattern,\n ...(typeof pattern.length === \"string\" || typeof pattern.length === \"number\" ? { length: pattern.length } : {}),\n ...(typeof pattern.example === \"string\" ? { example: pattern.example } : {}),\n ...(typeof pattern.matches === \"boolean\" || pattern.matches === null ? { matches: pattern.matches as boolean | null } : {}),\n }];\n }) : undefined;\n return {\n id: payer.id,\n name: payer.name,\n ...(typeof payer.hasElectronic === \"boolean\" ? { hasElectronic: payer.hasElectronic } : {}),\n ...(Array.isArray(payer.states) ? { states: payer.states.filter((state): state is string => typeof state === \"string\") } : {}),\n ...([\"high\", \"medium\", \"directory\"].includes(String(payer.confidence)) ? { confidence: payer.confidence as NonNullable<BillReviewPayer[\"confidence\"]> } : {}),\n ...(typeof payer.recommended === \"boolean\" ? { recommended: payer.recommended } : {}),\n ...(typeof payer.payerSelectionRequired === \"boolean\" ? { payerSelectionRequired: payer.payerSelectionRequired } : {}),\n ...(payers ? { payers } : {}),\n ...(Array.isArray(payer.aliases) ? { aliases: payer.aliases.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(Array.isArray(payer.affiliatedEntities) ? { affiliatedEntities: payer.affiliatedEntities.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof payer.claimNumberHint === \"string\" ? { claimNumberHint: payer.claimNumberHint } : {}),\n ...(claimNumberPatterns ? { claimNumberPatterns } : {}),\n ...(typeof payer.route === \"string\" ? { route: payer.route } : {}),\n ...(Array.isArray(payer.signals) ? { signals: payer.signals.flatMap((signal) => {\n if (!signal || typeof signal !== \"object\") return [];\n const candidate = signal as Record<string, unknown>;\n if (![\"name\", \"claim_number\"].includes(String(candidate.kind)) || ![\"match\", \"warning\"].includes(String(candidate.state)) || typeof candidate.label !== \"string\") return [];\n return [{ kind: candidate.kind as \"name\" | \"claim_number\", state: candidate.state as \"match\" | \"warning\", label: candidate.label }];\n }) } : {}),\n };\n };\n const results = body.results.flatMap((value): BillReviewPayer[] => {\n const payer = normalizePayer(value);\n return payer ? [payer] : [];\n });\n const suggestions = Array.isArray(body.suggestions) ? body.suggestions.flatMap((value): BillReviewPayerSuggestion[] => {\n const payer = normalizePayer(value);\n if (!payer || !value || typeof value !== \"object\") return [];\n const suggestion = value as Record<string, unknown>;\n if (typeof suggestion.deterministic !== \"boolean\" || typeof suggestion.reason !== \"string\") return [];\n return [{ ...payer, deterministic: suggestion.deterministic, reason: suggestion.reason, ...(typeof suggestion.selectedPayerId === \"string\" ? { selectedPayerId: suggestion.selectedPayerId } : {}) }];\n }) : [];\n const total = typeof body.total === \"number\" && Number.isFinite(body.total) ? Math.max(results.length, Math.floor(body.total)) : offset + results.length;\n return {\n results,\n ...(suggestions.length ? { suggestions } : {}),\n total,\n ...(typeof body.nextOffset === \"number\" && Number.isFinite(body.nextOffset) ? { nextOffset: Math.floor(body.nextOffset) } : {}),\n ...(typeof body.recommendedId === \"string\" ? { recommendedId: body.recommendedId } : {}),\n };\n };\n\n const searchClaimsAdministrators = async (query: string, claimNumber?: string): Promise<BillReviewPayer[]> =>\n (await listClaimsAdministrators({ query, ...(claimNumber ? { claimNumber } : {}) })).results;\n\n const getClaimsAdministratorDirectory = async (id: string, injuryState?: string): Promise<BillClaimsAdministratorDirectory> => {\n const params = new URLSearchParams();\n if (injuryState?.trim()) params.set(\"injuryState\", injuryState.trim());\n const response = await request(`/partner/v2/claims-administrators/${encodeURIComponent(id)}${params.size ? `?${params}` : \"\"}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator details are unavailable.\");\n const body = await response.json() as { data?: unknown };\n if (!body.data || typeof body.data !== \"object\") throw new Error(\"Claims administrator details returned an invalid response.\");\n return body.data as BillClaimsAdministratorDirectory;\n };\n\n const searchDiagnosisCodes = async (query: string, limit = 30, offset = 0): Promise<BillDiagnosisCode[]> => {\n const params = new URLSearchParams({ q: query.trim(), limit: String(Math.max(1, Math.min(100, limit))) });\n if (offset > 0) params.set(\"offset\", String(Math.max(0, Math.floor(offset))));\n const response = await request(`/partner/v2/diagnosis-codes?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Diagnosis-code search is unavailable.\");\n const body = await response.json() as { results?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Diagnosis-code search returned an invalid response.\");\n return body.results.flatMap((value): BillDiagnosisCode[] => {\n if (!value || typeof value !== \"object\") return [];\n const candidate = value as { code?: unknown; description?: unknown };\n return typeof candidate.code === \"string\" && typeof candidate.description === \"string\"\n ? [{ code: candidate.code, description: candidate.description }]\n : [];\n });\n };\n\n const lookupPostalCode = async (postalCode: string): Promise<BillPostalPlace | null> => {\n const params = new URLSearchParams({ postalCode: postalCode.trim() });\n const response = await request(`/partner/v2/postal-codes?${params.toString()}`);\n if (response.status === 404) return null;\n if (!response.ok) throw await responseError(response, \"ZIP lookup is unavailable.\");\n const body = await response.json() as { city?: unknown; state?: unknown };\n if (typeof body.city !== \"string\" || typeof body.state !== \"string\") {\n throw new Error(\"ZIP lookup returned an invalid response.\");\n }\n return { city: body.city, state: body.state };\n };\n\n const mutation = async (path: string, init: RequestInit, fallback: string) => {\n const headers = new Headers(init.headers);\n headers.set(\"idempotency-key\", idempotencyKey());\n const response = await request(path, { ...init, headers });\n if (!response.ok) throw await responseError(response, fallback);\n return response;\n };\n const action = async (input: Record<string, unknown>, fallback: string): Promise<BillLifecycleData> => {\n const response = await mutation(billPath(\"/actions\"), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, fallback);\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n const simulateSandbox = async (input: SimulateSandboxBillInput): Promise<BillLifecycleData> => {\n await mutation(`/partner/v2/sandbox/bills/${encodeURIComponent(currentBillId)}/simulate`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, \"Sandbox lifecycle could not be simulated.\");\n return loadLifecycle();\n };\n return {\n getBillId() { return currentBillId; },\n clearSession() { session = null; sessionRequest = null; },\n getLifecycle: loadLifecycle,\n listClaimsAdministrators,\n searchClaimsAdministrators,\n getClaimsAdministratorDirectory,\n searchDiagnosisCodes,\n lookupPostalCode,\n async getDeliveryOptions() {\n const response = await request(billPath(\"/delivery-options\"));\n if (!response.ok) throw await responseError(response, \"Delivery options could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getDeliveryPreview(input) {\n const params = new URLSearchParams({ claimsAdministratorId: input.claimsAdministratorId.trim() });\n if (input.payerId?.trim()) params.set(\"payerId\", input.payerId.trim());\n if (input.injuryState?.trim()) params.set(\"injuryState\", input.injuryState.trim());\n const response = await request(`/partner/v2/delivery-preview?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Delivery routes could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getAttachment(attachmentId) {\n const response = await request(billPath(`/documents/${encodeURIComponent(attachmentId)}`));\n if (!response.ok) throw await responseError(response, \"Document could not be opened.\");\n return response.blob();\n },\n async getEor(documentId) {\n const response = await request(billPath(`/eors/${encodeURIComponent(documentId)}`));\n if (!response.ok) throw await responseError(response, \"EOR could not be opened.\");\n return response.blob();\n },\n async getPacket() {\n const response = await request(billPath(\"/packet\"));\n if (!response.ok) throw await responseError(response, \"Submission packet could not be downloaded.\");\n return response.blob();\n },\n async previewCourtesyCopy(input) {\n const response = await request(billPath(\"/courtesy-forward\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ ...input, mode: \"preview\" }),\n });\n if (!response.ok) throw await responseError(response, \"Courtesy copy could not be previewed.\");\n return response.json() as Promise<BillCourtesyCopyPreview>;\n },\n async sendCourtesyCopy(input, key) {\n if (!key.trim() || key.length > 255) throw new Error(\"A stable idempotency key is required to send a courtesy copy.\");\n const response = await request(billPath(\"/courtesy-forward\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\", \"idempotency-key\": key },\n body: JSON.stringify({ ...input, mode: \"send\" }),\n });\n if (!response.ok) throw await responseError(response, \"Courtesy copy could not be sent. Retry with the same key to check the result safely.\");\n return response.json() as Promise<BillCourtesyCopyResult>;\n },\n addNote(input) { return action({ action: \"add_note\", ...input }, \"Note could not be added.\"); },\n closeBill(input) { return action({ action: \"close\", ...input }, \"Bill could not be closed.\"); },\n reopenBill(input) { return action({ action: \"reopen\", ...input }, \"Bill could not be reopened.\"); },\n postPayment(input) { return action({ action: \"post_payment\", penaltyAmount: 0, interestAmount: 0, ...input, checkNumber: input.checkNumber ?? \"\" }, \"Payment could not be posted.\"); },\n submitSecondReview(input) { return action({ action: \"second_review\", ...input }, \"Second Review could not be submitted.\"); },\n resubmitBill(input) { return action({ action: \"resubmit\", ...input }, \"Bill could not be resubmitted.\"); },\n submitNewBill(input) { return action({ action: \"submit_new_bill\", ...input }, \"The new bill could not be submitted.\"); },\n sendDuplicateBill(input) { return action({ action: \"send_duplicate\", ...input }, \"Duplicate bill could not be sent.\"); },\n reportBillStatus(input) { return action({ action: \"report_bill_status\", ...input }, \"Bill status could not be reported.\"); },\n simulateSandbox,\n };\n}\n\n/**\n * Browser-safe client for reference data needed before a bill exists.\n *\n * Partners can pass the same short-lived session provider used by the submitted-bill\n * lifecycle without inventing a draft bill or exposing payer directory credentials.\n */\nexport function createBillReferenceClient(\n options: BillReferenceClientOptions = {},\n): BillReferenceClient {\n const lifecycle = createBillLifecycleClient({\n ...options,\n billId: \"pre-submission-reference-data\",\n });\n return {\n listClaimsAdministrators: lifecycle.listClaimsAdministrators,\n searchClaimsAdministrators: lifecycle.searchClaimsAdministrators,\n getClaimsAdministratorDirectory: lifecycle.getClaimsAdministratorDirectory,\n searchDiagnosisCodes: lifecycle.searchDiagnosisCodes,\n 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/organization\"),\n getBillingProfile: () => request(\"/partner/v2/organization/billing-profile\"),\n saveBillingProfile: (input) =>\n request(\"/partner/v2/organization/billing-profile\", { method: \"PUT\", body: JSON.stringify({\n ...input,\n ...(input.practiceIdentity ? { practiceIdentity: organizationTaxIdWrite(input.practiceIdentity) } : {}),\n ...(input.billingProviders ? { billingProviders: input.billingProviders.map(organizationTaxIdWrite) } : {}),\n }) }),\n saveLocations: (locations) =>\n request(\"/partner/v2/organization/locations\", { method: \"PUT\", body: JSON.stringify({ locations }) }),\n saveW9: (input) =>\n request(\"/partner/v2/organization/w9\", { method: \"PUT\", body: JSON.stringify(input) }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Bill Tasks dashboard: a pure, framework-neutral\n// aggregation shared by the React and Angular components. Hosts flatten their\n// own work items and get back per-section rows bucketed by age in days.\n\nexport type BillTasksAgingBucket = {\n id: string;\n label: string;\n /** Exclusive lower bound in days. The first bucket also admits day 0. */\n minDays: number;\n /** Inclusive upper bound in days; null means unbounded. */\n maxDays: number | null;\n};\n\nexport const BILL_TASKS_AGING_BUCKETS: BillTasksAgingBucket[] = [\n { id: \"1-30\", label: \"1-30 Days Ago\", minDays: 0, maxDays: 30 },\n { id: \"31-60\", label: \"31-60 Days Ago\", minDays: 30, maxDays: 60 },\n { id: \"61-90\", label: \"61-90 Days Ago\", minDays: 60, maxDays: 90 },\n { id: \"91-180\", label: \"91-180 Days Ago\", minDays: 90, maxDays: 180 },\n { id: \"181+\", label: \"181+ Days Ago\", minDays: 180, maxDays: null },\n];\n\nexport type BillTasksDashboardItem = {\n sectionId: string;\n rowId: string;\n rowLabel: string;\n ageDays: number;\n balanceDue?: number;\n /** Opaque bill reference echoed back in click-through payloads. */\n ref?: string;\n};\n\nexport type BillTasksDashboardRow = {\n id: string;\n label: string;\n /** One count per aging bucket, in bucket order. */\n counts: number[];\n total: number;\n /** Summed item balanceDue per bucket; optional for older count-only payloads. */\n balances?: number[];\n balanceTotal?: number;\n /** Collected item refs per aging bucket, in bucket order. */\n refs: string[][];\n};\n\nexport type BillTasksDashboardTone = \"violet\" | \"red\" | \"blue\" | \"green\" | \"amber\" | \"neutral\";\n\nexport type BillTasksDashboardSectionInput = {\n id: string;\n label: string;\n /** Shown under the section label as \"by {agingBasisLabel}\". */\n agingBasisLabel: string;\n tone: BillTasksDashboardTone;\n};\n\nexport type BillTasksDashboardSection = BillTasksDashboardSectionInput & {\n rows: BillTasksDashboardRow[];\n /** Per-bucket totals across the section's rows. */\n totals: number[];\n total: number;\n balanceTotals?: number[];\n balanceTotal?: number;\n empty: boolean;\n};\n\nexport type BillTasksDashboardData = {\n sections: BillTasksDashboardSection[];\n grandTotals: number[];\n grandTotal: number;\n /** Work-item sums, not deduplicated financial A/R across task categories. */\n grandBalanceTotals?: number[];\n grandBalanceTotal?: number;\n};\n\n/**\n * Bucket index for an item age: a bucket admits `minDays < ageDays <= maxDays`\n * (`maxDays: null` = unbounded) and the first bucket also admits day 0.\n * Ages beyond every bucket clamp into the last bucket.\n */\nexport function billTasksAgingBucketIndex(\n ageDays: number,\n buckets: BillTasksAgingBucket[] = BILL_TASKS_AGING_BUCKETS,\n): number {\n const days = Math.max(0, Math.floor(ageDays));\n const index = buckets.findIndex((bucket, position) =>\n (bucket.maxDays === null || days <= bucket.maxDays)\n && (days > bucket.minDays || position === 0));\n return index === -1 ? buckets.length - 1 : index;\n}\n\n/**\n * Aggregates flat work items into the Bill Tasks dashboard.\n * Sections render in the given order even when empty; rows appear in\n * first-seen item order within their section.\n */\nexport function buildBillTasksDashboard(\n items: BillTasksDashboardItem[],\n sections: BillTasksDashboardSectionInput[],\n buckets: BillTasksAgingBucket[] = BILL_TASKS_AGING_BUCKETS,\n): BillTasksDashboardData {\n const zeros = () => buckets.map(() => 0);\n const built = sections.map((section): BillTasksDashboardSection => ({\n ...section,\n rows: [],\n totals: zeros(),\n total: 0,\n balanceTotals: zeros(),\n balanceTotal: 0,\n empty: true,\n }));\n const sectionById = new Map(built.map((section) => [section.id, section]));\n const rowByKey = new Map<string, BillTasksDashboardRow>();\n const grandTotals = zeros();\n let grandTotal = 0;\n const grandBalanceTotals = zeros();\n let grandBalanceTotal = 0;\n\n for (const item of items) {\n const section = sectionById.get(item.sectionId);\n if (!section) continue;\n const key = `${item.sectionId}\\u0000${item.rowId}`;\n let row = rowByKey.get(key);\n if (!row) {\n row = {\n id: item.rowId,\n label: item.rowLabel,\n counts: zeros(),\n total: 0,\n balances: zeros(),\n balanceTotal: 0,\n refs: buckets.map(() => []),\n };\n rowByKey.set(key, row);\n section.rows.push(row);\n section.empty = false;\n }\n const bucketIndex = billTasksAgingBucketIndex(item.ageDays, buckets);\n const balance = Number.isFinite(item.balanceDue) ? item.balanceDue! : 0;\n row.counts[bucketIndex] = (row.counts[bucketIndex] ?? 0) + 1;\n row.total += 1;\n row.balances![bucketIndex] = (row.balances![bucketIndex] ?? 0) + balance;\n row.balanceTotal = (row.balanceTotal ?? 0) + balance;\n if (item.ref) row.refs[bucketIndex]?.push(item.ref);\n section.totals[bucketIndex] = (section.totals[bucketIndex] ?? 0) + 1;\n section.total += 1;\n section.balanceTotals![bucketIndex] = (section.balanceTotals![bucketIndex] ?? 0) + balance;\n section.balanceTotal = (section.balanceTotal ?? 0) + balance;\n grandTotals[bucketIndex] = (grandTotals[bucketIndex] ?? 0) + 1;\n grandTotal += 1;\n grandBalanceTotals[bucketIndex] = (grandBalanceTotals[bucketIndex] ?? 0) + balance;\n grandBalanceTotal += balance;\n }\n\n return { sections: built, grandTotals, grandTotal, grandBalanceTotals, grandBalanceTotal };\n}\n"],"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,SAAY,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,IAChE,GAAI,MAAM,mBAAmB;AAAA,MAC3B,kBAAkB,YAAY,MAAM,kBAAkB;AAAA,QACpD;AAAA,QAAa;AAAA,QAAc;AAAA,QAAY;AAAA,MACzC,CAAC;AAAA,IACH,IAAI,CAAC;AAAA,IACL,GAAI,MAAM,kBAAkB;AAAA,MAC1B,iBAAiB,YAAY,MAAM,iBAAiB;AAAA,QAClD;AAAA,QAAe;AAAA,QAAY;AAAA,QAAO;AAAA,QAClC;AAAA,QAAoB;AAAA,MACtB,CAAC;AAAA,IACH,IAAI,CAAC;AAAA,IACL,KAAK,MAAM;AAAA,IACX,GAAI,MAAM,W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,cAAQ,QAAQ;AAAA,IAClB;AACA,UAAM,cAAc,0BAA0B,KAAK,SAAS,OAAO;AACnE,UAAM,UAAU,OAAO,SAAS,KAAK,UAAU,IAAI,KAAK,aAAc;AACtE,QAAI,OAAO,WAAW,KAAK,IAAI,OAAO,WAAW,KAAK,KAAK;AAC3D,QAAI,SAAS;AACb,QAAI,SAAU,WAAW,KAAK,IAAI,SAAU,WAAW,KAAK,KAAK;AACjE,QAAI,gBAAgB,IAAI,gBAAgB,KAAK;AAC7C,QAAI,KAAK,IAAK,KAAI,KAAK,WAAW,GAAG,KAAK,KAAK,GAAG;AAClD,YAAQ,OAAO,WAAW,KAAK,QAAQ,OAAO,WAAW,KAAK,KAAK;AACnE,YAAQ,SAAS;AACjB,YAAQ,cAAe,WAAW,KAAK,QAAQ,cAAe,WAAW,KAAK,KAAK;AACnF,YAAQ,gBAAgB,QAAQ,gBAAgB,KAAK;AACrD,gBAAY,WAAW,KAAK,YAAY,WAAW,KAAK,KAAK;AAC7D,kBAAc;AACd,uBAAmB,WAAW,KAAK,mBAAmB,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/second-review-corrections.ts","../src/index.ts"],"sourcesContent":["import type { SecondReviewLineInput } from \"./index\";\n\nexport type CorrectionDraft = {\n correctBilling: boolean;\n units: string;\n modifiers: string;\n charge: string;\n chargeReviewed: boolean;\n};\n\nexport function parseSecondReviewCorrection(draft: CorrectionDraft): SecondReviewLineInput[\"correction\"] {\n if (!draft.correctBilling) return undefined;\n const units = Number(draft.units);\n const charge = Number(draft.charge);\n const modifiers = draft.modifiers.trim().toUpperCase().split(/[\\s,]+/).filter(Boolean);\n if (!draft.units.trim() || !Number.isInteger(units) || units < 1 || units > 10_000) {\n throw new Error(\"Corrected units must be a whole number from 1 to 10,000.\");\n }\n if (modifiers.length > 4 || new Set(modifiers).size !== modifiers.length || modifiers.some((value) => !/^[A-Z0-9]{2}$/.test(value))) {\n throw new Error(\"Enter up to four unique two-character modifiers, separated by commas. Leave blank to remove modifiers.\");\n }\n if (!draft.charge.trim() || !Number.isFinite(charge) || charge < 0 || charge > 999_999.99 || Math.abs(charge * 100 - Math.round(charge * 100)) > 0.000001) {\n throw new Error(\"Enter the corrected charge in dollars and cents.\");\n }\n if (!draft.chargeReviewed) throw new Error(\"Confirm that you reviewed the corrected charge. It is not recalculated automatically.\");\n return { units, modifiers, charge };\n}\n","export const DEFAULT_API_BASE_URL = \"https://app.mindbill.org\";\nexport const DEFAULT_SESSION_ENDPOINT = \"/api/mindbill/session\";\nexport { parseSecondReviewCorrection, type CorrectionDraft } from \"./second-review-corrections\";\n\nexport type BillReviewDocumentType =\n | \"final_report\"\n | \"letter_of_attestation\"\n | \"proof_of_service\"\n | \"form_122\"\n | \"return_to_work_voucher\"\n | \"w9\"\n | \"medical_records\"\n | \"appeal\"\n | \"other\";\n\nexport type BillReviewBillingProvider = {\n name: string;\n taxId: string;\n taxIdType?: \"EIN\" | \"SSN\";\n taxIdConfigured?: boolean;\n taxIdLast4?: string;\n npi: string;\n billType: \"Professional\" | \"Institutional\";\n phone?: string;\n billingStreet?: string;\n billingCity?: string;\n billingState?: string;\n billingZip?: string;\n};\n\nexport type BillReviewClinician = {\n 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 BillTeamNote = { id: string; body: string; author: string; createdAt: string; pinned: boolean };\n\nexport type BillCourtesyCopyInput = {\n to: string[];\n cc?: string[];\n subject: string;\n bodyText: string;\n includeCms1500?: boolean;\n documentIds?: string[];\n};\nexport type BillCourtesyCopyPreview = {\n filename: string; documentCount: number; packetHash: string; pdfBase64: string;\n environment: \"sandbox\" | \"live\";\n};\nexport type BillCourtesyCopyResult = { ok: boolean; sent: boolean; simulated?: boolean; dryRun?: boolean; messageId?: string };\n\n/** Historical financial balances are unavailable, not zero. */\nexport type HistoricalBillReviewData = Omit<BillReviewData, \"bill\"> & {\n bill: Omit<BillReviewData[\"bill\"], \"totalPaid\" | \"balanceDue\"> & {\n totalPaid: number | null;\n balanceDue: number | null;\n };\n};\nexport type BillSubmissionDetail = {\n attemptId: string;\n billId: string;\n source: \"submission_snapshot\" | \"bill_record\" | \"unavailable\";\n capturedAt?: string | null;\n detail: HistoricalBillReviewData | null;\n /** Exact retained files for this attempt; never regenerated from current bill values. */\n artifacts?: Array<{ id: string; label: string; kind: \"submitted_attachment\" | \"submitted_edi\"; contentType: string }>;\n};\n\nexport type BillLifecycleData = BillReviewData & {\n environment: \"sandbox\" | \"live\";\n lifecycle: {\n state: string;\n nativeStatus: string;\n submittedAt?: string | null;\n agingDays?: number | null;\n updatedAt?: string | null;\n actions: BillLifecycleAction[];\n };\n eors: BillEorDocument[];\n activity: BillActivityRecord[];\n /** Presented history rows. Optional: absent when the API\n * predates the presented-history rollout — fall back to `activity`. */\n history?: BillHistoryEntry[];\n /** Canonical team notes, shared with the MindBill app. Absent on older APIs. */\n notes?: BillTeamNote[];\n /** Immutable submissions that share this bill's unified history. */\n attempts?: BillAttemptSummary[];\n /** Per-attempt details. Older APIs may omit this; never substitute the current bill. */\n submissionDetails?: BillSubmissionDetail[];\n payments: BillPaymentRecord[];\n remittance: BillRemittanceSummary;\n delivery: BillLifecycleDelivery;\n rejection?: BillRejection | null;\n};\n\nexport type BillLifecycleSession = {\n token: string;\n expiresAt?: string;\n apiBaseUrl?: string;\n};\n\nexport type BillLifecycleSessionRequest = {\n signal: AbortSignal;\n};\n\nexport type BillLifecycleSessionProvider = (\n request: BillLifecycleSessionRequest,\n) => Promise<BillLifecycleSession>;\n\nexport type CloseBillInput = BillActorInput & { reason: string };\nexport type ReopenBillInput = BillActorInput & { reason: string };\nexport type PostBillPaymentInput = BillActorInput & {\n amount: number;\n penaltyAmount?: number;\n interestAmount?: number;\n method: \"check\" | \"eft\";\n checkNumber?: string;\n depositDate: string;\n note?: string;\n};\nexport type SecondReviewLineInput = {\n lineItemId: string;\n reason: string;\n /** SBR-1 box for this service line. Omitted leaves the box blank. */\n serviceAuthorized?: boolean;\n /** Absolute corrected values for this Second Review only; charge is explicitly reviewed, never inferred. */\n correction?: { units: number; modifiers: string[]; charge: number };\n};\n\nexport type SubmitSecondReviewInput = BillActorInput & {\n /** @deprecated Prefer `lineItems[].reason`; retained for older hosts. */\n reason?: string;\n /** @deprecated MindBill derives this from the payer response on the server. */\n payerClaimControlNumber?: string;\n disputedAmount?: number;\n attachmentIds: string[];\n route: BillSubmissionRoute;\n /** New PDFs to include with the Second Review. */\n documents?: BrowserBillSubmissionDocument[];\n destination?: SubmitBillInput[\"destination\"];\n attention?: string;\n subject?: string;\n note?: string;\n cc?: string[];\n /** Line-by-line SBR-1 selections, reasons, and authorization answers. */\n lineItems?: SecondReviewLineInput[];\n /** @deprecated Prefer `lineItems`; omitted = the whole bill. */\n lineItemIds?: string[];\n /** @deprecated Prefer `lineItems[].serviceAuthorized`. */\n serviceAuthorized?: boolean;\n};\n\nexport type ReportBillStatusId =\n | \"message_left\"\n | \"eor_pending\"\n | \"eor_sent\"\n | \"bill_not_on_file\"\n | \"forwarded\";\n\nexport type ReportBillStatusOption = {\n id: ReportBillStatusId;\n label: string;\n description: string;\n};\n\n/** The five supported outcomes of a bill payment-status phone call. */\nexport const REPORT_BILL_STATUS_OPTIONS: ReportBillStatusOption[] = [\n {\n id: \"message_left\",\n label: \"Message Left Requesting Bill Payment Status\",\n description: \"Claims Administrator/Bill Review representative unavailable.\",\n },\n {\n id: \"eor_pending\",\n label: \"Explanation of Review (EOR) Pending\",\n description: \"Claims Administrator/Bill Review reported the bill is still in process and an EOR has not been generated or sent.\",\n },\n {\n id: \"eor_sent\",\n label: \"Explanation of Review (EOR) Sent\",\n description: \"Claims Administrator/Bill Review reported sending an EOR to the provider.\",\n },\n {\n id: \"bill_not_on_file\",\n label: \"Bill Not On File\",\n description: \"Claims Administrator/Bill Review reported not receiving the bill.\",\n },\n {\n id: \"forwarded\",\n label: \"Bill Forwarded to Different Payer / Network\",\n description: \"Claims Administrator/Bill Review reported forwarding the bill to a different payer.\",\n },\n];\n\n/**\n * Outcome of a phone call to the Claims Administrator / Bill Review vendor\n * about an outstanding bill, recorded through the lifecycle actions endpoint.\n */\nexport type ReportBillStatusInput = BillActorInput & {\n status: ReportBillStatusId;\n company?: string;\n representativeName?: string;\n representativeRole?: string;\n phone?: string;\n callReference?: string;\n note?: string;\n};\n\n/**\n * Payload for the \"report_bill_status\" lifecycle action: records the outcome\n * of a phone call to the Claims Administrator / Bill Review vendor about an\n * outstanding bill. Posted through the generic lifecycle actions endpoint.\n */\nexport type ReportBillStatusActionInput = ReportBillStatusInput & {\n action: \"report_bill_status\";\n};\n\n/**\n * Payload for the \"send_duplicate\" lifecycle action. A duplicate is a fresh,\n * editable bill snapshot linked to the submitted original. The original stays\n * immutable; the biller must review the snapshot and explicitly confirm its\n * delivery route before this action is posted.\n */\nexport type SendDuplicateBillInput = ResubmitBillInput;\n\nexport type ReportBillStatusContacts = {\n claimsAdmin: {\n name: string;\n hoursOfOperation?: string;\n phones: Array<{ label: string; value: string }>;\n } | null;\n billReview: { name: string; phone?: string } | null;\n};\n\n/**\n * Partner-safe \"who to call\" summary for the Report Bill Status flow, derived\n * from the lifecycle delivery block (payer contacts + optional directory).\n */\nexport function reportBillStatusContacts(\n delivery: BillLifecycleDelivery,\n): ReportBillStatusContacts {\n const payerName = delivery.payerName?.trim();\n const directory = delivery.directory ?? null;\n const phones: Array<{ label: string; value: string }> = [];\n const adjusterPhone = delivery.contacts.adjusterPhone?.trim();\n if (adjusterPhone) {\n const adjusterName = delivery.contacts.adjusterName?.trim();\n phones.push({\n label: adjusterName ? `Adjuster (${adjusterName})` : \"Adjuster\",\n value: adjusterPhone,\n });\n }\n const hours = directory?.hours?.trim();\n const claimsAdmin = payerName\n ? {\n name: payerName,\n ...(hours ? { hoursOfOperation: hours } : {}),\n phones,\n }\n : null;\n const billReviewContact = (directory?.billReview ?? []).find(\n (contact) => contact.name?.trim() || contact.phone?.trim(),\n );\n const billReview = billReviewContact\n ? {\n name: billReviewContact.name?.trim() || \"Bill Review\",\n ...(billReviewContact.phone?.trim() ? { phone: billReviewContact.phone.trim() } : {}),\n }\n : null;\n return { claimsAdmin, billReview };\n}\n\n/**\n * Default Second Bill Review dispute reason for an invalid med-legal denial.\n * Prefilled (editable) in the SBR panel.\n */\nexport const SECOND_REVIEW_REASON_TEMPLATE =\n \"This is an appeal of the invalid denial of this med-legal bill; per LC §4622 and the OMFS/MLFS, payment is due as billed.\";\n\n/** Days allowed to request Second Review after service of the denial EOR. */\nexport const SECOND_REVIEW_WINDOW_DAYS = 90;\n\nexport type SecondReviewDeadline = {\n /** ISO date (yyyy-mm-dd) of the latest denial/EOR document. */\n eorDate: string;\n /** ISO date (yyyy-mm-dd) 90 days after the EOR date. */\n deadline: string;\n};\n\n/**\n * The 90-day Second Review window anchored on the latest EOR date, or null\n * when the lifecycle data provides no parseable denial/EOR date.\n */\nexport function secondReviewDeadline(\n eors: Array<Pick<BillEorDocument, \"addedAt\">>,\n): SecondReviewDeadline | null {\n const times = eors\n .map((eor) => Date.parse(eor.addedAt))\n .filter((time) => Number.isFinite(time));\n if (!times.length) return null;\n const eorTime = Math.max(...times);\n const isoDate = (time: number): string => new Date(time).toISOString().slice(0, 10);\n return {\n eorDate: isoDate(eorTime),\n deadline: isoDate(eorTime + SECOND_REVIEW_WINDOW_DAYS * 86_400_000),\n };\n}\n/**\n * A corrected immutable snapshot submitted as the next attempt on the same bill.\n * The logical bill ID remains stable; only the submission/control-number attempt advances.\n */\nexport type ResubmitBillInput = BillActorInput & {\n reason?: string;\n bill: BrowserBillCreateInput;\n /** Explicit delivery route confirmed by the biller for this new attempt. */\n submission?: Omit<SubmitBillInput, keyof BillActorInput>;\n documents?: BrowserBillSubmissionDocument[];\n};\n/**\n * \"Submit New Bill\" from a CLOSED bill: the same snapshot payload shape as a\n * resubmission, but the server creates a FRESH original bill linked to the closed\n * predecessor — the closed bill stays closed and keeps its record, and the\n * submissions ribbon/timeline chains both records.\n */\nexport type SubmitNewBillInput = ResubmitBillInput;\nexport type SandboxSimulationScenario = \"accepted\" | \"rejected\" | \"processed\" | \"denied\" | \"partial_payment\" | \"paid\";\nexport type SimulateSandboxBillInput = {\n scenario: SandboxSimulationScenario;\n amount?: number;\n reasonCode?: string;\n};\n\nexport type BrowserBillAddress = {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n postalCode: string;\n};\n\n/** Complete bill snapshot accepted by the browser create endpoint. */\nexport type BrowserBillCreateInput = {\n externalId?: string;\n billingMode?: \"med_legal\" | \"professional\";\n patient: {\n id?: string;\n externalId?: string;\n firstName: string;\n middleName?: string;\n lastName: string;\n dateOfBirth: string;\n ssn?: string;\n gender?: \"M\" | \"F\" | \"X\";\n phone?: string;\n address: BrowserBillAddress;\n };\n claim: {\n id?: string;\n externalId?: string;\n claimNumber: string;\n adjNumber?: string;\n employer: string;\n dateOfInjury: string;\n injuryState?: string;\n description?: string;\n claimsAdministrator: {\n id: string;\n name: string;\n /** The chosen payer (subpayor) when the claims administrator requires payer selection. */\n payerId?: string;\n };\n };\n service: { date: string; endDate?: string | null; authorizationNumber?: string | null };\n billingProvider: { 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 /** Existing authorized RFA item linked to this service line. */\n rfaItemId?: string;\n }>;\n};\n\n/** Canonical immutable PDF snapshot sent with a bill submission. */\nexport type BrowserBillSubmissionDocument = {\n externalId?: string;\n filename: string;\n description?: string;\n documentType: BillReviewDocumentType;\n /** Opaque PWK report-type code selected by the component (for example OZ:J4). */\n reportTypeCode?: string;\n contentBase64: string;\n};\n\nexport type BrowserBillSubmissionInput = BillActorInput & {\n 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 BillProcedureCodeSearchInput = {\n query?: string;\n limit?: number;\n jurisdiction?: \"CA\" | \"NY\" | \"OWCP\";\n};\n\n/** Catalog membership does not imply that a fee is available for a service date. */\nexport type BillProcedureCodePage = {\n results: Array<{ code: string }>;\n total: number;\n limit: number;\n jurisdiction: \"CA\" | \"NY\" | \"OWCP\";\n catalogAsOf: string | null;\n};\n\nexport type BillFeeSource = {\n id: string;\n url: string;\n sha256?: string;\n effectiveFrom: string;\n effectiveThrough: string;\n};\n\nexport type BillFeeQuoteInput = {\n code: string;\n dateOfService: string;\n chargeCents?: number;\n units?: number;\n modifiers?: string[];\n pages?: number;\n reportKind?: \"progress\" | \"permanent_stationary_pr3\" | \"permanent_stationary_pr4\";\n hasFeeAgreement?: boolean;\n serviceZip?: string;\n /** Supply verified service facts; omitted context can require review. */\n physicianContext?: {\n providerKind: \"physician\" | \"physician_assistant\" | \"nurse_practitioner\" | \"clinical_nurse_specialist\" | \"other\";\n incidentToPhysicianService?: boolean;\n placeOfService: string;\n standaloneService: boolean;\n globalPeriodApplies: boolean;\n hpsaBonusEligible: boolean;\n };\n therapyContext?: {\n providerKind: \"physical_therapist\" | \"other\";\n personallyPerformed: boolean;\n hospitalPatient: boolean;\n incidentToPhysicianService: boolean;\n assistantInvolved: boolean;\n placeOfService: string;\n directOneOnOneMinutes: number;\n totalVisitMinutes: number;\n visitsOnDate: number;\n completeSameDayServices: boolean;\n otherSameDayServices: boolean;\n globalPeriodApplies: boolean;\n hpsaBonusEligible: boolean;\n };\n reportQualification?:\n | { kind: \"psychiatric_report\"; requestedBy: \"wcab\" | \"administrative_director\"; medicalLegalEvaluation: boolean; reportPayableUnderMedicalLegalSchedule: boolean }\n | { kind: \"consultation_report\"; requestedBy: \"wcab\" | \"administrative_director\" | \"qme\" | \"ame\"; medicalLegalEvaluation: boolean; reportPayableUnderMedicalLegalSchedule: boolean }\n | { kind: \"chart_notes\"; requestedBy: \"claims_administrator\"; writtenRequest: boolean }\n | { kind: \"duplicate_report\"; requestedBy: \"claims_administrator\"; writtenRequest: boolean; relatedToBilling: boolean; initialRequiredCopy: boolean };\n};\n\nexport type BillFeeQuote =\n | {\n status: \"priced\";\n /** Total for the service line in cents, already accounting for units. */\n amountCents: number;\n scheduleMaximumCents: number;\n basis: \"ca_report\" | \"ca_physician_rbrvs\" | \"ca_therapy_rbrvs\";\n provenance: BillFeeSource[];\n notes: string[];\n }\n | { status: \"requires_review\" | \"not_separately_payable\"; reason: string; provenance: BillFeeSource[] };\n\nexport type BillReferenceClient = {\n listClaimsAdministrators: (input?: BillReviewPayerListInput) => Promise<BillReviewPayerPage>;\n searchClaimsAdministrators: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;\n getClaimsAdministratorDirectory: (id: string, injuryState?: string) => Promise<BillClaimsAdministratorDirectory>;\n searchDiagnosisCodes: (query: string, limit?: number, offset?: number) => Promise<BillDiagnosisCode[]>;\n searchProcedureCodes: (input?: BillProcedureCodeSearchInput) => Promise<BillProcedureCodePage>;\n quoteFee: (input: BillFeeQuoteInput) => Promise<BillFeeQuote>;\n lookupPostalCode: (postalCode: string) => Promise<BillPostalPlace | null>;\n /**\n * Delivery-route preview (recommended route + selectable options + payer\n * contacts) for a claims administrator BEFORE the bill exists — powers the\n * send-route picker shown at submit time.\n */\n getDeliveryPreview: (input: BillDeliveryPreviewInput) => Promise<BillDeliveryOptions>;\n clearSession: () => void;\n};\n\nexport type BillLifecycleClient = {\n getBillId: () => string;\n getLifecycle: (signal?: AbortSignal) => Promise<BillLifecycleData>;\n listClaimsAdministrators: (input?: BillReviewPayerListInput) => Promise<BillReviewPayerPage>;\n searchClaimsAdministrators: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;\n getClaimsAdministratorDirectory: (id: string, injuryState?: string) => Promise<BillClaimsAdministratorDirectory>;\n searchDiagnosisCodes: (query: string, limit?: number, offset?: number) => Promise<BillDiagnosisCode[]>;\n searchProcedureCodes: (input?: BillProcedureCodeSearchInput) => Promise<BillProcedureCodePage>;\n quoteFee: (input: BillFeeQuoteInput) => Promise<BillFeeQuote>;\n lookupPostalCode: (postalCode: string) => Promise<BillPostalPlace | null>;\n getDeliveryOptions: () => Promise<BillDeliveryOptions>;\n getDeliveryPreview: (input: BillDeliveryPreviewInput) => Promise<BillDeliveryOptions>;\n getAttachment: (attachmentId: string) => Promise<Blob>;\n getEor: (documentId: string) => Promise<Blob>;\n getPacket: () => Promise<Blob>;\n getSubmissionArtifact: (attemptId: string, artifactId: string) => Promise<Blob>;\n /** Prepare a self-filing packet. Does not file IBR or send anything to a payer. */\n prepareIbrPacket: () => Promise<Blob>;\n previewCourtesyCopy: (input: BillCourtesyCopyInput) => Promise<BillCourtesyCopyPreview>;\n /** Reuse the same key when retrying the same send after a network interruption. */\n sendCourtesyCopy: (input: BillCourtesyCopyInput & { packetHash: string }, idempotencyKey: string) => Promise<BillCourtesyCopyResult>;\n addNote: (input: AddBillNoteInput) => Promise<BillLifecycleData>;\n closeBill: (input: CloseBillInput) => Promise<BillLifecycleData>;\n reopenBill: (input: ReopenBillInput) => Promise<BillLifecycleData>;\n postPayment: (input: PostBillPaymentInput) => Promise<BillLifecycleData>;\n submitSecondReview: (input: SubmitSecondReviewInput) => Promise<BillLifecycleData>;\n resubmitBill: (input: ResubmitBillInput) => Promise<BillLifecycleData>;\n submitNewBill: (input: SubmitNewBillInput) => Promise<BillLifecycleData>;\n sendDuplicateBill: (input: SendDuplicateBillInput) => Promise<BillLifecycleData>;\n reportBillStatus: (input: ReportBillStatusInput) => Promise<BillLifecycleData>;\n simulateSandbox: (input: SimulateSandboxBillInput) => Promise<BillLifecycleData>;\n clearSession: () => void;\n};\n\nasync function responseError(response: Response, fallback: string): Promise<Error> {\n const body: unknown = await response.json().catch(() => null);\n const detail = body && typeof body === \"object\"\n ? (body as { detail?: unknown; message?: unknown; error?: unknown }).detail\n ?? (body as { message?: unknown }).message\n ?? (body as { error?: unknown }).error\n : null;\n return new Error(typeof detail === \"string\" ? detail : fallback);\n}\n\nfunction isSessionFresh(session: BillLifecycleSession | null): boolean {\n if (!session) return false;\n if (!session.expiresAt) return true;\n const expiresAt = new Date(session.expiresAt).getTime();\n return Number.isFinite(expiresAt) && expiresAt > Date.now() + 30_000;\n}\n\nfunction normalizeSession(value: unknown): BillLifecycleSession {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing session endpoint returned an invalid response.\");\n }\n const candidate = value as { token?: unknown; expiresAt?: unknown; apiBaseUrl?: unknown; session?: unknown; data?: unknown };\n const nested = candidate.session ?? candidate.data;\n const session = nested && typeof nested === \"object\" ? nested as typeof candidate : candidate;\n if (typeof session.token !== \"string\" || session.token.length < 8) {\n throw new Error(\"The billing session endpoint did not return a browser session token.\");\n }\n return {\n token: session.token,\n ...(typeof session.expiresAt === \"string\" ? { expiresAt: session.expiresAt } : {}),\n ...(typeof session.apiBaseUrl === \"string\" ? { apiBaseUrl: session.apiBaseUrl } : {}),\n };\n}\n\nfunction normalizeLifecycle(value: unknown): BillLifecycleData {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n const data = value as Partial<BillLifecycleData>;\n if (\n ![\"sandbox\", \"live\"].includes(data.environment ?? \"\")\n || !data.bill\n || !data.patient\n || !data.injury\n || !data.lifecycle\n || !Array.isArray(data.lifecycle.actions)\n || !Array.isArray(data.eors)\n || !Array.isArray(data.activity)\n || !Array.isArray(data.payments)\n || !data.remittance\n || typeof data.remittance !== \"object\"\n || !data.delivery\n || typeof data.delivery !== \"object\"\n || !data.delivery.contacts\n || typeof data.delivery.contacts !== \"object\"\n || (data.rejection != null && (\n typeof data.rejection !== \"object\"\n || typeof data.rejection.reason !== \"string\"\n || (data.rejection.issues != null && (\n !Array.isArray(data.rejection.issues)\n || data.rejection.issues.some((issue) => (\n !issue\n || typeof issue !== \"object\"\n || typeof issue.description !== \"string\"\n || (issue.code != null && typeof issue.code !== \"string\")\n ))\n ))\n ))\n ) {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n return data as BillLifecycleData;\n}\n\nfunction normalizeDeliveryOptions(value: unknown): BillDeliveryOptions {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n const data = value as Partial<BillDeliveryOptions>;\n if (\n typeof data.payerName !== \"string\"\n || !data.recommended\n || typeof data.recommended !== \"object\"\n || ![\"ebill\", \"fax\", \"mail\", \"email\"].includes(data.recommended.route ?? \"\")\n || !Array.isArray(data.options)\n || !data.contacts\n ) {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n return data as BillDeliveryOptions;\n}\n\nfunction idempotencyKey(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") return globalThis.crypto.randomUUID();\n return `mb-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Browser-safe client for one atomic create-and-submit operation.\n *\n * The browser session is short-lived and origin-bound. The host application\n * never needs the Partner API document schema or a long-lived API key.\n */\nexport function createBillSubmissionClient({\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillSubmissionClientOptions = {}): BillSubmissionClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const submitBill = async (\n input: BrowserBillSubmissionInput,\n options: { idempotencyKey?: string } = {},\n ): Promise<BrowserBillSubmissionResult> => {\n const controller = new AbortController();\n const requestIdempotencyKey = options.idempotencyKey ?? idempotencyKey();\n let browserSession = await mintSession(controller.signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n return fetcher(`${base}/partner/v2/bills`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${current.token}`,\n \"content-type\": \"application/json\",\n \"idempotency-key\": requestIdempotencyKey,\n },\n body: JSON.stringify(input),\n signal: controller.signal,\n });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(controller.signal, true);\n response = await perform(browserSession);\n }\n if (!response.ok) throw await responseError(response, \"The bill could not be submitted.\");\n const body: unknown = await response.json().catch(() => null);\n const envelope = body && typeof body === \"object\" && \"data\" in body\n ? (body as { data?: unknown }).data\n : body;\n if (!envelope || typeof envelope !== \"object\" || typeof (envelope as { id?: unknown }).id !== \"string\") {\n throw new Error(\"The billing service submitted the bill but returned an invalid bill ID.\");\n }\n const bill = envelope as BrowserSubmittedBill;\n return { billId: bill.id, bill };\n };\n\n return {\n submitBill,\n clearSession() { session = null; sessionRequest = null; },\n };\n}\n\n/** Browser-safe, framework-neutral client for an already-submitted bill. */\nexport function createBillLifecycleClient({\n billId,\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillLifecycleClientOptions): BillLifecycleClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n const currentBillId = billId.trim();\n if (!currentBillId) throw new Error(\"billId is required for the submitted-bill lifecycle client.\");\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const request = async (path: string, init: RequestInit = {}, providedSignal?: AbortSignal): Promise<Response> => {\n const controller = providedSignal ? null : new AbortController();\n const signal = providedSignal ?? controller?.signal;\n if (!signal) throw new Error(\"An AbortSignal could not be created.\");\n let browserSession = await mintSession(signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n const headers = new Headers(init.headers);\n headers.set(\"authorization\", `Bearer ${current.token}`);\n return fetcher(`${base}${path}`, { ...init, headers, signal });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(signal, true);\n response = await perform(browserSession);\n }\n return response;\n };\n\n const billPath = (suffix = \"\"): string =>\n `/partner/v2/bills/${encodeURIComponent(currentBillId)}${suffix}`;\n\n const loadLifecycle = async (signal?: AbortSignal) => {\n const response = await request(billPath(\"/lifecycle\"), {}, signal);\n if (!response.ok) throw await responseError(response, \"Bill lifecycle could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n\n const listClaimsAdministrators = async (input: BillReviewPayerListInput = {}): Promise<BillReviewPayerPage> => {\n const params = new URLSearchParams();\n if (input.query?.trim()) params.set(\"q\", input.query.trim());\n if (input.claimNumber?.trim()) params.set(\"claimNumber\", input.claimNumber.trim());\n if (input.sourceClaimsAdministratorName?.trim()) params.set(\"sourceClaimsAdministratorName\", input.sourceClaimsAdministratorName.trim());\n if (input.employerName?.trim()) params.set(\"employerName\", input.employerName.trim());\n const limit = Math.max(1, Math.min(100, Math.floor(input.limit ?? 50)));\n const offset = Math.max(0, Math.floor(input.offset ?? 0));\n params.set(\"limit\", String(limit));\n if (offset) params.set(\"offset\", String(offset));\n const response = await request(`/partner/v2/claims-administrators?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator search is unavailable.\");\n const body = await response.json() as { results?: unknown; suggestions?: unknown; total?: unknown; nextOffset?: unknown; recommendedId?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Claims administrator search returned an invalid response.\");\n const normalizePayer = (value: unknown): BillReviewPayer | null => {\n if (!value || typeof value !== \"object\") return null;\n const payer = value as Record<string, unknown>;\n if (typeof payer.id !== \"string\" || typeof payer.name !== \"string\") return null;\n const payers = Array.isArray(payer.payers) ? payer.payers.flatMap((option): BillReviewPayerOption[] => {\n if (!option || typeof option !== \"object\") return [];\n const candidate = option as Record<string, unknown>;\n const id = typeof candidate.id === \"string\" ? candidate.id : typeof candidate.key === \"string\" ? candidate.key : null;\n if (!id || typeof candidate.label !== \"string\") return [];\n return [{\n id,\n label: candidate.label,\n ...(typeof candidate.default === \"boolean\" ? { default: candidate.default } : {}),\n ...(typeof candidate.active === \"boolean\" ? { active: candidate.active } : {}),\n ...(Array.isArray(candidate.aliases) ? { aliases: candidate.aliases.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof candidate.hint === \"string\" ? { hint: candidate.hint } : {}),\n ...(Array.isArray(candidate.affiliatedEntities) ? { affiliatedEntities: candidate.affiliatedEntities.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof candidate.route === \"string\" ? { route: candidate.route } : {}),\n ...(typeof candidate.optionType === \"string\" ? { optionType: candidate.optionType } : {}),\n ...(typeof candidate.deliveryType === \"string\" ? { deliveryType: candidate.deliveryType } : {}),\n ...(typeof candidate.clearinghouse === \"string\" ? { clearinghouse: candidate.clearinghouse } : {}),\n ...(typeof candidate.payerId === \"string\" ? { payerId: candidate.payerId } : {}),\n ...(typeof candidate.sourceClearinghouse === \"string\" ? { sourceClearinghouse: candidate.sourceClearinghouse } : {}),\n ...(typeof candidate.sourcePayerId === \"string\" ? { sourcePayerId: candidate.sourcePayerId } : {}),\n ...(candidate.clearinghousePayerIds && typeof candidate.clearinghousePayerIds === \"object\" && !Array.isArray(candidate.clearinghousePayerIds)\n ? { clearinghousePayerIds: Object.fromEntries(Object.entries(candidate.clearinghousePayerIds).filter((entry): entry is [string, string] => typeof entry[1] === \"string\")) }\n : {}),\n ...(typeof candidate.preferredClearinghouse === \"string\" ? { preferredClearinghouse: candidate.preferredClearinghouse } : {}),\n }];\n }) : undefined;\n const claimNumberPatterns = Array.isArray(payer.claimNumberPatterns) ? payer.claimNumberPatterns.flatMap((value): BillClaimsAdministratorPattern[] => {\n if (!value || typeof value !== \"object\") return [];\n const pattern = value as Record<string, unknown>;\n if (typeof pattern.pattern !== \"string\") return [];\n return [{\n pattern: pattern.pattern,\n ...(typeof pattern.length === \"string\" || typeof pattern.length === \"number\" ? { length: pattern.length } : {}),\n ...(typeof pattern.example === \"string\" ? { example: pattern.example } : {}),\n ...(typeof pattern.matches === \"boolean\" || pattern.matches === null ? { matches: pattern.matches as boolean | null } : {}),\n }];\n }) : undefined;\n return {\n id: payer.id,\n name: payer.name,\n ...(typeof payer.hasElectronic === \"boolean\" ? { hasElectronic: payer.hasElectronic } : {}),\n ...(Array.isArray(payer.states) ? { states: payer.states.filter((state): state is string => typeof state === \"string\") } : {}),\n ...([\"high\", \"medium\", \"directory\"].includes(String(payer.confidence)) ? { confidence: payer.confidence as NonNullable<BillReviewPayer[\"confidence\"]> } : {}),\n ...(typeof payer.recommended === \"boolean\" ? { recommended: payer.recommended } : {}),\n ...(typeof payer.payerSelectionRequired === \"boolean\" ? { payerSelectionRequired: payer.payerSelectionRequired } : {}),\n ...(payers ? { payers } : {}),\n ...(Array.isArray(payer.aliases) ? { aliases: payer.aliases.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(Array.isArray(payer.affiliatedEntities) ? { affiliatedEntities: payer.affiliatedEntities.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof payer.claimNumberHint === \"string\" ? { claimNumberHint: payer.claimNumberHint } : {}),\n ...(claimNumberPatterns ? { claimNumberPatterns } : {}),\n ...(typeof payer.route === \"string\" ? { route: payer.route } : {}),\n ...(Array.isArray(payer.signals) ? { signals: payer.signals.flatMap((signal) => {\n if (!signal || typeof signal !== \"object\") return [];\n const candidate = signal as Record<string, unknown>;\n if (![\"name\", \"claim_number\"].includes(String(candidate.kind)) || ![\"match\", \"warning\"].includes(String(candidate.state)) || typeof candidate.label !== \"string\") return [];\n return [{ kind: candidate.kind as \"name\" | \"claim_number\", state: candidate.state as \"match\" | \"warning\", label: candidate.label }];\n }) } : {}),\n };\n };\n const results = body.results.flatMap((value): BillReviewPayer[] => {\n const payer = normalizePayer(value);\n return payer ? [payer] : [];\n });\n const suggestions = Array.isArray(body.suggestions) ? body.suggestions.flatMap((value): BillReviewPayerSuggestion[] => {\n const payer = normalizePayer(value);\n if (!payer || !value || typeof value !== \"object\") return [];\n const suggestion = value as Record<string, unknown>;\n if (typeof suggestion.deterministic !== \"boolean\" || typeof suggestion.reason !== \"string\") return [];\n return [{ ...payer, deterministic: suggestion.deterministic, reason: suggestion.reason, ...(typeof suggestion.selectedPayerId === \"string\" ? { selectedPayerId: suggestion.selectedPayerId } : {}) }];\n }) : [];\n const total = typeof body.total === \"number\" && Number.isFinite(body.total) ? Math.max(results.length, Math.floor(body.total)) : offset + results.length;\n return {\n results,\n ...(suggestions.length ? { suggestions } : {}),\n total,\n ...(typeof body.nextOffset === \"number\" && Number.isFinite(body.nextOffset) ? { nextOffset: Math.floor(body.nextOffset) } : {}),\n ...(typeof body.recommendedId === \"string\" ? { recommendedId: body.recommendedId } : {}),\n };\n };\n\n const searchClaimsAdministrators = async (query: string, claimNumber?: string): Promise<BillReviewPayer[]> =>\n (await listClaimsAdministrators({ query, ...(claimNumber ? { claimNumber } : {}) })).results;\n\n const getClaimsAdministratorDirectory = async (id: string, injuryState?: string): Promise<BillClaimsAdministratorDirectory> => {\n const params = new URLSearchParams();\n if (injuryState?.trim()) params.set(\"injuryState\", injuryState.trim());\n const response = await request(`/partner/v2/claims-administrators/${encodeURIComponent(id)}${params.size ? `?${params}` : \"\"}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator details are unavailable.\");\n const body = await response.json() as { data?: unknown };\n if (!body.data || typeof body.data !== \"object\") throw new Error(\"Claims administrator details returned an invalid response.\");\n return body.data as BillClaimsAdministratorDirectory;\n };\n\n const searchDiagnosisCodes = async (query: string, limit = 30, offset = 0): Promise<BillDiagnosisCode[]> => {\n const params = new URLSearchParams({ q: query.trim(), limit: String(Math.max(1, Math.min(100, limit))) });\n if (offset > 0) params.set(\"offset\", String(Math.max(0, Math.floor(offset))));\n const response = await request(`/partner/v2/diagnosis-codes?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Diagnosis-code search is unavailable.\");\n const body = await response.json() as { results?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Diagnosis-code search returned an invalid response.\");\n return body.results.flatMap((value): BillDiagnosisCode[] => {\n if (!value || typeof value !== \"object\") return [];\n const candidate = value as { code?: unknown; description?: unknown };\n return typeof candidate.code === \"string\" && typeof candidate.description === \"string\"\n ? [{ code: candidate.code, description: candidate.description }]\n : [];\n });\n };\n\n const searchProcedureCodes = async (input: BillProcedureCodeSearchInput = {}): Promise<BillProcedureCodePage> => {\n const limit = Number.isFinite(input.limit) ? Math.max(1, Math.min(100, Math.floor(input.limit!))) : 30;\n const params = new URLSearchParams({ q: input.query?.trim() ?? \"\", limit: String(limit), jurisdiction: input.jurisdiction?.trim().toUpperCase() || \"CA\" });\n const response = await request(`/partner/v2/procedure-codes?${params}`);\n if (!response.ok) throw await responseError(response, \"Procedure-code search is unavailable.\");\n const body = await response.json() as Partial<BillProcedureCodePage>;\n if (!Array.isArray(body.results) || typeof body.total !== \"number\" || !Number.isFinite(body.total) || body.total < 0 || typeof body.limit !== \"number\" || !Number.isFinite(body.limit) || body.limit < 1 || ![\"CA\", \"NY\", \"OWCP\"].includes(body.jurisdiction ?? \"\") || !(body.catalogAsOf === null || typeof body.catalogAsOf === \"string\")) {\n throw new Error(\"Procedure-code search returned an invalid response.\");\n }\n return {\n results: body.results.flatMap((entry) => entry && typeof entry.code === \"string\" && entry.code.trim() ? [{ code: entry.code }] : []),\n total: body.total,\n limit: body.limit,\n jurisdiction: body.jurisdiction!,\n catalogAsOf: body.catalogAsOf,\n };\n };\n\n const quoteFee = async (input: BillFeeQuoteInput): Promise<BillFeeQuote> => {\n const response = await request(\"/partner/v2/fee-quotes\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n });\n if (!response.ok) throw await responseError(response, \"Fee-schedule pricing is unavailable.\");\n const body = await response.json() as { data?: BillFeeQuote };\n const quote = body.data;\n if (!quote || !Array.isArray(quote.provenance)) throw new Error(\"Fee quote returned an invalid response.\");\n if (quote.status === \"priced\") {\n if (!Number.isSafeInteger(quote.amountCents) || quote.amountCents < 0 || !Number.isSafeInteger(quote.scheduleMaximumCents) || quote.scheduleMaximumCents < 0 || ![\"ca_report\", \"ca_physician_rbrvs\", \"ca_therapy_rbrvs\"].includes(quote.basis) || !Array.isArray(quote.notes) || quote.notes.some((note) => typeof note !== \"string\")) throw new Error(\"Fee quote returned an invalid response.\");\n } else if ((quote.status !== \"requires_review\" && quote.status !== \"not_separately_payable\") || typeof quote.reason !== \"string\") {\n throw new Error(\"Fee quote returned an invalid response.\");\n }\n return quote;\n };\n\n const lookupPostalCode = async (postalCode: string): Promise<BillPostalPlace | null> => {\n const params = new URLSearchParams({ postalCode: postalCode.trim() });\n const response = await request(`/partner/v2/postal-codes?${params.toString()}`);\n if (response.status === 404) return null;\n if (!response.ok) throw await responseError(response, \"ZIP lookup is unavailable.\");\n const body = await response.json() as { city?: unknown; state?: unknown };\n if (typeof body.city !== \"string\" || typeof body.state !== \"string\") {\n throw new Error(\"ZIP lookup returned an invalid response.\");\n }\n return { city: body.city, state: body.state };\n };\n\n const mutation = async (path: string, init: RequestInit, fallback: string) => {\n const headers = new Headers(init.headers);\n headers.set(\"idempotency-key\", idempotencyKey());\n const response = await request(path, { ...init, headers });\n if (!response.ok) throw await responseError(response, fallback);\n return response;\n };\n const action = async (input: Record<string, unknown>, fallback: string): Promise<BillLifecycleData> => {\n const response = await mutation(billPath(\"/actions\"), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, fallback);\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n const simulateSandbox = async (input: SimulateSandboxBillInput): Promise<BillLifecycleData> => {\n await mutation(`/partner/v2/sandbox/bills/${encodeURIComponent(currentBillId)}/simulate`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, \"Sandbox lifecycle could not be simulated.\");\n return loadLifecycle();\n };\n return {\n getBillId() { return currentBillId; },\n clearSession() { session = null; sessionRequest = null; },\n getLifecycle: loadLifecycle,\n listClaimsAdministrators,\n searchClaimsAdministrators,\n getClaimsAdministratorDirectory,\n searchDiagnosisCodes,\n searchProcedureCodes,\n quoteFee,\n lookupPostalCode,\n async getDeliveryOptions() {\n const response = await request(billPath(\"/delivery-options\"));\n if (!response.ok) throw await responseError(response, \"Delivery options could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getDeliveryPreview(input) {\n const params = new URLSearchParams({ claimsAdministratorId: input.claimsAdministratorId.trim() });\n if (input.payerId?.trim()) params.set(\"payerId\", input.payerId.trim());\n if (input.injuryState?.trim()) params.set(\"injuryState\", input.injuryState.trim());\n const response = await request(`/partner/v2/delivery-preview?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Delivery routes could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getAttachment(attachmentId) {\n const response = await request(billPath(`/documents/${encodeURIComponent(attachmentId)}`));\n if (!response.ok) throw await responseError(response, \"Document could not be opened.\");\n return response.blob();\n },\n async getEor(documentId) {\n const response = await request(billPath(`/eors/${encodeURIComponent(documentId)}`));\n if (!response.ok) throw await responseError(response, \"EOR could not be opened.\");\n return response.blob();\n },\n async getPacket() {\n const response = await request(billPath(\"/packet\"));\n if (!response.ok) throw await responseError(response, \"Submission packet could not be downloaded.\");\n return response.blob();\n },\n async getSubmissionArtifact(attemptId, artifactId) {\n const response = await request(billPath(`/submissions/${encodeURIComponent(attemptId)}/artifacts/${encodeURIComponent(artifactId)}`));\n if (!response.ok) throw await responseError(response, \"The retained submission file could not be downloaded.\");\n return response.blob();\n },\n async prepareIbrPacket() {\n const prepared = await mutation(billPath(\"/actions\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ action: \"independent_bill_review\" }),\n }, \"IBR packet could not be prepared.\");\n const body = await prepared.json() as { packetUrl?: unknown };\n // Never forward the browser bearer token to an arbitrary response URL.\n if (typeof body.packetUrl !== \"string\" || !/^\\/partner\\/v2\\/(?:browser\\/)?bills\\/[A-Za-z0-9_-]+\\/ibr-packet$/.test(body.packetUrl)) throw new Error(\"The billing service returned an invalid IBR packet path.\");\n // The server may resolve a root bill to its current linked bill.\n const response = await request(body.packetUrl);\n if (!response.ok) throw await responseError(response, \"IBR packet could not be downloaded.\");\n return response.blob();\n },\n async previewCourtesyCopy(input) {\n const response = await request(billPath(\"/courtesy-forward\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ ...input, mode: \"preview\" }),\n });\n if (!response.ok) throw await responseError(response, \"Courtesy copy could not be previewed.\");\n return response.json() as Promise<BillCourtesyCopyPreview>;\n },\n async sendCourtesyCopy(input, key) {\n if (!key.trim() || key.length > 255) throw new Error(\"A stable idempotency key is required to send a courtesy copy.\");\n const response = await request(billPath(\"/courtesy-forward\"), {\n method: \"POST\", headers: { \"content-type\": \"application/json\", \"idempotency-key\": key },\n body: JSON.stringify({ ...input, mode: \"send\" }),\n });\n if (!response.ok) throw await responseError(response, \"Courtesy copy could not be sent. Retry with the same key to check the result safely.\");\n return response.json() as Promise<BillCourtesyCopyResult>;\n },\n addNote(input) { return action({ action: \"add_note\", ...input }, \"Note could not be added.\"); },\n closeBill(input) { return action({ action: \"close\", ...input }, \"Bill could not be closed.\"); },\n reopenBill(input) { return action({ action: \"reopen\", ...input }, \"Bill could not be reopened.\"); },\n postPayment(input) { return action({ action: \"post_payment\", penaltyAmount: 0, interestAmount: 0, ...input, checkNumber: input.checkNumber ?? \"\" }, \"Payment could not be posted.\"); },\n submitSecondReview(input) { return action({ action: \"second_review\", ...input }, \"Second Review could not be submitted.\"); },\n resubmitBill(input) { return action({ action: \"resubmit\", ...input }, \"Bill could not be resubmitted.\"); },\n submitNewBill(input) { return action({ action: \"submit_new_bill\", ...input }, \"The new bill could not be submitted.\"); },\n sendDuplicateBill(input) { return action({ action: \"send_duplicate\", ...input }, \"Duplicate bill could not be sent.\"); },\n reportBillStatus(input) { return action({ action: \"report_bill_status\", ...input }, \"Bill status could not be reported.\"); },\n simulateSandbox,\n };\n}\n\n/**\n * Browser-safe client for reference data needed before a bill exists.\n *\n * Partners can pass the same short-lived session provider used by the submitted-bill\n * lifecycle without inventing a draft bill or exposing payer directory credentials.\n */\nexport function createBillReferenceClient(\n options: BillReferenceClientOptions = {},\n): BillReferenceClient {\n const lifecycle = createBillLifecycleClient({\n ...options,\n billId: \"pre-submission-reference-data\",\n });\n return {\n listClaimsAdministrators: lifecycle.listClaimsAdministrators,\n searchClaimsAdministrators: lifecycle.searchClaimsAdministrators,\n getClaimsAdministratorDirectory: lifecycle.getClaimsAdministratorDirectory,\n searchDiagnosisCodes: lifecycle.searchDiagnosisCodes,\n searchProcedureCodes: lifecycle.searchProcedureCodes,\n quoteFee: lifecycle.quoteFee,\n 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/organization\"),\n getBillingProfile: () => request(\"/partner/v2/organization/billing-profile\"),\n saveBillingProfile: (input) =>\n request(\"/partner/v2/organization/billing-profile\", { method: \"PUT\", body: JSON.stringify({\n ...input,\n ...(input.practiceIdentity ? { practiceIdentity: organizationTaxIdWrite(input.practiceIdentity) } : {}),\n ...(input.billingProviders ? { billingProviders: input.billingProviders.map(organizationTaxIdWrite) } : {}),\n }) }),\n saveLocations: (locations) =>\n request(\"/partner/v2/organization/locations\", { method: \"PUT\", body: JSON.stringify({ locations }) }),\n saveW9: (input) =>\n request(\"/partner/v2/organization/w9\", { method: \"PUT\", body: JSON.stringify(input) }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Bill Tasks dashboard: a pure, framework-neutral\n// aggregation shared by the React and Angular components. Hosts flatten their\n// own work items and get back per-section rows bucketed by age in days.\n\nexport type BillTasksAgingBucket = {\n id: string;\n label: string;\n /** Exclusive lower bound in days. The first bucket also admits day 0. */\n minDays: number;\n /** Inclusive upper bound in days; null means unbounded. */\n maxDays: number | null;\n};\n\nexport const BILL_TASKS_AGING_BUCKETS: BillTasksAgingBucket[] = [\n { id: \"1-30\", label: \"1-30 Days Ago\", minDays: 0, maxDays: 30 },\n { id: \"31-60\", label: \"31-60 Days Ago\", minDays: 30, maxDays: 60 },\n { id: \"61-90\", label: \"61-90 Days Ago\", minDays: 60, maxDays: 90 },\n { id: \"91-180\", label: \"91-180 Days Ago\", minDays: 90, maxDays: 180 },\n { id: \"181+\", label: \"181+ Days Ago\", minDays: 180, maxDays: null },\n];\n\nexport type BillTasksDashboardItem = {\n sectionId: string;\n rowId: string;\n rowLabel: string;\n ageDays: number;\n balanceDue?: number;\n /** Opaque bill reference echoed back in click-through payloads. */\n ref?: string;\n};\n\nexport type BillTasksDashboardRow = {\n id: string;\n label: string;\n /** One count per aging bucket, in bucket order. */\n counts: number[];\n total: number;\n /** Summed item balanceDue per bucket; optional for older count-only payloads. */\n balances?: number[];\n balanceTotal?: number;\n /** Collected item refs per aging bucket, in bucket order. */\n refs: string[][];\n};\n\nexport type BillTasksDashboardTone = \"violet\" | \"red\" | \"blue\" | \"green\" | \"amber\" | \"neutral\";\n\nexport type BillTasksDashboardSectionInput = {\n id: string;\n label: string;\n /** Shown under the section label as \"by {agingBasisLabel}\". */\n agingBasisLabel: string;\n tone: BillTasksDashboardTone;\n};\n\nexport type BillTasksDashboardSection = BillTasksDashboardSectionInput & {\n rows: BillTasksDashboardRow[];\n /** Per-bucket totals across the section's rows. */\n totals: number[];\n total: number;\n balanceTotals?: number[];\n balanceTotal?: number;\n empty: boolean;\n};\n\nexport type BillTasksDashboardData = {\n sections: BillTasksDashboardSection[];\n grandTotals: number[];\n grandTotal: number;\n /** Work-item sums, not deduplicated financial A/R across task categories. */\n grandBalanceTotals?: number[];\n grandBalanceTotal?: number;\n};\n\n/**\n * Bucket index for an item age: a bucket admits `minDays < ageDays <= maxDays`\n * (`maxDays: null` = unbounded) and the first bucket also admits day 0.\n * Ages beyond every bucket clamp into the last bucket.\n */\nexport function billTasksAgingBucketIndex(\n ageDays: number,\n buckets: BillTasksAgingBucket[] = BILL_TASKS_AGING_BUCKETS,\n): number {\n const days = Math.max(0, Math.floor(ageDays));\n const index = buckets.findIndex((bucket, position) =>\n (bucket.maxDays === null || days <= bucket.maxDays)\n && (days > bucket.minDays || position === 0));\n return index === -1 ? buckets.length - 1 : index;\n}\n\n/**\n * Aggregates flat work items into the Bill Tasks dashboard.\n * Sections render in the given order even when empty; rows appear in\n * first-seen item order within their section.\n */\nexport function buildBillTasksDashboard(\n items: BillTasksDashboardItem[],\n sections: BillTasksDashboardSectionInput[],\n buckets: BillTasksAgingBucket[] = BILL_TASKS_AGING_BUCKETS,\n): BillTasksDashboardData {\n const zeros = () => buckets.map(() => 0);\n const built = sections.map((section): BillTasksDashboardSection => ({\n ...section,\n rows: [],\n totals: zeros(),\n total: 0,\n balanceTotals: zeros(),\n balanceTotal: 0,\n empty: true,\n }));\n const sectionById = new Map(built.map((section) => [section.id, section]));\n const rowByKey = new Map<string, BillTasksDashboardRow>();\n const grandTotals = zeros();\n let grandTotal = 0;\n const grandBalanceTotals = zeros();\n let grandBalanceTotal = 0;\n\n for (const item of items) {\n const section = sectionById.get(item.sectionId);\n if (!section) continue;\n const key = `${item.sectionId}\\u0000${item.rowId}`;\n let row = rowByKey.get(key);\n if (!row) {\n row = {\n id: item.rowId,\n label: item.rowLabel,\n counts: zeros(),\n total: 0,\n balances: zeros(),\n balanceTotal: 0,\n refs: buckets.map(() => []),\n };\n rowByKey.set(key, row);\n section.rows.push(row);\n section.empty = false;\n }\n const bucketIndex = billTasksAgingBucketIndex(item.ageDays, buckets);\n const balance = Number.isFinite(item.balanceDue) ? item.balanceDue! : 0;\n row.counts[bucketIndex] = (row.counts[bucketIndex] ?? 0) + 1;\n row.total += 1;\n row.balances![bucketIndex] = (row.balances![bucketIndex] ?? 0) + balance;\n row.balanceTotal = (row.balanceTotal ?? 0) + balance;\n if (item.ref) row.refs[bucketIndex]?.push(item.ref);\n section.totals[bucketIndex] = (section.totals[bucketIndex] ?? 0) + 1;\n section.total += 1;\n section.balanceTotals![bucketIndex] = (section.balanceTotals![bucketIndex] ?? 0) + balance;\n section.balanceTotal = (section.balanceTotal ?? 0) + balance;\n grandTotals[bucketIndex] = (grandTotals[bucketIndex] ?? 0) + 1;\n grandTotal += 1;\n grandBalanceTotals[bucketIndex] = (grandBalanceTotals[bucketIndex] ?? 0) + balance;\n grandBalanceTotal += balance;\n }\n\n return { sections: built, grandTotals, grandTotal, grandBalanceTotals, grandBalanceTotal };\n}\n"],"mappings":";AAUO,SAAS,4BAA4B,OAA6D;AACvG,MAAI,CAAC,MAAM,eAAgB,QAAO;AAClC,QAAM,QAAQ,OAAO,MAAM,KAAK;AAChC,QAAM,SAAS,OAAO,MAAM,MAAM;AAClC,QAAM,YAAY,MAAM,UAAU,KAAK,EAAE,YAAY,EAAE,MAAM,QAAQ,EAAE,OAAO,OAAO;AACrF,MAAI,CAAC,MAAM,MAAM,KAAK,KAAK,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,KAAK,QAAQ,KAAQ;AAClF,UAAM,IAAI,MAAM,0DAA0D;AAAA,EAC5E;AACA,MAAI,UAAU,SAAS,KAAK,IAAI,IAAI,SAAS,EAAE,SAAS,UAAU,UAAU,UAAU,KAAK,CAAC,UAAU,CAAC,gBAAgB,KAAK,KAAK,CAAC,GAAG;AACnI,UAAM,IAAI,MAAM,wGAAwG;AAAA,EAC1H;AACA,MAAI,CAAC,MAAM,OAAO,KAAK,KAAK,CAAC,OAAO,SAAS,MAAM,KAAK,SAAS,KAAK,SAAS,aAAc,KAAK,IAAI,SAAS,MAAM,KAAK,MAAM,SAAS,GAAG,CAAC,IAAI,MAAU;AACzJ,UAAM,IAAI,MAAM,kDAAkD;AAAA,EACpE;AACA,MAAI,CAAC,MAAM,eAAgB,OAAM,IAAI,MAAM,uFAAuF;AAClI,SAAO,EAAE,OAAO,WAAW,OAAO;AACpC;;;AC1BO,IAAM,uBAAuB;AAC7B,IAAM,2BAA2B;AAmJjC,SAAS,6BACd,OAC8B;AAC9B,MAAI,CAAC,MAAM,uBA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B;AACA,UAAM,cAAc,0BAA0B,KAAK,SAAS,OAAO;AACnE,UAAM,UAAU,OAAO,SAAS,KAAK,UAAU,IAAI,KAAK,aAAc;AACtE,QAAI,OAAO,WAAW,KAAK,IAAI,OAAO,WAAW,KAAK,KAAK;AAC3D,QAAI,SAAS;AACb,QAAI,SAAU,WAAW,KAAK,IAAI,SAAU,WAAW,KAAK,KAAK;AACjE,QAAI,gBAAgB,IAAI,gBAAgB,KAAK;AAC7C,QAAI,KAAK,IAAK,KAAI,KAAK,WAAW,GAAG,KAAK,KAAK,GAAG;AAClD,YAAQ,OAAO,WAAW,KAAK,QAAQ,OAAO,WAAW,KAAK,KAAK;AACnE,YAAQ,SAAS;AACjB,YAAQ,cAAe,WAAW,KAAK,QAAQ,cAAe,WAAW,KAAK,KAAK;AACnF,YAAQ,gBAAgB,QAAQ,gBAAgB,KAAK;AACrD,gBAAY,WAAW,KAAK,YAAY,WAAW,KAAK,KAAK;AAC7D,kBAAc;AACd,uBAAmB,WAAW,KAAK,mBAAmB,WAAW,KAAK,KAAK;AAC3E,yBAAqB;AAAA,EACvB;AAEA,SAAO,EAAE,UAAU,OAAO,aAAa,YAAY,oBAAoB,kBAAkB;AAC3F;","names":["request","value"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mindbill/browser",
3
- "version": "0.29.1",
3
+ "version": "0.31.0",
4
4
  "description": "Framework-neutral browser client for the MindBill bill lifecycle",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",