@mindbill/browser 0.22.0 → 0.23.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/README.md CHANGED
@@ -35,6 +35,11 @@ const references = createBillReferenceClient({
35
35
  sessionEndpoint: "/api/mindbill/session",
36
36
  });
37
37
 
38
+ const firstPayerPage = await references.listClaimsAdministrators({ limit: 50 });
39
+ const nextPayerPage = await references.listClaimsAdministrators({
40
+ limit: 50,
41
+ offset: firstPayerPage.nextOffset,
42
+ });
38
43
  const payers = await references.searchClaimsAdministrators("Zurich", "claim-123");
39
44
  const diagnoses = await references.searchDiagnosisCodes("left knee");
40
45
  const firstAlphabeticalPage = await references.searchDiagnosisCodes("", 100, 0);
@@ -44,13 +49,20 @@ const place = await references.lookupPostalCode("94403");
44
49
 
45
50
  `searchDiagnosisCodes(query, limit, offset)` supports directory browsing as well as search. Pass an empty query for ICD-10 code order; `limit` is capped at 100 and `offset` advances through the directory.
46
51
 
47
- Some claims administrators route bills through more than one payer. Search
48
- results mark them with `payerSelectionRequired: true` and list the choices in
49
- `payers` (`{ id, label, default? }`, with at most one entry marked `default`).
52
+ `listClaimsAdministrators({ query, claimNumber, limit, offset })` supports both
53
+ alphabetical browsing and search, returns `total` and `nextOffset`, and does not
54
+ impose a minimum query length. The legacy `searchClaimsAdministrators` method
55
+ remains as a results-only convenience wrapper.
56
+
57
+ Some claims administrators route bills through more than one payer. Results mark
58
+ them with `payerSelectionRequired: true` and list rich routing choices in `payers`:
59
+ aliases, affiliated entities, claim-number hints, route and delivery type,
60
+ clearinghouse, payer IDs, and the directory default marker are preserved.
50
61
  Send the chosen entry as `bill.claim.claimsAdministrator.payerId` on the atomic
51
62
  submission (the same optional `payerId` exists on `BillReviewSaveInput`);
52
63
  administrators without subpayors are unchanged and need no `payerId`.
53
- `defaultBillReviewPayerOption(payer)` returns the option to preselect.
64
+ Interactive forms should require the user to choose a required routing payer;
65
+ `defaultBillReviewPayerOption(payer)` only reads the source catalog's default marker.
54
66
 
55
67
  Submit a locally reviewed bill and its PDF attachments directly from the browser:
56
68
 
package/dist/index.d.ts CHANGED
@@ -64,13 +64,23 @@ type BillReviewAttachment = {
64
64
  type BillReviewPayerOption = {
65
65
  id: string;
66
66
  label: string;
67
- /** Preselect this payer when the claims administrator is chosen. */
67
+ /** Directory-provided default marker. Interactive forms still require an explicit choice. */
68
68
  default?: boolean;
69
69
  active?: boolean;
70
70
  aliases?: string[];
71
71
  hint?: string | null;
72
72
  affiliatedEntities?: string[];
73
73
  route?: string | null;
74
+ optionType?: string | null;
75
+ deliveryType?: string | null;
76
+ clearinghouse?: string | null;
77
+ payerId?: string | null;
78
+ /** Original directory route when live delivery uses a replacement clearinghouse. */
79
+ sourceClearinghouse?: string | null;
80
+ /** Original directory payer ID when live delivery uses a replacement route. */
81
+ sourcePayerId?: string | null;
82
+ clearinghousePayerIds?: Record<string, string>;
83
+ preferredClearinghouse?: string | null;
74
84
  };
75
85
  type BillReviewPayer = {
76
86
  id: string;
@@ -91,11 +101,26 @@ type BillReviewPayer = {
91
101
  aliases?: string[];
92
102
  affiliatedEntities?: string[];
93
103
  claimNumberHint?: string | null;
104
+ claimNumberPatterns?: BillClaimsAdministratorPattern[];
94
105
  route?: string | null;
95
106
  };
107
+ /** A directory suggestion derived from host-provided evidence. Suggestions are never auto-applied. */
108
+ type BillReviewPayerSuggestion = BillReviewPayer & {
109
+ deterministic: boolean;
110
+ reason: string;
111
+ /** A uniquely proven routing payer under a multi-payer claims administrator. */
112
+ selectedPayerId?: string;
113
+ };
114
+ /** Host-system evidence shown alongside claims-administrator suggestions. */
115
+ type BillClaimsAdministratorSource = {
116
+ source: "eams" | "report" | string;
117
+ label: string;
118
+ name: string;
119
+ url?: string;
120
+ };
96
121
  /**
97
- * The payer option to preselect when a claims administrator that requires
98
- * payer selection is chosen, or null when nothing is marked as the default.
122
+ * The directory-marked default payer option, or null when none is marked.
123
+ * Interactive forms should still require an explicit routing-payer choice.
99
124
  */
100
125
  declare function defaultBillReviewPayerOption(payer: Pick<BillReviewPayer, "payerSelectionRequired" | "payers">): BillReviewPayerOption | null;
101
126
  type BillPostalPlace = {
@@ -375,18 +400,40 @@ type BillClaimsAdministratorMailingAddress = {
375
400
  billTreatmentTypes?: string[];
376
401
  };
377
402
  type BillClaimsAdministratorPattern = {
378
- length?: number | null;
403
+ length?: number | string | null;
379
404
  pattern: string;
380
405
  example?: string | null;
381
406
  matches?: boolean | null;
382
407
  };
383
408
  type BillClaimsAdministratorPayer = {
384
409
  name: string;
385
- daisyBillPayerId?: string | null;
386
410
  route?: string | null;
387
411
  aliases?: string[];
388
412
  hint?: string | null;
389
413
  affiliatedEntities?: string[];
414
+ optionType?: string | null;
415
+ deliveryType?: string | null;
416
+ clearinghouse?: string | null;
417
+ payerId?: string | null;
418
+ sourceClearinghouse?: string | null;
419
+ sourcePayerId?: string | null;
420
+ clearinghousePayerIds?: Record<string, string>;
421
+ preferredClearinghouse?: string | null;
422
+ };
423
+ type BillReviewPayerPage = {
424
+ results: BillReviewPayer[];
425
+ suggestions?: BillReviewPayerSuggestion[];
426
+ total: number;
427
+ nextOffset?: number;
428
+ recommendedId?: string;
429
+ };
430
+ type BillReviewPayerListInput = {
431
+ query?: string;
432
+ claimNumber?: string;
433
+ sourceClaimsAdministratorName?: string;
434
+ employerName?: string;
435
+ limit?: number;
436
+ offset?: number;
390
437
  };
391
438
  type BillClaimsAdministratorDirectory = {
392
439
  id?: string;
@@ -436,7 +483,7 @@ type BillLifecycleData = BillReviewData & {
436
483
  };
437
484
  eors: BillEorDocument[];
438
485
  activity: BillActivityRecord[];
439
- /** daisyBill-style presented history rows. Optional: absent when the API
486
+ /** Presented history rows. Optional: absent when the API
440
487
  * predates the presented-history rollout — fall back to `activity`. */
441
488
  history?: BillHistoryEntry[];
442
489
  payments: BillPaymentRecord[];
@@ -485,7 +532,7 @@ type ReportBillStatusOption = {
485
532
  label: string;
486
533
  description: string;
487
534
  };
488
- /** The five daisyBill-worded outcomes of a bill payment-status phone call. */
535
+ /** The five supported outcomes of a bill payment-status phone call. */
489
536
  declare const REPORT_BILL_STATUS_OPTIONS: ReportBillStatusOption[];
490
537
  /**
491
538
  * Outcome of a phone call to the Claims Administrator / Bill Review vendor
@@ -714,6 +761,7 @@ type BillDeliveryPreviewInput = {
714
761
  injuryState?: string;
715
762
  };
716
763
  type BillReferenceClient = {
764
+ listClaimsAdministrators: (input?: BillReviewPayerListInput) => Promise<BillReviewPayerPage>;
717
765
  searchClaimsAdministrators: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;
718
766
  getClaimsAdministratorDirectory: (id: string, injuryState?: string) => Promise<BillClaimsAdministratorDirectory>;
719
767
  searchDiagnosisCodes: (query: string, limit?: number, offset?: number) => Promise<BillDiagnosisCode[]>;
@@ -729,6 +777,7 @@ type BillReferenceClient = {
729
777
  type BillLifecycleClient = {
730
778
  getBillId: () => string;
731
779
  getLifecycle: (signal?: AbortSignal) => Promise<BillLifecycleData>;
780
+ listClaimsAdministrators: (input?: BillReviewPayerListInput) => Promise<BillReviewPayerPage>;
732
781
  searchClaimsAdministrators: (query: string, claimNumber?: string) => Promise<BillReviewPayer[]>;
733
782
  getClaimsAdministratorDirectory: (id: string, injuryState?: string) => Promise<BillClaimsAdministratorDirectory>;
734
783
  searchDiagnosisCodes: (query: string, limit?: number, offset?: number) => Promise<BillDiagnosisCode[]>;
@@ -899,10 +948,10 @@ type BillTasksDashboardData = {
899
948
  */
900
949
  declare function billTasksAgingBucketIndex(ageDays: number, buckets?: BillTasksAgingBucket[]): number;
901
950
  /**
902
- * Aggregates flat work items into the daisyBill-style Bill Tasks dashboard.
951
+ * Aggregates flat work items into the Bill Tasks dashboard.
903
952
  * Sections render in the given order even when empty; rows appear in
904
953
  * first-seen item order within their section.
905
954
  */
906
955
  declare function buildBillTasksDashboard(items: BillTasksDashboardItem[], sections: BillTasksDashboardSectionInput[], buckets?: BillTasksAgingBucket[]): BillTasksDashboardData;
907
956
 
908
- export { BILL_TASKS_AGING_BUCKETS, type BillActivityRecord, type BillActorInput, type BillClaimsAdministratorContact, type BillClaimsAdministratorDirectory, type BillClaimsAdministratorMailingAddress, type BillClaimsAdministratorPattern, type BillClaimsAdministratorPayer, 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 BillReviewPayerOption, type BillReviewSaveInput, type BillSubmissionClient, type BillSubmissionClientOptions, type BillSubmissionRoute, type BillTasksAgingBucket, type BillTasksDashboardData, type BillTasksDashboardItem, type BillTasksDashboardRow, type BillTasksDashboardSection, type BillTasksDashboardSectionInput, type BillTasksDashboardTone, type BrowserBillAddress, type BrowserBillCreateInput, type BrowserBillSubmissionDocument, type BrowserBillSubmissionInput, type BrowserBillSubmissionResult, type BrowserSubmittedBill, type CloseBillInput, DEFAULT_API_BASE_URL, DEFAULT_SESSION_ENDPOINT, type OrganizationBillingProviderInput, type OrganizationChecklistItem, type OrganizationClient, type OrganizationClientOptions, type OrganizationLocationInput, type OrganizationPracticeIdentity, type OrganizationProfileData, type 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 SendDuplicateBillInput, type SimulateSandboxBillInput, type SubmitBillInput, type SubmitNewBillInput, type SubmitSecondReviewInput, billTasksAgingBucketIndex, buildBillTasksDashboard, createBillLifecycleClient, createBillReferenceClient, createBillSubmissionClient, createOrganizationClient, defaultBillReviewPayerOption, reportBillStatusContacts, sanitizeBillReviewSaveInput, secondReviewDeadline };
957
+ export { BILL_TASKS_AGING_BUCKETS, type BillActivityRecord, type BillActorInput, type BillClaimsAdministratorContact, type BillClaimsAdministratorDirectory, type BillClaimsAdministratorMailingAddress, type BillClaimsAdministratorPattern, type BillClaimsAdministratorPayer, type BillClaimsAdministratorSource, type BillDeliveryOption, type BillDeliveryOptions, type BillDeliveryPreviewInput, type BillDiagnosisCode, type BillEorDocument, type BillHistoryEntry, type BillLifecycleAction, type BillLifecycleActionId, type BillLifecycleClient, type BillLifecycleClientOptions, type BillLifecycleData, type BillLifecycleDelivery, type BillLifecycleSession, type BillLifecycleSessionProvider, type BillLifecycleSessionRequest, type BillPaymentRecord, type BillPostalPlace, type BillReferenceClient, type BillReferenceClientOptions, type BillRejection, type BillRejectionIssue, type BillRemittanceSummary, type BillReviewAttachment, type BillReviewBillingProvider, type BillReviewClaimPatternStatus, type BillReviewClinician, type BillReviewData, type BillReviewDocumentType, type BillReviewFeatures, type BillReviewLineItem, type BillReviewLocation, type BillReviewPayer, type BillReviewPayerListInput, type BillReviewPayerOption, type BillReviewPayerPage, type BillReviewPayerSuggestion, type BillReviewSaveInput, type BillSubmissionClient, type BillSubmissionClientOptions, type BillSubmissionRoute, type BillTasksAgingBucket, type BillTasksDashboardData, type BillTasksDashboardItem, type BillTasksDashboardRow, type BillTasksDashboardSection, type BillTasksDashboardSectionInput, type BillTasksDashboardTone, type BrowserBillAddress, type BrowserBillCreateInput, type BrowserBillSubmissionDocument, type BrowserBillSubmissionInput, type BrowserBillSubmissionResult, type BrowserSubmittedBill, type CloseBillInput, DEFAULT_API_BASE_URL, DEFAULT_SESSION_ENDPOINT, type OrganizationBillingProviderInput, type OrganizationChecklistItem, type OrganizationClient, type OrganizationClientOptions, type OrganizationLocationInput, type OrganizationPracticeIdentity, type OrganizationProfileData, type 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 SendDuplicateBillInput, type SimulateSandboxBillInput, type SubmitBillInput, type SubmitNewBillInput, type SubmitSecondReviewInput, billTasksAgingBucketIndex, buildBillTasksDashboard, createBillLifecycleClient, createBillReferenceClient, createBillSubmissionClient, createOrganizationClient, defaultBillReviewPayerOption, reportBillStatusContacts, sanitizeBillReviewSaveInput, secondReviewDeadline };
package/dist/index.js CHANGED
@@ -342,63 +342,102 @@ function createBillLifecycleClient({
342
342
  const body = await response.json();
343
343
  return normalizeLifecycle(body.data);
344
344
  };
345
- const searchClaimsAdministrators = async (query, claimNumber) => {
345
+ const listClaimsAdministrators = async (input = {}) => {
346
346
  const params = new URLSearchParams();
347
- if (query.trim()) params.set("q", query.trim());
348
- if (claimNumber?.trim()) params.set("claimNumber", claimNumber.trim());
347
+ if (input.query?.trim()) params.set("q", input.query.trim());
348
+ if (input.claimNumber?.trim()) params.set("claimNumber", input.claimNumber.trim());
349
+ if (input.sourceClaimsAdministratorName?.trim()) params.set("sourceClaimsAdministratorName", input.sourceClaimsAdministratorName.trim());
350
+ if (input.employerName?.trim()) params.set("employerName", input.employerName.trim());
351
+ const limit = Math.max(1, Math.min(100, Math.floor(input.limit ?? 50)));
352
+ const offset = Math.max(0, Math.floor(input.offset ?? 0));
353
+ params.set("limit", String(limit));
354
+ if (offset) params.set("offset", String(offset));
349
355
  const response = await request(`/partner/v2/browser/claims-administrators?${params.toString()}`);
350
356
  if (!response.ok) throw await responseError(response, "Claims administrator search is unavailable.");
351
357
  const body = await response.json();
352
358
  if (!Array.isArray(body.results)) throw new Error("Claims administrator search returned an invalid response.");
353
- return body.results.flatMap((value) => {
354
- if (!value || typeof value !== "object") return [];
359
+ const normalizePayer = (value) => {
360
+ if (!value || typeof value !== "object") return null;
355
361
  const payer = value;
356
- if (typeof payer.id !== "string" || typeof payer.name !== "string") return [];
357
- return [{
362
+ if (typeof payer.id !== "string" || typeof payer.name !== "string") return null;
363
+ const payers = Array.isArray(payer.payers) ? payer.payers.flatMap((option) => {
364
+ if (!option || typeof option !== "object") return [];
365
+ const candidate = option;
366
+ const id = typeof candidate.id === "string" ? candidate.id : typeof candidate.key === "string" ? candidate.key : null;
367
+ if (!id || typeof candidate.label !== "string") return [];
368
+ return [{
369
+ id,
370
+ label: candidate.label,
371
+ ...typeof candidate.default === "boolean" ? { default: candidate.default } : {},
372
+ ...typeof candidate.active === "boolean" ? { active: candidate.active } : {},
373
+ ...Array.isArray(candidate.aliases) ? { aliases: candidate.aliases.filter((item) => typeof item === "string") } : {},
374
+ ...typeof candidate.hint === "string" ? { hint: candidate.hint } : {},
375
+ ...Array.isArray(candidate.affiliatedEntities) ? { affiliatedEntities: candidate.affiliatedEntities.filter((item) => typeof item === "string") } : {},
376
+ ...typeof candidate.route === "string" ? { route: candidate.route } : {},
377
+ ...typeof candidate.optionType === "string" ? { optionType: candidate.optionType } : {},
378
+ ...typeof candidate.deliveryType === "string" ? { deliveryType: candidate.deliveryType } : {},
379
+ ...typeof candidate.clearinghouse === "string" ? { clearinghouse: candidate.clearinghouse } : {},
380
+ ...typeof candidate.payerId === "string" ? { payerId: candidate.payerId } : {},
381
+ ...typeof candidate.sourceClearinghouse === "string" ? { sourceClearinghouse: candidate.sourceClearinghouse } : {},
382
+ ...typeof candidate.sourcePayerId === "string" ? { sourcePayerId: candidate.sourcePayerId } : {},
383
+ ...candidate.clearinghousePayerIds && typeof candidate.clearinghousePayerIds === "object" && !Array.isArray(candidate.clearinghousePayerIds) ? { clearinghousePayerIds: Object.fromEntries(Object.entries(candidate.clearinghousePayerIds).filter((entry) => typeof entry[1] === "string")) } : {},
384
+ ...typeof candidate.preferredClearinghouse === "string" ? { preferredClearinghouse: candidate.preferredClearinghouse } : {}
385
+ }];
386
+ }) : void 0;
387
+ const claimNumberPatterns = Array.isArray(payer.claimNumberPatterns) ? payer.claimNumberPatterns.flatMap((value2) => {
388
+ if (!value2 || typeof value2 !== "object") return [];
389
+ const pattern = value2;
390
+ if (typeof pattern.pattern !== "string") return [];
391
+ return [{
392
+ pattern: pattern.pattern,
393
+ ...typeof pattern.length === "string" || typeof pattern.length === "number" ? { length: pattern.length } : {},
394
+ ...typeof pattern.example === "string" ? { example: pattern.example } : {},
395
+ ...typeof pattern.matches === "boolean" || pattern.matches === null ? { matches: pattern.matches } : {}
396
+ }];
397
+ }) : void 0;
398
+ return {
358
399
  id: payer.id,
359
400
  name: payer.name,
360
401
  ...typeof payer.hasElectronic === "boolean" ? { hasElectronic: payer.hasElectronic } : {},
361
402
  ...Array.isArray(payer.states) ? { states: payer.states.filter((state) => typeof state === "string") } : {},
362
- ...["high", "medium", "directory"].includes(payer.confidence ?? "") ? { confidence: payer.confidence } : {},
403
+ ...["high", "medium", "directory"].includes(String(payer.confidence)) ? { confidence: payer.confidence } : {},
363
404
  ...typeof payer.recommended === "boolean" ? { recommended: payer.recommended } : {},
364
405
  ...typeof payer.payerSelectionRequired === "boolean" ? { payerSelectionRequired: payer.payerSelectionRequired } : {},
365
- ...Array.isArray(payer.payers) ? {
366
- payers: payer.payers.flatMap((option) => {
367
- if (!option || typeof option !== "object") return [];
368
- const candidate = option;
369
- const id = typeof candidate.id === "string" ? candidate.id : typeof candidate.key === "string" ? candidate.key : null;
370
- if (!id || typeof candidate.label !== "string") return [];
371
- return [{
372
- id,
373
- label: candidate.label,
374
- ...typeof candidate.default === "boolean" ? { default: candidate.default } : {},
375
- ...typeof candidate.active === "boolean" ? { active: candidate.active } : {},
376
- ...Array.isArray(candidate.aliases) ? { aliases: candidate.aliases.filter((item) => typeof item === "string") } : {},
377
- ...typeof candidate.hint === "string" ? { hint: candidate.hint } : {},
378
- ...Array.isArray(candidate.affiliatedEntities) ? { affiliatedEntities: candidate.affiliatedEntities.filter((item) => typeof item === "string") } : {},
379
- ...typeof candidate.route === "string" ? { route: candidate.route } : {}
380
- }];
381
- })
382
- } : {},
406
+ ...payers ? { payers } : {},
383
407
  ...Array.isArray(payer.aliases) ? { aliases: payer.aliases.filter((item) => typeof item === "string") } : {},
384
408
  ...Array.isArray(payer.affiliatedEntities) ? { affiliatedEntities: payer.affiliatedEntities.filter((item) => typeof item === "string") } : {},
385
409
  ...typeof payer.claimNumberHint === "string" ? { claimNumberHint: payer.claimNumberHint } : {},
410
+ ...claimNumberPatterns ? { claimNumberPatterns } : {},
386
411
  ...typeof payer.route === "string" ? { route: payer.route } : {},
387
- ...Array.isArray(payer.signals) ? {
388
- signals: payer.signals.flatMap((signal) => {
389
- if (!signal || typeof signal !== "object") return [];
390
- const candidate = signal;
391
- if (!["name", "claim_number"].includes(String(candidate.kind)) || !["match", "warning"].includes(String(candidate.state)) || typeof candidate.label !== "string") return [];
392
- return [{
393
- kind: candidate.kind,
394
- state: candidate.state,
395
- label: candidate.label
396
- }];
397
- })
398
- } : {}
399
- }];
412
+ ...Array.isArray(payer.signals) ? { signals: payer.signals.flatMap((signal) => {
413
+ if (!signal || typeof signal !== "object") return [];
414
+ const candidate = signal;
415
+ if (!["name", "claim_number"].includes(String(candidate.kind)) || !["match", "warning"].includes(String(candidate.state)) || typeof candidate.label !== "string") return [];
416
+ return [{ kind: candidate.kind, state: candidate.state, label: candidate.label }];
417
+ }) } : {}
418
+ };
419
+ };
420
+ const results = body.results.flatMap((value) => {
421
+ const payer = normalizePayer(value);
422
+ return payer ? [payer] : [];
400
423
  });
424
+ const suggestions = Array.isArray(body.suggestions) ? body.suggestions.flatMap((value) => {
425
+ const payer = normalizePayer(value);
426
+ if (!payer || !value || typeof value !== "object") return [];
427
+ const suggestion = value;
428
+ if (typeof suggestion.deterministic !== "boolean" || typeof suggestion.reason !== "string") return [];
429
+ return [{ ...payer, deterministic: suggestion.deterministic, reason: suggestion.reason, ...typeof suggestion.selectedPayerId === "string" ? { selectedPayerId: suggestion.selectedPayerId } : {} }];
430
+ }) : [];
431
+ const total = typeof body.total === "number" && Number.isFinite(body.total) ? Math.max(results.length, Math.floor(body.total)) : offset + results.length;
432
+ return {
433
+ results,
434
+ ...suggestions.length ? { suggestions } : {},
435
+ total,
436
+ ...typeof body.nextOffset === "number" && Number.isFinite(body.nextOffset) ? { nextOffset: Math.floor(body.nextOffset) } : {},
437
+ ...typeof body.recommendedId === "string" ? { recommendedId: body.recommendedId } : {}
438
+ };
401
439
  };
440
+ const searchClaimsAdministrators = async (query, claimNumber) => (await listClaimsAdministrators({ query, ...claimNumber ? { claimNumber } : {} })).results;
402
441
  const getClaimsAdministratorDirectory = async (id, injuryState) => {
403
442
  const params = new URLSearchParams();
404
443
  if (injuryState?.trim()) params.set("injuryState", injuryState.trim());
@@ -466,6 +505,7 @@ function createBillLifecycleClient({
466
505
  sessionRequest = null;
467
506
  },
468
507
  getLifecycle: loadLifecycle,
508
+ listClaimsAdministrators,
469
509
  searchClaimsAdministrators,
470
510
  getClaimsAdministratorDirectory,
471
511
  searchDiagnosisCodes,
@@ -532,6 +572,7 @@ function createBillReferenceClient(options = {}) {
532
572
  billId: "pre-submission-reference-data"
533
573
  });
534
574
  return {
575
+ listClaimsAdministrators: lifecycle.listClaimsAdministrators,
535
576
  searchClaimsAdministrators: lifecycle.searchClaimsAdministrators,
536
577
  getClaimsAdministratorDirectory: lifecycle.getClaimsAdministratorDirectory,
537
578
  searchDiagnosisCodes: lifecycle.searchDiagnosisCodes,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export const DEFAULT_API_BASE_URL = \"https://app.mindbill.org\";\nexport const DEFAULT_SESSION_ENDPOINT = \"/api/mindbill/session\";\n\nexport type BillReviewDocumentType =\n | \"final_report\"\n | \"letter_of_attestation\"\n | \"proof_of_service\"\n | \"form_122\"\n | \"return_to_work_voucher\"\n | \"w9\"\n | \"medical_records\"\n | \"appeal\"\n | \"other\";\n\nexport type BillReviewBillingProvider = {\n name: string;\n taxId: string;\n npi: string;\n billType: \"Professional\" | \"Institutional\";\n phone?: string;\n billingStreet?: string;\n billingCity?: string;\n billingState?: string;\n billingZip?: string;\n};\n\nexport type BillReviewClinician = {\n name: string;\n specialty: string;\n npi: string;\n taxonomy?: string;\n licenseNumber?: string;\n licenseState?: string;\n signaturePng?: string;\n signatureKey?: string;\n isQME?: boolean;\n isAME?: boolean;\n email?: string;\n active?: boolean;\n};\n\nexport type BillReviewLocation = {\n billingProviderId?: string;\n name: string;\n nickname?: string;\n street: string;\n city: string;\n state: string;\n zip: string;\n county?: string;\n posCode?: string;\n isPrimary?: boolean;\n active?: boolean;\n};\n\nexport type BillReviewLineItem = {\n id?: string;\n code: string;\n modifiers: string[];\n units: number;\n charge: number;\n feeSchedule?: number;\n serviceDate?: string | null;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n};\n\nexport type BillReviewAttachment = {\n id: string;\n filename: string;\n description?: string | null;\n documentType: string;\n reportType?: string | null;\n source?: string;\n addedAt?: string;\n contentUrl?: string;\n};\n\n/** One selectable payer (subpayor) under a claims administrator. */\nexport type BillReviewPayerOption = {\n id: string;\n label: string;\n /** Preselect this payer when the claims administrator is chosen. */\n default?: boolean;\n active?: boolean;\n aliases?: string[];\n hint?: string | null;\n affiliatedEntities?: string[];\n route?: 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 route?: string | null;\n};\n\n/**\n * The payer option to preselect when a claims administrator that requires\n * payer selection is chosen, or null when nothing is marked as the default.\n */\nexport function defaultBillReviewPayerOption(\n payer: Pick<BillReviewPayer, \"payerSelectionRequired\" | \"payers\">,\n): BillReviewPayerOption | null {\n if (!payer.payerSelectionRequired) return null;\n return payer.payers?.find((option) => option.default) ?? null;\n}\n\nexport type BillPostalPlace = { city: string; state: string };\nexport type BillDiagnosisCode = { code: string; description: string };\n\nexport type BillReviewFeatures = {\n authorizationNumber?: boolean;\n serviceDateRange?: boolean;\n wcabNumber?: boolean;\n codingPresets?: boolean;\n};\n\nexport type BillReviewClaimPatternStatus = {\n state: \"match\" | \"warning\" | \"unknown\";\n label: string;\n detail?: string;\n suggestion?: string;\n};\n\nexport type BillReviewData = {\n bill: {\n id: string;\n billNumber: string | number;\n status: string;\n transmissionState?: string;\n billingMode: \"med_legal\" | \"professional\";\n dos: string;\n dosEnd?: string | null;\n authorizationNumber?: string | null;\n billingSnapshot?: {\n billingProvider?: BillReviewBillingProvider;\n renderingProvider?: BillReviewClinician;\n placeOfService?: BillReviewLocation;\n } | null;\n lineItems: BillReviewLineItem[];\n attachments: BillReviewAttachment[];\n totalCharge: number;\n totalPaid: number;\n balanceDue: number;\n };\n patient: {\n name: string;\n firstName?: string;\n middleName?: string;\n lastName?: string;\n dob?: string;\n phone?: string;\n address?: {\n line1?: string;\n city?: string;\n state?: string;\n postalCode?: string;\n };\n };\n injury: {\n claimNumber?: string;\n employer?: string;\n doi?: string;\n injuryEndDate?: string;\n cumulativeTrauma?: boolean;\n adjNumber?: string;\n claimsAdminId?: string;\n claimsAdminName?: string;\n injuryDescription?: string;\n /** Diagnosis codes enriched with their human-readable ICD-10 descriptions. */\n diagnoses?: BillDiagnosisCode[];\n /** @deprecated Prefer diagnoses so users can understand each code. */\n diagnosisCodes?: string[];\n claimPatternStatus?: BillReviewClaimPatternStatus;\n };\n};\n\nexport type BillReviewSaveInput = {\n claimsAdminId: string;\n /** The chosen payer (subpayor) when the claims administrator requires payer selection. */\n payerId?: string;\n patientOverrides?: {\n firstName: string;\n middleName?: string;\n lastName: string;\n dob?: string;\n };\n injuryOverrides?: {\n claimNumber?: string;\n employer?: string;\n doi?: string;\n injuryEndDate?: string;\n cumulativeTrauma?: boolean;\n adjNumber?: string;\n };\n dos: string;\n dosEnd?: string | null;\n authorizationNumber?: string | null;\n billingProvider?: BillReviewBillingProvider;\n renderingProvider?: BillReviewClinician;\n placeOfService?: BillReviewLocation;\n lineItems: Array<{\n id?: string;\n code: string;\n modifiers: string[];\n units: number;\n charge?: number;\n serviceDate?: string | null;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n }>;\n};\n\nfunction pickDefined(\n source: object,\n keys: readonly string[],\n): Record<string, unknown> {\n const record = source as Record<string, unknown>;\n return Object.fromEntries(\n keys.flatMap((key) => record[key] === undefined ? [] : [[key, record[key]]]),\n );\n}\n\n/**\n * Removes read-only snapshot metadata before a review mutation is sent.\n * Lifecycle reads can include display-only fields such as entity IDs; the v2\n * write contract accepts only the values that should be frozen onto the bill.\n */\nexport function sanitizeBillReviewSaveInput(\n input: BillReviewSaveInput,\n): BillReviewSaveInput {\n return {\n claimsAdminId: input.claimsAdminId,\n ...(input.payerId !== undefined ? { payerId: input.payerId } : {}),\n ...(input.patientOverrides ? {\n patientOverrides: pickDefined(input.patientOverrides, [\n \"firstName\", \"middleName\", \"lastName\", \"dob\",\n ]) as NonNullable<BillReviewSaveInput[\"patientOverrides\"]>,\n } : {}),\n ...(input.injuryOverrides ? {\n injuryOverrides: pickDefined(input.injuryOverrides, [\n \"claimNumber\", \"employer\", \"doi\", \"injuryEndDate\",\n \"cumulativeTrauma\", \"adjNumber\",\n ]) as NonNullable<BillReviewSaveInput[\"injuryOverrides\"]>,\n } : {}),\n dos: input.dos,\n ...(input.dosEnd !== undefined ? { dosEnd: input.dosEnd } : {}),\n ...(input.authorizationNumber !== undefined\n ? { authorizationNumber: input.authorizationNumber }\n : {}),\n ...(input.billingProvider ? {\n billingProvider: pickDefined(input.billingProvider, [\n \"name\", \"taxId\", \"npi\", \"billType\", \"phone\", \"billingStreet\",\n \"billingCity\", \"billingState\", \"billingZip\",\n ]) as BillReviewBillingProvider,\n } : {}),\n ...(input.renderingProvider ? {\n renderingProvider: pickDefined(input.renderingProvider, [\n \"name\", \"specialty\", \"npi\", \"taxonomy\", \"licenseNumber\",\n \"licenseState\", \"signaturePng\", \"signatureKey\", \"isQME\", \"isAME\",\n \"email\", \"active\",\n ]) as BillReviewClinician,\n } : {}),\n ...(input.placeOfService ? {\n placeOfService: pickDefined(input.placeOfService, [\n \"billingProviderId\", \"name\", \"nickname\", \"street\", \"city\", \"state\",\n \"zip\", \"county\", \"posCode\", \"isPrimary\", \"active\",\n ]) as BillReviewLocation,\n } : {}),\n lineItems: input.lineItems.map((line) => pickDefined(line, [\n \"id\", \"code\", \"modifiers\", \"units\", \"charge\", \"serviceDate\",\n \"serviceDateEnd\", \"diagnosisPointers\",\n ]) as BillReviewSaveInput[\"lineItems\"][number]),\n };\n}\n\nexport type BillSubmissionRoute = \"ebill\" | \"fax\" | \"mail\" | \"email\";\nexport type BillDeliveryOption = {\n route: BillSubmissionRoute;\n label: string;\n detail: string;\n fallback: boolean;\n confidence: string;\n payerName: string;\n target?: string;\n chKey?: string;\n payerId?: string;\n printAndMail?: boolean;\n costUsd?: number;\n};\nexport type BillDeliveryOptions = {\n payerName: string;\n recommended: BillDeliveryOption;\n options: BillDeliveryOption[];\n contacts: {\n faxNumber?: string | null;\n claimsEmail?: string | null;\n portalUrl?: string | null;\n mailingAddress?: string | null;\n adjusterName?: string | null;\n adjusterPhone?: string | null;\n adjusterEmail?: string | null;\n };\n};\nexport type BillActorInput = {\n /** Human-readable name shown for user-initiated audit history. */\n actorName?: string;\n};\n\nexport type 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 /** 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\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 | null;\n pattern: string;\n example?: string | null;\n matches?: boolean | null;\n};\n\nexport type BillClaimsAdministratorPayer = {\n name: string;\n daisyBillPayerId?: string | null;\n route?: string | null;\n aliases?: string[];\n hint?: string | null;\n affiliatedEntities?: string[];\n};\n\nexport type BillClaimsAdministratorDirectory = {\n id?: string;\n name?: string;\n type?: string | null;\n description?: string | null;\n website?: string | null;\n aliases?: string[];\n affiliatedEntities?: string[];\n hours?: string | null;\n claimNumberHint?: string | null;\n billProcessingWorkflow?: string | null;\n billProcessingWorkflowNotes?: string | null;\n telephoneNumbers?: string[];\n emailAddresses?: string[];\n webPortals?: string[];\n payers?: BillClaimsAdministratorPayer[];\n authorizationNotice?: string | null;\n billReview?: BillClaimsAdministratorContact[];\n authorization?: BillClaimsAdministratorContact[];\n mailingAddresses?: BillClaimsAdministratorMailingAddress[];\n claimNumberPatterns?: BillClaimsAdministratorPattern[];\n};\n\n/** End-user-safe details explaining why the latest submission was rejected. */\nexport type BillRejectionIssue = {\n code?: string | null;\n description: string;\n /** Bill-submission field paths implicated by this issue. */\n fieldPaths?: string[];\n};\n\nexport type BillRejection = {\n reason: string;\n code?: string | null;\n issues?: BillRejectionIssue[];\n receivedAt?: string | null;\n source?: string | null;\n};\n\nexport type BillLifecycleData = BillReviewData & {\n environment: \"sandbox\" | \"live\";\n lifecycle: {\n state: string;\n nativeStatus: string;\n submittedAt?: string | null;\n agingDays?: number | null;\n updatedAt?: string | null;\n actions: BillLifecycleAction[];\n };\n eors: BillEorDocument[];\n activity: BillActivityRecord[];\n /** daisyBill-style presented history rows. Optional: absent when the API\n * predates the presented-history rollout — fall back to `activity`. */\n history?: BillHistoryEntry[];\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 SubmitSecondReviewInput = BillActorInput & {\n reason: string;\n payerClaimControlNumber: string;\n disputedAmount: number | undefined;\n attachmentIds: string[];\n route: BillSubmissionRoute;\n /** Optional subset of disputed line items; omitted = the whole bill. */\n lineItemIds?: string[];\n /** SBR-1 box: whether the disputed service was authorized. */\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 daisyBill-worded 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: resends the immutable\n * submission packet, unchanged, over the selected delivery route — typically\n * after the payer reports the bill is not on file.\n */\nexport type SendDuplicateBillInput = BillActorInput & {\n route: BillSubmissionRoute;\n destination?: SubmitBillInput[\"destination\"];\n attention?: string;\n subject?: string;\n note?: string;\n /** CC recipients for the email route (at most 10). */\n cc?: string[];\n};\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 documents?: BrowserBillSubmissionDocument[];\n};\n/**\n * \"Submit New Bill\" from a CLOSED bill: the same snapshot payload shape as a\n * resubmission, but the server creates a FRESH original bill linked to the closed\n * predecessor — the closed bill stays closed and keeps its record, and the\n * submissions ribbon/timeline chains both records.\n */\nexport type SubmitNewBillInput = ResubmitBillInput;\nexport type SandboxSimulationScenario = \"accepted\" | \"rejected\" | \"processed\" | \"denied\" | \"partial_payment\" | \"paid\";\nexport type SimulateSandboxBillInput = {\n scenario: SandboxSimulationScenario;\n amount?: number;\n reasonCode?: string;\n};\n\nexport type BrowserBillAddress = {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n postalCode: string;\n};\n\n/** Complete bill snapshot accepted by the browser create endpoint. */\nexport type BrowserBillCreateInput = {\n externalId?: string;\n billingMode?: \"med_legal\" | \"professional\";\n patient: {\n id?: string;\n externalId?: string;\n firstName: string;\n middleName?: string;\n lastName: string;\n dateOfBirth: string;\n ssn?: string;\n gender?: \"M\" | \"F\" | \"X\";\n phone?: string;\n address: BrowserBillAddress;\n };\n claim: {\n id?: string;\n externalId?: string;\n claimNumber: string;\n adjNumber?: string;\n employer: string;\n dateOfInjury: string;\n injuryState?: string;\n description?: string;\n claimsAdministrator: {\n id: string;\n name: string;\n /** The chosen payer (subpayor) when the claims administrator requires payer selection. */\n payerId?: string;\n };\n };\n service: { date: string; endDate?: string | null; authorizationNumber?: string | null };\n billingProvider: { name: string; taxId: string; npi: string; phone: string; address: BrowserBillAddress };\n renderingProvider: {\n name: string;\n specialty?: string;\n npi: string;\n taxonomy: string;\n licenseNumber?: string;\n licenseState?: string;\n isQme?: boolean;\n isAme?: boolean;\n };\n serviceLocation: { name?: string; address: BrowserBillAddress; placeOfServiceCode: string };\n diagnoses: string[];\n serviceLines: Array<{\n code: string;\n modifiers?: string[];\n units?: number;\n charge?: number;\n serviceDate?: string;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n }>;\n};\n\n/** Canonical immutable PDF snapshot sent with a bill submission. */\nexport type BrowserBillSubmissionDocument = {\n externalId?: string;\n filename: string;\n description?: string;\n documentType: BillReviewDocumentType;\n /** Opaque PWK report-type code selected by the component (for example OZ:J4). */\n reportTypeCode?: string;\n contentBase64: string;\n};\n\nexport type BrowserBillSubmissionInput = BillActorInput & {\n bill: BrowserBillCreateInput;\n submission?: {\n route?: BillSubmissionRoute;\n destination?: SubmitBillInput[\"destination\"];\n attention?: string;\n subject?: string;\n note?: string;\n cc?: string[];\n };\n documents?: BrowserBillSubmissionDocument[];\n};\n\nexport type BrowserSubmittedBill = Record<string, unknown> & {\n id: string;\n externalId?: string | null;\n state?: string;\n};\n\nexport type BrowserBillSubmissionResult = {\n billId: string;\n bill: BrowserSubmittedBill;\n};\n\nexport type BillLifecycleClientOptions = {\n /** ID of an already-submitted bill. Bills are created only by the atomic server API. */\n billId: string;\n sessionEndpoint?: string | undefined;\n getSession?: BillLifecycleSessionProvider | undefined;\n apiBaseUrl?: string | undefined;\n fetch?: typeof globalThis.fetch | undefined;\n};\n\n/** Browser-session options for pre-submission reference-data lookups. */\nexport type BillReferenceClientOptions = Omit<BillLifecycleClientOptions, \"billId\">;\n\n/** Browser-session options for an atomic immutable bill submission. */\nexport type BillSubmissionClientOptions = BillReferenceClientOptions;\n\nexport type BillSubmissionClient = {\n submitBill: (\n input: BrowserBillSubmissionInput,\n options?: { idempotencyKey?: string },\n ) => Promise<BrowserBillSubmissionResult>;\n clearSession: () => void;\n};\n\n/** Input for the pre-submission delivery preview keyed on a payer-directory id. */\nexport type BillDeliveryPreviewInput = {\n claimsAdministratorId: string;\n /** Two-letter state; defaults to CA server-side. */\n injuryState?: string;\n};\n\nexport type BillReferenceClient = {\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 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 closeBill: (input: CloseBillInput) => Promise<BillLifecycleData>;\n reopenBill: (input: ReopenBillInput) => Promise<BillLifecycleData>;\n postPayment: (input: PostBillPaymentInput) => Promise<BillLifecycleData>;\n submitSecondReview: (input: SubmitSecondReviewInput) => Promise<BillLifecycleData>;\n resubmitBill: (input: ResubmitBillInput) => Promise<BillLifecycleData>;\n submitNewBill: (input: SubmitNewBillInput) => Promise<BillLifecycleData>;\n sendDuplicateBill: (input: SendDuplicateBillInput) => Promise<BillLifecycleData>;\n reportBillStatus: (input: ReportBillStatusInput) => Promise<BillLifecycleData>;\n simulateSandbox: (input: SimulateSandboxBillInput) => Promise<BillLifecycleData>;\n clearSession: () => void;\n};\n\nasync function responseError(response: Response, fallback: string): Promise<Error> {\n const body: unknown = await response.json().catch(() => null);\n const detail = body && typeof body === \"object\"\n ? (body as { detail?: unknown; message?: unknown; error?: unknown }).detail\n ?? (body as { message?: unknown }).message\n ?? (body as { error?: unknown }).error\n : null;\n return new Error(typeof detail === \"string\" ? detail : fallback);\n}\n\nfunction isSessionFresh(session: BillLifecycleSession | null): boolean {\n if (!session) return false;\n if (!session.expiresAt) return true;\n const expiresAt = new Date(session.expiresAt).getTime();\n return Number.isFinite(expiresAt) && expiresAt > Date.now() + 30_000;\n}\n\nfunction normalizeSession(value: unknown): BillLifecycleSession {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing session endpoint returned an invalid response.\");\n }\n const candidate = value as { token?: unknown; expiresAt?: unknown; apiBaseUrl?: unknown; session?: unknown; data?: unknown };\n const nested = candidate.session ?? candidate.data;\n const session = nested && typeof nested === \"object\" ? nested as typeof candidate : candidate;\n if (typeof session.token !== \"string\" || session.token.length < 8) {\n throw new Error(\"The billing session endpoint did not return a browser session token.\");\n }\n return {\n token: session.token,\n ...(typeof session.expiresAt === \"string\" ? { expiresAt: session.expiresAt } : {}),\n ...(typeof session.apiBaseUrl === \"string\" ? { apiBaseUrl: session.apiBaseUrl } : {}),\n };\n}\n\nfunction normalizeLifecycle(value: unknown): BillLifecycleData {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n const data = value as Partial<BillLifecycleData>;\n if (\n ![\"sandbox\", \"live\"].includes(data.environment ?? \"\")\n || !data.bill\n || !data.patient\n || !data.injury\n || !data.lifecycle\n || !Array.isArray(data.lifecycle.actions)\n || !Array.isArray(data.eors)\n || !Array.isArray(data.activity)\n || !Array.isArray(data.payments)\n || !data.remittance\n || typeof data.remittance !== \"object\"\n || !data.delivery\n || typeof data.delivery !== \"object\"\n || !data.delivery.contacts\n || typeof data.delivery.contacts !== \"object\"\n || (data.rejection != null && (\n typeof data.rejection !== \"object\"\n || typeof data.rejection.reason !== \"string\"\n || (data.rejection.issues != null && (\n !Array.isArray(data.rejection.issues)\n || data.rejection.issues.some((issue) => (\n !issue\n || typeof issue !== \"object\"\n || typeof issue.description !== \"string\"\n || (issue.code != null && typeof issue.code !== \"string\")\n ))\n ))\n ))\n ) {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n return data as BillLifecycleData;\n}\n\nfunction normalizeDeliveryOptions(value: unknown): BillDeliveryOptions {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n const data = value as Partial<BillDeliveryOptions>;\n if (\n typeof data.payerName !== \"string\"\n || !data.recommended\n || typeof data.recommended !== \"object\"\n || ![\"ebill\", \"fax\", \"mail\", \"email\"].includes(data.recommended.route ?? \"\")\n || !Array.isArray(data.options)\n || !data.contacts\n ) {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n return data as BillDeliveryOptions;\n}\n\nfunction idempotencyKey(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") return globalThis.crypto.randomUUID();\n return `mb-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Browser-safe client for one atomic create-and-submit operation.\n *\n * The browser session is short-lived and origin-bound. The host application\n * never needs the Partner API document schema or a long-lived API key.\n */\nexport function createBillSubmissionClient({\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillSubmissionClientOptions = {}): BillSubmissionClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const submitBill = async (\n input: BrowserBillSubmissionInput,\n options: { idempotencyKey?: string } = {},\n ): Promise<BrowserBillSubmissionResult> => {\n const controller = new AbortController();\n const requestIdempotencyKey = options.idempotencyKey ?? idempotencyKey();\n let browserSession = await mintSession(controller.signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n return fetcher(`${base}/partner/v2/browser/bills`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${current.token}`,\n \"content-type\": \"application/json\",\n \"idempotency-key\": requestIdempotencyKey,\n },\n body: JSON.stringify(input),\n signal: controller.signal,\n });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(controller.signal, true);\n response = await perform(browserSession);\n }\n if (!response.ok) throw await responseError(response, \"The bill could not be submitted.\");\n const body: unknown = await response.json().catch(() => null);\n const envelope = body && typeof body === \"object\" && \"data\" in body\n ? (body as { data?: unknown }).data\n : body;\n if (!envelope || typeof envelope !== \"object\" || typeof (envelope as { id?: unknown }).id !== \"string\") {\n throw new Error(\"The billing service submitted the bill but returned an invalid bill ID.\");\n }\n const bill = envelope as BrowserSubmittedBill;\n return { billId: bill.id, bill };\n };\n\n return {\n submitBill,\n clearSession() { session = null; sessionRequest = null; },\n };\n}\n\n/** Browser-safe, framework-neutral client for an already-submitted bill. */\nexport function createBillLifecycleClient({\n billId,\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillLifecycleClientOptions): BillLifecycleClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n const currentBillId = billId.trim();\n if (!currentBillId) throw new Error(\"billId is required for the submitted-bill lifecycle client.\");\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const request = async (path: string, init: RequestInit = {}, providedSignal?: AbortSignal): Promise<Response> => {\n const controller = providedSignal ? null : new AbortController();\n const signal = providedSignal ?? controller?.signal;\n if (!signal) throw new Error(\"An AbortSignal could not be created.\");\n let browserSession = await mintSession(signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n const headers = new Headers(init.headers);\n headers.set(\"authorization\", `Bearer ${current.token}`);\n return fetcher(`${base}${path}`, { ...init, headers, signal });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(signal, true);\n response = await perform(browserSession);\n }\n return response;\n };\n\n const billPath = (suffix = \"\"): string =>\n `/partner/v2/browser/bills/${encodeURIComponent(currentBillId)}${suffix}`;\n\n const loadLifecycle = async (signal?: AbortSignal) => {\n const response = await request(billPath(\"/lifecycle\"), {}, signal);\n if (!response.ok) throw await responseError(response, \"Bill lifecycle could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n\n const searchClaimsAdministrators = async (query: string, claimNumber?: string): Promise<BillReviewPayer[]> => {\n const params = new URLSearchParams();\n if (query.trim()) params.set(\"q\", query.trim());\n if (claimNumber?.trim()) params.set(\"claimNumber\", claimNumber.trim());\n const response = await request(`/partner/v2/browser/claims-administrators?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator search is unavailable.\");\n const body = await response.json() as { results?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Claims administrator search returned an invalid response.\");\n return body.results.flatMap((value): BillReviewPayer[] => {\n if (!value || typeof value !== \"object\") return [];\n const payer = value as Partial<BillReviewPayer>;\n if (typeof payer.id !== \"string\" || typeof payer.name !== \"string\") return [];\n return [{\n id: payer.id,\n name: payer.name,\n ...(typeof payer.hasElectronic === \"boolean\" ? { hasElectronic: payer.hasElectronic } : {}),\n ...(Array.isArray(payer.states)\n ? { states: payer.states.filter((state): state is string => typeof state === \"string\") }\n : {}),\n ...([\"high\", \"medium\", \"directory\"].includes(payer.confidence ?? \"\")\n ? { confidence: payer.confidence as NonNullable<BillReviewPayer[\"confidence\"]> }\n : {}),\n ...(typeof payer.recommended === \"boolean\" ? { recommended: payer.recommended } : {}),\n ...(typeof payer.payerSelectionRequired === \"boolean\"\n ? { payerSelectionRequired: payer.payerSelectionRequired }\n : {}),\n ...(Array.isArray(payer.payers)\n ? {\n 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 }];\n }),\n }\n : {}),\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 ...(typeof payer.route === \"string\" ? { route: payer.route } : {}),\n ...(Array.isArray(payer.signals)\n ? {\n signals: payer.signals.flatMap((signal) => {\n if (!signal || typeof signal !== \"object\") return [];\n const candidate = signal as { kind?: unknown; state?: unknown; label?: unknown };\n if (\n ![\"name\", \"claim_number\"].includes(String(candidate.kind))\n || ![\"match\", \"warning\"].includes(String(candidate.state))\n || typeof candidate.label !== \"string\"\n ) return [];\n return [{\n kind: candidate.kind as \"name\" | \"claim_number\",\n state: candidate.state as \"match\" | \"warning\",\n label: candidate.label,\n }];\n }),\n }\n : {}),\n }];\n });\n };\n\n const getClaimsAdministratorDirectory = async (id: string, injuryState?: string): Promise<BillClaimsAdministratorDirectory> => {\n const params = new URLSearchParams();\n if (injuryState?.trim()) params.set(\"injuryState\", injuryState.trim());\n const response = await request(`/partner/v2/browser/claims-administrators/${encodeURIComponent(id)}${params.size ? `?${params}` : \"\"}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator details are unavailable.\");\n const body = await response.json() as { data?: unknown };\n if (!body.data || typeof body.data !== \"object\") throw new Error(\"Claims administrator details returned an invalid response.\");\n return body.data as BillClaimsAdministratorDirectory;\n };\n\n const searchDiagnosisCodes = async (query: string, limit = 30, offset = 0): Promise<BillDiagnosisCode[]> => {\n const params = new URLSearchParams({ q: query.trim(), limit: String(Math.max(1, Math.min(100, limit))) });\n if (offset > 0) params.set(\"offset\", String(Math.max(0, Math.floor(offset))));\n const response = await request(`/partner/v2/browser/diagnosis-codes?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Diagnosis-code search is unavailable.\");\n const body = await response.json() as { results?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Diagnosis-code search returned an invalid response.\");\n return body.results.flatMap((value): BillDiagnosisCode[] => {\n if (!value || typeof value !== \"object\") return [];\n const candidate = value as { code?: unknown; description?: unknown };\n return typeof candidate.code === \"string\" && typeof candidate.description === \"string\"\n ? [{ code: candidate.code, description: candidate.description }]\n : [];\n });\n };\n\n const lookupPostalCode = async (postalCode: string): Promise<BillPostalPlace | null> => {\n const params = new URLSearchParams({ postalCode: postalCode.trim() });\n const response = await request(`/partner/v2/browser/postal-codes?${params.toString()}`);\n if (response.status === 404) return null;\n if (!response.ok) throw await responseError(response, \"ZIP lookup is unavailable.\");\n const body = await response.json() as { city?: unknown; state?: unknown };\n if (typeof body.city !== \"string\" || typeof body.state !== \"string\") {\n throw new Error(\"ZIP lookup returned an invalid response.\");\n }\n return { city: body.city, state: body.state };\n };\n\n const mutation = async (path: string, init: RequestInit, fallback: string) => {\n const headers = new Headers(init.headers);\n headers.set(\"idempotency-key\", idempotencyKey());\n const response = await request(path, { ...init, headers });\n if (!response.ok) throw await responseError(response, fallback);\n return response;\n };\n const action = async (input: Record<string, unknown>, fallback: string): Promise<BillLifecycleData> => {\n const response = await mutation(billPath(\"/actions\"), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, fallback);\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n const simulateSandbox = async (input: SimulateSandboxBillInput): Promise<BillLifecycleData> => {\n const response = await mutation(billPath(\"/simulate\"), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, \"Sandbox lifecycle could not be simulated.\");\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n return {\n getBillId() { return currentBillId; },\n clearSession() { session = null; sessionRequest = null; },\n getLifecycle: loadLifecycle,\n 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.injuryState?.trim()) params.set(\"injuryState\", input.injuryState.trim());\n const response = await request(`/partner/v2/browser/delivery-preview?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Delivery routes could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getAttachment(attachmentId) {\n const response = await request(billPath(`/documents/${encodeURIComponent(attachmentId)}`));\n if (!response.ok) throw await responseError(response, \"Document could not be opened.\");\n return response.blob();\n },\n async getEor(documentId) {\n const response = await request(billPath(`/eors/${encodeURIComponent(documentId)}`));\n if (!response.ok) throw await responseError(response, \"EOR could not be opened.\");\n return response.blob();\n },\n async getPacket() {\n const response = await request(billPath(\"/packet\"));\n if (!response.ok) throw await responseError(response, \"Submission packet could not be downloaded.\");\n return response.blob();\n },\n 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 searchClaimsAdministrators: lifecycle.searchClaimsAdministrators,\n getClaimsAdministratorDirectory: lifecycle.getClaimsAdministratorDirectory,\n searchDiagnosisCodes: lifecycle.searchDiagnosisCodes,\n lookupPostalCode: lifecycle.lookupPostalCode,\n getDeliveryPreview: lifecycle.getDeliveryPreview,\n clearSession: lifecycle.clearSession,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Organization profile client (INC-1470): backs the embeddable\n// OrganizationOnboarding / BillingSettings components. Requires a browser\n// session minted with the OPTIONAL organization:manage permission; sessions\n// without it are rejected by the API and nothing else changes.\n\nexport type OrganizationPracticeIdentity = {\n name?: string; legalName?: string; taxId?: string; npi?: string;\n phone?: string; email?: string; website?: string;\n};\n\nexport type OrganizationBillingProviderInput = {\n id?: string; externalId?: string; name: string; taxId: string; npi: string;\n billType?: \"Professional\" | \"Institutional\"; phone?: string;\n billingStreet?: string; billingCity?: string; billingState?: string; billingZip?: string;\n};\n\nexport type OrganizationLocationInput = {\n id?: string; externalId?: string; name: string; street: string; city: string;\n state: string; zip: string; nickname?: string; posCode?: string;\n isPrimary?: boolean; active?: boolean;\n};\n\nexport type OrganizationChecklistItem = { id: string; label: string; complete: boolean };\n\nexport type OrganizationProfileData = {\n organizationId: string;\n practiceIdentity: OrganizationPracticeIdentity;\n billingProviders: Array<OrganizationBillingProviderInput & { id: string }>;\n locations: Array<OrganizationLocationInput & { id: string }>;\n w9: { filename: string; addDate: string; taxYear?: number } | null;\n onboarding: { status: string | null; complete: boolean; checklist: OrganizationChecklistItem[] };\n};\n\nexport type OrganizationClientOptions = {\n sessionEndpoint?: string;\n getSession?: BillLifecycleSessionProvider;\n apiBaseUrl?: string;\n fetch?: typeof globalThis.fetch;\n};\n\nexport type OrganizationClient = {\n getOrganization: () => Promise<OrganizationProfileData>;\n saveBillingProfile: (input: {\n practiceIdentity?: OrganizationPracticeIdentity;\n billingProviders?: OrganizationBillingProviderInput[];\n }) => Promise<OrganizationProfileData>;\n saveLocations: (locations: OrganizationLocationInput[]) => Promise<OrganizationProfileData>;\n saveW9: (input: { filename: string; contentBase64: string; taxYear?: number }) => Promise<OrganizationProfileData>;\n};\n\nexport function createOrganizationClient({\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: OrganizationClientOptions = {}): OrganizationClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n\n const mintSession = async (force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n const pending = getSession\n ? getSession({ signal: new AbortController().signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The organization session could not be created.\");\n return response.json();\n });\n session = normalizeSession(await Promise.resolve(pending));\n return session;\n };\n\n const request = async (path: string, init: RequestInit = {}): Promise<OrganizationProfileData> => {\n let current = await mintSession();\n const perform = (active: BillLifecycleSession) => {\n const base = (active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n const headers = new Headers(init.headers);\n headers.set(\"authorization\", `Bearer ${active.token}`);\n if (init.body) headers.set(\"content-type\", \"application/json\");\n return fetcher(`${base}${path}`, { ...init, headers });\n };\n let response = await perform(current);\n if (response.status === 401) {\n current = await mintSession(true);\n response = await perform(current);\n }\n if (!response.ok) throw await responseError(response, \"The organization request failed.\");\n const body = (await response.json()) as { data?: OrganizationProfileData };\n if (!body.data || typeof body.data !== \"object\") {\n throw new Error(\"The organization response was invalid.\");\n }\n return body.data;\n };\n\n return {\n getOrganization: () => request(\"/partner/v2/browser/organization\"),\n saveBillingProfile: (input) =>\n request(\"/partner/v2/browser/organization/billing-profile\", { method: \"PUT\", body: JSON.stringify(input) }),\n saveLocations: (locations) =>\n request(\"/partner/v2/browser/organization/locations\", { method: \"PUT\", body: JSON.stringify({ locations }) }),\n saveW9: (input) =>\n request(\"/partner/v2/browser/organization/w9\", { method: \"PUT\", body: JSON.stringify(input) }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Bill Tasks dashboard (daisyBill-style worklist): 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 /** 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 empty: boolean;\n};\n\nexport type BillTasksDashboardData = {\n sections: BillTasksDashboardSection[];\n grandTotals: number[];\n grandTotal: 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 daisyBill-style 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 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\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 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 row.counts[bucketIndex] = (row.counts[bucketIndex] ?? 0) + 1;\n row.total += 1;\n if (item.ref) row.refs[bucketIndex]?.push(item.ref);\n section.totals[bucketIndex] = (section.totals[bucketIndex] ?? 0) + 1;\n section.total += 1;\n grandTotals[bucketIndex] = (grandTotals[bucketIndex] ?? 0) + 1;\n grandTotal += 1;\n }\n\n return { sections: built, grandTotals, grandTotal };\n}\n"],"mappings":";AAAO,IAAM,uBAAuB;AAC7B,IAAM,2BAA2B;AAoHjC,SAAS,6BACd,OAC8B;AAC9B,MAAI,CAAC,MAAM,uBAAwB,QAAO;AAC1C,SAAO,MAAM,QAAQ,KAAK,CAAC,WAAW,OAAO,OAAO,KAAK;AAC3D;AA4GA,SAAS,YACP,QACA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KAAI,KAAK,WAAW,GAAG,KAAK,KAAK,GAAG;AAClD,YAAQ,OAAO,WAAW,KAAK,QAAQ,OAAO,WAAW,KAAK,KAAK;AACnE,YAAQ,SAAS;AACjB,gBAAY,WAAW,KAAK,YAAY,WAAW,KAAK,KAAK;AAC7D,kBAAc;AAAA,EAChB;AAEA,SAAO,EAAE,UAAU,OAAO,aAAa,WAAW;AACpD;","names":["request"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export const DEFAULT_API_BASE_URL = \"https://app.mindbill.org\";\nexport const DEFAULT_SESSION_ENDPOINT = \"/api/mindbill/session\";\n\nexport type BillReviewDocumentType =\n | \"final_report\"\n | \"letter_of_attestation\"\n | \"proof_of_service\"\n | \"form_122\"\n | \"return_to_work_voucher\"\n | \"w9\"\n | \"medical_records\"\n | \"appeal\"\n | \"other\";\n\nexport type BillReviewBillingProvider = {\n name: string;\n taxId: string;\n npi: string;\n billType: \"Professional\" | \"Institutional\";\n phone?: string;\n billingStreet?: string;\n billingCity?: string;\n billingState?: string;\n billingZip?: string;\n};\n\nexport type BillReviewClinician = {\n name: string;\n specialty: string;\n npi: string;\n taxonomy?: string;\n licenseNumber?: string;\n licenseState?: string;\n signaturePng?: string;\n signatureKey?: string;\n isQME?: boolean;\n isAME?: boolean;\n email?: string;\n active?: boolean;\n};\n\nexport type BillReviewLocation = {\n billingProviderId?: string;\n name: string;\n nickname?: string;\n street: string;\n city: string;\n state: string;\n zip: string;\n county?: string;\n posCode?: string;\n isPrimary?: boolean;\n active?: boolean;\n};\n\nexport type BillReviewLineItem = {\n id?: string;\n code: string;\n modifiers: string[];\n units: number;\n charge: number;\n feeSchedule?: number;\n serviceDate?: string | null;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n};\n\nexport type BillReviewAttachment = {\n id: string;\n filename: string;\n description?: string | null;\n documentType: string;\n reportType?: string | null;\n source?: string;\n addedAt?: string;\n contentUrl?: string;\n};\n\n/** One selectable payer (subpayor) under a claims administrator. */\nexport type BillReviewPayerOption = {\n id: string;\n label: string;\n /** Directory-provided default marker. Interactive forms still require an explicit choice. */\n default?: boolean;\n active?: boolean;\n aliases?: string[];\n hint?: string | null;\n affiliatedEntities?: string[];\n route?: string | null;\n optionType?: string | null;\n deliveryType?: string | null;\n clearinghouse?: string | null;\n payerId?: string | null;\n /** Original directory route when live delivery uses a replacement clearinghouse. */\n sourceClearinghouse?: string | null;\n /** Original directory payer ID when live delivery uses a replacement route. */\n sourcePayerId?: string | null;\n clearinghousePayerIds?: Record<string, string>;\n preferredClearinghouse?: string | null;\n};\n\nexport type BillReviewPayer = {\n id: string;\n name: string;\n hasElectronic?: boolean;\n states?: string[];\n confidence?: \"high\" | \"medium\" | \"directory\";\n recommended?: boolean;\n signals?: Array<{\n kind: \"name\" | \"claim_number\";\n state: \"match\" | \"warning\";\n label: string;\n }>;\n /** True when a bill for this claims administrator must name one of `payers`. */\n payerSelectionRequired?: boolean;\n /** Selectable payers (subpayors) under this claims administrator. */\n payers?: BillReviewPayerOption[];\n aliases?: string[];\n affiliatedEntities?: string[];\n claimNumberHint?: string | null;\n claimNumberPatterns?: BillClaimsAdministratorPattern[];\n route?: string | null;\n};\n\n/** A directory suggestion derived from host-provided evidence. Suggestions are never auto-applied. */\nexport type BillReviewPayerSuggestion = BillReviewPayer & {\n deterministic: boolean;\n reason: string;\n /** A uniquely proven routing payer under a multi-payer claims administrator. */\n selectedPayerId?: string;\n};\n\n/** Host-system evidence shown alongside claims-administrator suggestions. */\nexport type BillClaimsAdministratorSource = {\n source: \"eams\" | \"report\" | string;\n label: string;\n name: string;\n url?: string;\n};\n\n/**\n * The directory-marked default payer option, or null when none is marked.\n * Interactive forms should still require an explicit routing-payer choice.\n */\nexport function defaultBillReviewPayerOption(\n payer: Pick<BillReviewPayer, \"payerSelectionRequired\" | \"payers\">,\n): BillReviewPayerOption | null {\n if (!payer.payerSelectionRequired) return null;\n return payer.payers?.find((option) => option.default) ?? null;\n}\n\nexport type BillPostalPlace = { city: string; state: string };\nexport type BillDiagnosisCode = { code: string; description: string };\n\nexport type BillReviewFeatures = {\n authorizationNumber?: boolean;\n serviceDateRange?: boolean;\n wcabNumber?: boolean;\n codingPresets?: boolean;\n};\n\nexport type BillReviewClaimPatternStatus = {\n state: \"match\" | \"warning\" | \"unknown\";\n label: string;\n detail?: string;\n suggestion?: string;\n};\n\nexport type BillReviewData = {\n bill: {\n id: string;\n billNumber: string | number;\n status: string;\n transmissionState?: string;\n billingMode: \"med_legal\" | \"professional\";\n dos: string;\n dosEnd?: string | null;\n authorizationNumber?: string | null;\n billingSnapshot?: {\n billingProvider?: BillReviewBillingProvider;\n renderingProvider?: BillReviewClinician;\n placeOfService?: BillReviewLocation;\n } | null;\n lineItems: BillReviewLineItem[];\n attachments: BillReviewAttachment[];\n totalCharge: number;\n totalPaid: number;\n balanceDue: number;\n };\n patient: {\n name: string;\n firstName?: string;\n middleName?: string;\n lastName?: string;\n dob?: string;\n phone?: string;\n address?: {\n line1?: string;\n city?: string;\n state?: string;\n postalCode?: string;\n };\n };\n injury: {\n claimNumber?: string;\n employer?: string;\n doi?: string;\n injuryEndDate?: string;\n cumulativeTrauma?: boolean;\n adjNumber?: string;\n claimsAdminId?: string;\n claimsAdminName?: string;\n injuryDescription?: string;\n /** Diagnosis codes enriched with their human-readable ICD-10 descriptions. */\n diagnoses?: BillDiagnosisCode[];\n /** @deprecated Prefer diagnoses so users can understand each code. */\n diagnosisCodes?: string[];\n claimPatternStatus?: BillReviewClaimPatternStatus;\n };\n};\n\nexport type BillReviewSaveInput = {\n claimsAdminId: string;\n /** The chosen payer (subpayor) when the claims administrator requires payer selection. */\n payerId?: string;\n patientOverrides?: {\n firstName: string;\n middleName?: string;\n lastName: string;\n dob?: string;\n };\n injuryOverrides?: {\n claimNumber?: string;\n employer?: string;\n doi?: string;\n injuryEndDate?: string;\n cumulativeTrauma?: boolean;\n adjNumber?: string;\n };\n dos: string;\n dosEnd?: string | null;\n authorizationNumber?: string | null;\n billingProvider?: BillReviewBillingProvider;\n renderingProvider?: BillReviewClinician;\n placeOfService?: BillReviewLocation;\n lineItems: Array<{\n id?: string;\n code: string;\n modifiers: string[];\n units: number;\n charge?: number;\n serviceDate?: string | null;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n }>;\n};\n\nfunction pickDefined(\n source: object,\n keys: readonly string[],\n): Record<string, unknown> {\n const record = source as Record<string, unknown>;\n return Object.fromEntries(\n keys.flatMap((key) => record[key] === undefined ? [] : [[key, record[key]]]),\n );\n}\n\n/**\n * Removes read-only snapshot metadata before a review mutation is sent.\n * Lifecycle reads can include display-only fields such as entity IDs; the v2\n * write contract accepts only the values that should be frozen onto the bill.\n */\nexport function sanitizeBillReviewSaveInput(\n input: BillReviewSaveInput,\n): BillReviewSaveInput {\n return {\n claimsAdminId: input.claimsAdminId,\n ...(input.payerId !== undefined ? { payerId: input.payerId } : {}),\n ...(input.patientOverrides ? {\n patientOverrides: pickDefined(input.patientOverrides, [\n \"firstName\", \"middleName\", \"lastName\", \"dob\",\n ]) as NonNullable<BillReviewSaveInput[\"patientOverrides\"]>,\n } : {}),\n ...(input.injuryOverrides ? {\n injuryOverrides: pickDefined(input.injuryOverrides, [\n \"claimNumber\", \"employer\", \"doi\", \"injuryEndDate\",\n \"cumulativeTrauma\", \"adjNumber\",\n ]) as NonNullable<BillReviewSaveInput[\"injuryOverrides\"]>,\n } : {}),\n dos: input.dos,\n ...(input.dosEnd !== undefined ? { dosEnd: input.dosEnd } : {}),\n ...(input.authorizationNumber !== undefined\n ? { authorizationNumber: input.authorizationNumber }\n : {}),\n ...(input.billingProvider ? {\n billingProvider: pickDefined(input.billingProvider, [\n \"name\", \"taxId\", \"npi\", \"billType\", \"phone\", \"billingStreet\",\n \"billingCity\", \"billingState\", \"billingZip\",\n ]) as BillReviewBillingProvider,\n } : {}),\n ...(input.renderingProvider ? {\n renderingProvider: pickDefined(input.renderingProvider, [\n \"name\", \"specialty\", \"npi\", \"taxonomy\", \"licenseNumber\",\n \"licenseState\", \"signaturePng\", \"signatureKey\", \"isQME\", \"isAME\",\n \"email\", \"active\",\n ]) as BillReviewClinician,\n } : {}),\n ...(input.placeOfService ? {\n placeOfService: pickDefined(input.placeOfService, [\n \"billingProviderId\", \"name\", \"nickname\", \"street\", \"city\", \"state\",\n \"zip\", \"county\", \"posCode\", \"isPrimary\", \"active\",\n ]) as BillReviewLocation,\n } : {}),\n lineItems: input.lineItems.map((line) => pickDefined(line, [\n \"id\", \"code\", \"modifiers\", \"units\", \"charge\", \"serviceDate\",\n \"serviceDateEnd\", \"diagnosisPointers\",\n ]) as BillReviewSaveInput[\"lineItems\"][number]),\n };\n}\n\nexport type BillSubmissionRoute = \"ebill\" | \"fax\" | \"mail\" | \"email\";\nexport type BillDeliveryOption = {\n route: BillSubmissionRoute;\n label: string;\n detail: string;\n fallback: boolean;\n confidence: string;\n payerName: string;\n target?: string;\n chKey?: string;\n payerId?: string;\n printAndMail?: boolean;\n costUsd?: number;\n};\nexport type BillDeliveryOptions = {\n payerName: string;\n recommended: BillDeliveryOption;\n options: BillDeliveryOption[];\n contacts: {\n faxNumber?: string | null;\n claimsEmail?: string | null;\n portalUrl?: string | null;\n mailingAddress?: string | null;\n adjusterName?: string | null;\n adjusterPhone?: string | null;\n adjusterEmail?: string | null;\n };\n};\nexport type BillActorInput = {\n /** Human-readable name shown for user-initiated audit history. */\n actorName?: string;\n};\n\nexport type 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 /** 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\nexport type BillPaymentRecord = {\n id: string;\n method: \"check\" | \"eft\";\n checkNumber: string;\n status: string | null;\n depositDate: string | null;\n checkReceived: boolean | null;\n receivedDate: string | null;\n amount: number;\n principalAmount: number;\n feeAmount: number | null;\n feeReason: string | null;\n source: \"paper\" | \"835\" | \"portal\";\n postedAt: string;\n updatedAt: string | null;\n note: string | null;\n};\n\nexport type BillRemittanceSummary = {\n billedAmount: number;\n expectedAmount: number;\n payerAllowedAmount: number | null;\n payerReportedPaid: number | null;\n postedPrincipal: number;\n postedAdditional: number;\n totalPostedCash: number;\n balanceDue: number;\n denialReason: string | null;\n};\n\nexport type BillLifecycleDelivery = {\n payerName: string;\n contacts: BillDeliveryOptions[\"contacts\"];\n /**\n * Partner-safe directory details. `id` is an opaque MindBill directory ID;\n * Values are safe, partner-facing directory details; internal database identifiers are opaque.\n */\n directory?: BillClaimsAdministratorDirectory | null;\n};\n\nexport type BillClaimsAdministratorContact = {\n name?: string | null;\n phone?: string | null;\n email?: string | null;\n fax?: string | null;\n portalUrl?: string | null;\n address?: string | null;\n note?: string | null;\n};\n\nexport type BillClaimsAdministratorMailingAddress = {\n company?: string | null;\n address: string;\n notes?: string | null;\n submissionTypes?: string[];\n billTreatmentTypes?: string[];\n};\n\nexport type BillClaimsAdministratorPattern = {\n length?: number | string | null;\n pattern: string;\n example?: string | null;\n matches?: boolean | null;\n};\n\nexport type BillClaimsAdministratorPayer = {\n name: string;\n route?: string | null;\n aliases?: string[];\n hint?: string | null;\n affiliatedEntities?: string[];\n optionType?: string | null;\n deliveryType?: string | null;\n clearinghouse?: string | null;\n payerId?: string | null;\n sourceClearinghouse?: string | null;\n sourcePayerId?: string | null;\n clearinghousePayerIds?: Record<string, string>;\n preferredClearinghouse?: string | null;\n};\n\nexport type BillReviewPayerPage = {\n results: BillReviewPayer[];\n suggestions?: BillReviewPayerSuggestion[];\n total: number;\n nextOffset?: number;\n recommendedId?: string;\n};\n\nexport type BillReviewPayerListInput = {\n query?: string;\n claimNumber?: string;\n sourceClaimsAdministratorName?: string;\n employerName?: string;\n limit?: number;\n offset?: number;\n};\n\nexport type BillClaimsAdministratorDirectory = {\n id?: string;\n name?: string;\n type?: string | null;\n description?: string | null;\n website?: string | null;\n aliases?: string[];\n affiliatedEntities?: string[];\n hours?: string | null;\n claimNumberHint?: string | null;\n billProcessingWorkflow?: string | null;\n billProcessingWorkflowNotes?: string | null;\n telephoneNumbers?: string[];\n emailAddresses?: string[];\n webPortals?: string[];\n payers?: BillClaimsAdministratorPayer[];\n authorizationNotice?: string | null;\n billReview?: BillClaimsAdministratorContact[];\n authorization?: BillClaimsAdministratorContact[];\n mailingAddresses?: BillClaimsAdministratorMailingAddress[];\n claimNumberPatterns?: BillClaimsAdministratorPattern[];\n};\n\n/** End-user-safe details explaining why the latest submission was rejected. */\nexport type BillRejectionIssue = {\n code?: string | null;\n description: string;\n /** Bill-submission field paths implicated by this issue. */\n fieldPaths?: string[];\n};\n\nexport type BillRejection = {\n reason: string;\n code?: string | null;\n issues?: BillRejectionIssue[];\n receivedAt?: string | null;\n source?: string | null;\n};\n\nexport type BillLifecycleData = BillReviewData & {\n environment: \"sandbox\" | \"live\";\n lifecycle: {\n state: string;\n nativeStatus: string;\n submittedAt?: string | null;\n agingDays?: number | null;\n updatedAt?: string | null;\n actions: BillLifecycleAction[];\n };\n eors: BillEorDocument[];\n activity: BillActivityRecord[];\n /** Presented history rows. Optional: absent when the API\n * predates the presented-history rollout — fall back to `activity`. */\n history?: BillHistoryEntry[];\n 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 SubmitSecondReviewInput = BillActorInput & {\n reason: string;\n payerClaimControlNumber: string;\n disputedAmount: number | undefined;\n attachmentIds: string[];\n route: BillSubmissionRoute;\n /** Optional subset of disputed line items; omitted = the whole bill. */\n lineItemIds?: string[];\n /** SBR-1 box: whether the disputed service was authorized. */\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: resends the immutable\n * submission packet, unchanged, over the selected delivery route — typically\n * after the payer reports the bill is not on file.\n */\nexport type SendDuplicateBillInput = BillActorInput & {\n route: BillSubmissionRoute;\n destination?: SubmitBillInput[\"destination\"];\n attention?: string;\n subject?: string;\n note?: string;\n /** CC recipients for the email route (at most 10). */\n cc?: string[];\n};\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 documents?: BrowserBillSubmissionDocument[];\n};\n/**\n * \"Submit New Bill\" from a CLOSED bill: the same snapshot payload shape as a\n * resubmission, but the server creates a FRESH original bill linked to the closed\n * predecessor — the closed bill stays closed and keeps its record, and the\n * submissions ribbon/timeline chains both records.\n */\nexport type SubmitNewBillInput = ResubmitBillInput;\nexport type SandboxSimulationScenario = \"accepted\" | \"rejected\" | \"processed\" | \"denied\" | \"partial_payment\" | \"paid\";\nexport type SimulateSandboxBillInput = {\n scenario: SandboxSimulationScenario;\n amount?: number;\n reasonCode?: string;\n};\n\nexport type BrowserBillAddress = {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n postalCode: string;\n};\n\n/** Complete bill snapshot accepted by the browser create endpoint. */\nexport type BrowserBillCreateInput = {\n externalId?: string;\n billingMode?: \"med_legal\" | \"professional\";\n patient: {\n id?: string;\n externalId?: string;\n firstName: string;\n middleName?: string;\n lastName: string;\n dateOfBirth: string;\n ssn?: string;\n gender?: \"M\" | \"F\" | \"X\";\n phone?: string;\n address: BrowserBillAddress;\n };\n claim: {\n id?: string;\n externalId?: string;\n claimNumber: string;\n adjNumber?: string;\n employer: string;\n dateOfInjury: string;\n injuryState?: string;\n description?: string;\n claimsAdministrator: {\n id: string;\n name: string;\n /** The chosen payer (subpayor) when the claims administrator requires payer selection. */\n payerId?: string;\n };\n };\n service: { date: string; endDate?: string | null; authorizationNumber?: string | null };\n billingProvider: { name: string; taxId: string; npi: string; phone: string; address: BrowserBillAddress };\n renderingProvider: {\n name: string;\n specialty?: string;\n npi: string;\n taxonomy: string;\n licenseNumber?: string;\n licenseState?: string;\n isQme?: boolean;\n isAme?: boolean;\n };\n serviceLocation: { name?: string; address: BrowserBillAddress; placeOfServiceCode: string };\n diagnoses: string[];\n serviceLines: Array<{\n code: string;\n modifiers?: string[];\n units?: number;\n charge?: number;\n serviceDate?: string;\n serviceDateEnd?: string | null;\n diagnosisPointers?: number[];\n }>;\n};\n\n/** Canonical immutable PDF snapshot sent with a bill submission. */\nexport type BrowserBillSubmissionDocument = {\n externalId?: string;\n filename: string;\n description?: string;\n documentType: BillReviewDocumentType;\n /** Opaque PWK report-type code selected by the component (for example OZ:J4). */\n reportTypeCode?: string;\n contentBase64: string;\n};\n\nexport type BrowserBillSubmissionInput = BillActorInput & {\n bill: BrowserBillCreateInput;\n submission?: {\n route?: BillSubmissionRoute;\n destination?: SubmitBillInput[\"destination\"];\n attention?: string;\n subject?: string;\n note?: string;\n cc?: string[];\n };\n documents?: BrowserBillSubmissionDocument[];\n};\n\nexport type BrowserSubmittedBill = Record<string, unknown> & {\n id: string;\n externalId?: string | null;\n state?: string;\n};\n\nexport type BrowserBillSubmissionResult = {\n billId: string;\n bill: BrowserSubmittedBill;\n};\n\nexport type BillLifecycleClientOptions = {\n /** ID of an already-submitted bill. Bills are created only by the atomic server API. */\n billId: string;\n sessionEndpoint?: string | undefined;\n getSession?: BillLifecycleSessionProvider | undefined;\n apiBaseUrl?: string | undefined;\n fetch?: typeof globalThis.fetch | undefined;\n};\n\n/** Browser-session options for pre-submission reference-data lookups. */\nexport type BillReferenceClientOptions = Omit<BillLifecycleClientOptions, \"billId\">;\n\n/** Browser-session options for an atomic immutable bill submission. */\nexport type BillSubmissionClientOptions = BillReferenceClientOptions;\n\nexport type BillSubmissionClient = {\n submitBill: (\n input: BrowserBillSubmissionInput,\n options?: { idempotencyKey?: string },\n ) => Promise<BrowserBillSubmissionResult>;\n clearSession: () => void;\n};\n\n/** Input for the pre-submission delivery preview keyed on a payer-directory id. */\nexport type BillDeliveryPreviewInput = {\n claimsAdministratorId: string;\n /** 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 closeBill: (input: CloseBillInput) => Promise<BillLifecycleData>;\n reopenBill: (input: ReopenBillInput) => Promise<BillLifecycleData>;\n postPayment: (input: PostBillPaymentInput) => Promise<BillLifecycleData>;\n submitSecondReview: (input: SubmitSecondReviewInput) => Promise<BillLifecycleData>;\n resubmitBill: (input: ResubmitBillInput) => Promise<BillLifecycleData>;\n submitNewBill: (input: SubmitNewBillInput) => Promise<BillLifecycleData>;\n sendDuplicateBill: (input: SendDuplicateBillInput) => Promise<BillLifecycleData>;\n reportBillStatus: (input: ReportBillStatusInput) => Promise<BillLifecycleData>;\n simulateSandbox: (input: SimulateSandboxBillInput) => Promise<BillLifecycleData>;\n clearSession: () => void;\n};\n\nasync function responseError(response: Response, fallback: string): Promise<Error> {\n const body: unknown = await response.json().catch(() => null);\n const detail = body && typeof body === \"object\"\n ? (body as { detail?: unknown; message?: unknown; error?: unknown }).detail\n ?? (body as { message?: unknown }).message\n ?? (body as { error?: unknown }).error\n : null;\n return new Error(typeof detail === \"string\" ? detail : fallback);\n}\n\nfunction isSessionFresh(session: BillLifecycleSession | null): boolean {\n if (!session) return false;\n if (!session.expiresAt) return true;\n const expiresAt = new Date(session.expiresAt).getTime();\n return Number.isFinite(expiresAt) && expiresAt > Date.now() + 30_000;\n}\n\nfunction normalizeSession(value: unknown): BillLifecycleSession {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing session endpoint returned an invalid response.\");\n }\n const candidate = value as { token?: unknown; expiresAt?: unknown; apiBaseUrl?: unknown; session?: unknown; data?: unknown };\n const nested = candidate.session ?? candidate.data;\n const session = nested && typeof nested === \"object\" ? nested as typeof candidate : candidate;\n if (typeof session.token !== \"string\" || session.token.length < 8) {\n throw new Error(\"The billing session endpoint did not return a browser session token.\");\n }\n return {\n token: session.token,\n ...(typeof session.expiresAt === \"string\" ? { expiresAt: session.expiresAt } : {}),\n ...(typeof session.apiBaseUrl === \"string\" ? { apiBaseUrl: session.apiBaseUrl } : {}),\n };\n}\n\nfunction normalizeLifecycle(value: unknown): BillLifecycleData {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n const data = value as Partial<BillLifecycleData>;\n if (\n ![\"sandbox\", \"live\"].includes(data.environment ?? \"\")\n || !data.bill\n || !data.patient\n || !data.injury\n || !data.lifecycle\n || !Array.isArray(data.lifecycle.actions)\n || !Array.isArray(data.eors)\n || !Array.isArray(data.activity)\n || !Array.isArray(data.payments)\n || !data.remittance\n || typeof data.remittance !== \"object\"\n || !data.delivery\n || typeof data.delivery !== \"object\"\n || !data.delivery.contacts\n || typeof data.delivery.contacts !== \"object\"\n || (data.rejection != null && (\n typeof data.rejection !== \"object\"\n || typeof data.rejection.reason !== \"string\"\n || (data.rejection.issues != null && (\n !Array.isArray(data.rejection.issues)\n || data.rejection.issues.some((issue) => (\n !issue\n || typeof issue !== \"object\"\n || typeof issue.description !== \"string\"\n || (issue.code != null && typeof issue.code !== \"string\")\n ))\n ))\n ))\n ) {\n throw new Error(\"The billing service returned an invalid bill lifecycle.\");\n }\n return data as BillLifecycleData;\n}\n\nfunction normalizeDeliveryOptions(value: unknown): BillDeliveryOptions {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n const data = value as Partial<BillDeliveryOptions>;\n if (\n typeof data.payerName !== \"string\"\n || !data.recommended\n || typeof data.recommended !== \"object\"\n || ![\"ebill\", \"fax\", \"mail\", \"email\"].includes(data.recommended.route ?? \"\")\n || !Array.isArray(data.options)\n || !data.contacts\n ) {\n throw new Error(\"The billing service returned invalid delivery options.\");\n }\n return data as BillDeliveryOptions;\n}\n\nfunction idempotencyKey(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") return globalThis.crypto.randomUUID();\n return `mb-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Browser-safe client for one atomic create-and-submit operation.\n *\n * The browser session is short-lived and origin-bound. The host application\n * never needs the Partner API document schema or a long-lived API key.\n */\nexport function createBillSubmissionClient({\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillSubmissionClientOptions = {}): BillSubmissionClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const submitBill = async (\n input: BrowserBillSubmissionInput,\n options: { idempotencyKey?: string } = {},\n ): Promise<BrowserBillSubmissionResult> => {\n const controller = new AbortController();\n const requestIdempotencyKey = options.idempotencyKey ?? idempotencyKey();\n let browserSession = await mintSession(controller.signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n return fetcher(`${base}/partner/v2/browser/bills`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${current.token}`,\n \"content-type\": \"application/json\",\n \"idempotency-key\": requestIdempotencyKey,\n },\n body: JSON.stringify(input),\n signal: controller.signal,\n });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(controller.signal, true);\n response = await perform(browserSession);\n }\n if (!response.ok) throw await responseError(response, \"The bill could not be submitted.\");\n const body: unknown = await response.json().catch(() => null);\n const envelope = body && typeof body === \"object\" && \"data\" in body\n ? (body as { data?: unknown }).data\n : body;\n if (!envelope || typeof envelope !== \"object\" || typeof (envelope as { id?: unknown }).id !== \"string\") {\n throw new Error(\"The billing service submitted the bill but returned an invalid bill ID.\");\n }\n const bill = envelope as BrowserSubmittedBill;\n return { billId: bill.id, bill };\n };\n\n return {\n submitBill,\n clearSession() { session = null; sessionRequest = null; },\n };\n}\n\n/** Browser-safe, framework-neutral client for an already-submitted bill. */\nexport function createBillLifecycleClient({\n billId,\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: BillLifecycleClientOptions): BillLifecycleClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n let sessionRequest: Promise<BillLifecycleSession> | null = null;\n const currentBillId = billId.trim();\n if (!currentBillId) throw new Error(\"billId is required for the submitted-bill lifecycle client.\");\n\n const mintSession = async (signal: AbortSignal, force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n if (!force && sessionRequest) return sessionRequest;\n const pending = getSession\n ? getSession({ signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n signal,\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The billing session could not be created.\");\n return response.json();\n });\n const request = Promise.resolve(pending).then(normalizeSession).then((nextSession) => {\n session = nextSession;\n return nextSession;\n }).finally(() => {\n if (sessionRequest === request) sessionRequest = null;\n });\n sessionRequest = request;\n return request;\n };\n\n const request = async (path: string, init: RequestInit = {}, providedSignal?: AbortSignal): Promise<Response> => {\n const controller = providedSignal ? null : new AbortController();\n const signal = providedSignal ?? controller?.signal;\n if (!signal) throw new Error(\"An AbortSignal could not be created.\");\n let browserSession = await mintSession(signal);\n const perform = (current: BillLifecycleSession) => {\n const base = (current.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n const headers = new Headers(init.headers);\n headers.set(\"authorization\", `Bearer ${current.token}`);\n return fetcher(`${base}${path}`, { ...init, headers, signal });\n };\n let response = await perform(browserSession);\n if (response.status === 401) {\n session = null;\n browserSession = await mintSession(signal, true);\n response = await perform(browserSession);\n }\n return response;\n };\n\n const billPath = (suffix = \"\"): string =>\n `/partner/v2/browser/bills/${encodeURIComponent(currentBillId)}${suffix}`;\n\n const loadLifecycle = async (signal?: AbortSignal) => {\n const response = await request(billPath(\"/lifecycle\"), {}, signal);\n if (!response.ok) throw await responseError(response, \"Bill lifecycle could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n\n const listClaimsAdministrators = async (input: BillReviewPayerListInput = {}): Promise<BillReviewPayerPage> => {\n const params = new URLSearchParams();\n if (input.query?.trim()) params.set(\"q\", input.query.trim());\n if (input.claimNumber?.trim()) params.set(\"claimNumber\", input.claimNumber.trim());\n if (input.sourceClaimsAdministratorName?.trim()) params.set(\"sourceClaimsAdministratorName\", input.sourceClaimsAdministratorName.trim());\n if (input.employerName?.trim()) params.set(\"employerName\", input.employerName.trim());\n const limit = Math.max(1, Math.min(100, Math.floor(input.limit ?? 50)));\n const offset = Math.max(0, Math.floor(input.offset ?? 0));\n params.set(\"limit\", String(limit));\n if (offset) params.set(\"offset\", String(offset));\n const response = await request(`/partner/v2/browser/claims-administrators?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator search is unavailable.\");\n const body = await response.json() as { results?: unknown; suggestions?: unknown; total?: unknown; nextOffset?: unknown; recommendedId?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Claims administrator search returned an invalid response.\");\n const normalizePayer = (value: unknown): BillReviewPayer | null => {\n if (!value || typeof value !== \"object\") return null;\n const payer = value as Record<string, unknown>;\n if (typeof payer.id !== \"string\" || typeof payer.name !== \"string\") return null;\n const payers = Array.isArray(payer.payers) ? payer.payers.flatMap((option): BillReviewPayerOption[] => {\n if (!option || typeof option !== \"object\") return [];\n const candidate = option as Record<string, unknown>;\n const id = typeof candidate.id === \"string\" ? candidate.id : typeof candidate.key === \"string\" ? candidate.key : null;\n if (!id || typeof candidate.label !== \"string\") return [];\n return [{\n id,\n label: candidate.label,\n ...(typeof candidate.default === \"boolean\" ? { default: candidate.default } : {}),\n ...(typeof candidate.active === \"boolean\" ? { active: candidate.active } : {}),\n ...(Array.isArray(candidate.aliases) ? { aliases: candidate.aliases.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof candidate.hint === \"string\" ? { hint: candidate.hint } : {}),\n ...(Array.isArray(candidate.affiliatedEntities) ? { affiliatedEntities: candidate.affiliatedEntities.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof candidate.route === \"string\" ? { route: candidate.route } : {}),\n ...(typeof candidate.optionType === \"string\" ? { optionType: candidate.optionType } : {}),\n ...(typeof candidate.deliveryType === \"string\" ? { deliveryType: candidate.deliveryType } : {}),\n ...(typeof candidate.clearinghouse === \"string\" ? { clearinghouse: candidate.clearinghouse } : {}),\n ...(typeof candidate.payerId === \"string\" ? { payerId: candidate.payerId } : {}),\n ...(typeof candidate.sourceClearinghouse === \"string\" ? { sourceClearinghouse: candidate.sourceClearinghouse } : {}),\n ...(typeof candidate.sourcePayerId === \"string\" ? { sourcePayerId: candidate.sourcePayerId } : {}),\n ...(candidate.clearinghousePayerIds && typeof candidate.clearinghousePayerIds === \"object\" && !Array.isArray(candidate.clearinghousePayerIds)\n ? { clearinghousePayerIds: Object.fromEntries(Object.entries(candidate.clearinghousePayerIds).filter((entry): entry is [string, string] => typeof entry[1] === \"string\")) }\n : {}),\n ...(typeof candidate.preferredClearinghouse === \"string\" ? { preferredClearinghouse: candidate.preferredClearinghouse } : {}),\n }];\n }) : undefined;\n const claimNumberPatterns = Array.isArray(payer.claimNumberPatterns) ? payer.claimNumberPatterns.flatMap((value): BillClaimsAdministratorPattern[] => {\n if (!value || typeof value !== \"object\") return [];\n const pattern = value as Record<string, unknown>;\n if (typeof pattern.pattern !== \"string\") return [];\n return [{\n pattern: pattern.pattern,\n ...(typeof pattern.length === \"string\" || typeof pattern.length === \"number\" ? { length: pattern.length } : {}),\n ...(typeof pattern.example === \"string\" ? { example: pattern.example } : {}),\n ...(typeof pattern.matches === \"boolean\" || pattern.matches === null ? { matches: pattern.matches as boolean | null } : {}),\n }];\n }) : undefined;\n return {\n id: payer.id,\n name: payer.name,\n ...(typeof payer.hasElectronic === \"boolean\" ? { hasElectronic: payer.hasElectronic } : {}),\n ...(Array.isArray(payer.states) ? { states: payer.states.filter((state): state is string => typeof state === \"string\") } : {}),\n ...([\"high\", \"medium\", \"directory\"].includes(String(payer.confidence)) ? { confidence: payer.confidence as NonNullable<BillReviewPayer[\"confidence\"]> } : {}),\n ...(typeof payer.recommended === \"boolean\" ? { recommended: payer.recommended } : {}),\n ...(typeof payer.payerSelectionRequired === \"boolean\" ? { payerSelectionRequired: payer.payerSelectionRequired } : {}),\n ...(payers ? { payers } : {}),\n ...(Array.isArray(payer.aliases) ? { aliases: payer.aliases.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(Array.isArray(payer.affiliatedEntities) ? { affiliatedEntities: payer.affiliatedEntities.filter((item): item is string => typeof item === \"string\") } : {}),\n ...(typeof payer.claimNumberHint === \"string\" ? { claimNumberHint: payer.claimNumberHint } : {}),\n ...(claimNumberPatterns ? { claimNumberPatterns } : {}),\n ...(typeof payer.route === \"string\" ? { route: payer.route } : {}),\n ...(Array.isArray(payer.signals) ? { signals: payer.signals.flatMap((signal) => {\n if (!signal || typeof signal !== \"object\") return [];\n const candidate = signal as Record<string, unknown>;\n if (![\"name\", \"claim_number\"].includes(String(candidate.kind)) || ![\"match\", \"warning\"].includes(String(candidate.state)) || typeof candidate.label !== \"string\") return [];\n return [{ kind: candidate.kind as \"name\" | \"claim_number\", state: candidate.state as \"match\" | \"warning\", label: candidate.label }];\n }) } : {}),\n };\n };\n const results = body.results.flatMap((value): BillReviewPayer[] => {\n const payer = normalizePayer(value);\n return payer ? [payer] : [];\n });\n const suggestions = Array.isArray(body.suggestions) ? body.suggestions.flatMap((value): BillReviewPayerSuggestion[] => {\n const payer = normalizePayer(value);\n if (!payer || !value || typeof value !== \"object\") return [];\n const suggestion = value as Record<string, unknown>;\n if (typeof suggestion.deterministic !== \"boolean\" || typeof suggestion.reason !== \"string\") return [];\n return [{ ...payer, deterministic: suggestion.deterministic, reason: suggestion.reason, ...(typeof suggestion.selectedPayerId === \"string\" ? { selectedPayerId: suggestion.selectedPayerId } : {}) }];\n }) : [];\n const total = typeof body.total === \"number\" && Number.isFinite(body.total) ? Math.max(results.length, Math.floor(body.total)) : offset + results.length;\n return {\n results,\n ...(suggestions.length ? { suggestions } : {}),\n total,\n ...(typeof body.nextOffset === \"number\" && Number.isFinite(body.nextOffset) ? { nextOffset: Math.floor(body.nextOffset) } : {}),\n ...(typeof body.recommendedId === \"string\" ? { recommendedId: body.recommendedId } : {}),\n };\n };\n\n const searchClaimsAdministrators = async (query: string, claimNumber?: string): Promise<BillReviewPayer[]> =>\n (await listClaimsAdministrators({ query, ...(claimNumber ? { claimNumber } : {}) })).results;\n\n const getClaimsAdministratorDirectory = async (id: string, injuryState?: string): Promise<BillClaimsAdministratorDirectory> => {\n const params = new URLSearchParams();\n if (injuryState?.trim()) params.set(\"injuryState\", injuryState.trim());\n const response = await request(`/partner/v2/browser/claims-administrators/${encodeURIComponent(id)}${params.size ? `?${params}` : \"\"}`);\n if (!response.ok) throw await responseError(response, \"Claims administrator details are unavailable.\");\n const body = await response.json() as { data?: unknown };\n if (!body.data || typeof body.data !== \"object\") throw new Error(\"Claims administrator details returned an invalid response.\");\n return body.data as BillClaimsAdministratorDirectory;\n };\n\n const searchDiagnosisCodes = async (query: string, limit = 30, offset = 0): Promise<BillDiagnosisCode[]> => {\n const params = new URLSearchParams({ q: query.trim(), limit: String(Math.max(1, Math.min(100, limit))) });\n if (offset > 0) params.set(\"offset\", String(Math.max(0, Math.floor(offset))));\n const response = await request(`/partner/v2/browser/diagnosis-codes?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Diagnosis-code search is unavailable.\");\n const body = await response.json() as { results?: unknown };\n if (!Array.isArray(body.results)) throw new Error(\"Diagnosis-code search returned an invalid response.\");\n return body.results.flatMap((value): BillDiagnosisCode[] => {\n if (!value || typeof value !== \"object\") return [];\n const candidate = value as { code?: unknown; description?: unknown };\n return typeof candidate.code === \"string\" && typeof candidate.description === \"string\"\n ? [{ code: candidate.code, description: candidate.description }]\n : [];\n });\n };\n\n const lookupPostalCode = async (postalCode: string): Promise<BillPostalPlace | null> => {\n const params = new URLSearchParams({ postalCode: postalCode.trim() });\n const response = await request(`/partner/v2/browser/postal-codes?${params.toString()}`);\n if (response.status === 404) return null;\n if (!response.ok) throw await responseError(response, \"ZIP lookup is unavailable.\");\n const body = await response.json() as { city?: unknown; state?: unknown };\n if (typeof body.city !== \"string\" || typeof body.state !== \"string\") {\n throw new Error(\"ZIP lookup returned an invalid response.\");\n }\n return { city: body.city, state: body.state };\n };\n\n const mutation = async (path: string, init: RequestInit, fallback: string) => {\n const headers = new Headers(init.headers);\n headers.set(\"idempotency-key\", idempotencyKey());\n const response = await request(path, { ...init, headers });\n if (!response.ok) throw await responseError(response, fallback);\n return response;\n };\n const action = async (input: Record<string, unknown>, fallback: string): Promise<BillLifecycleData> => {\n const response = await mutation(billPath(\"/actions\"), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, fallback);\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n const simulateSandbox = async (input: SimulateSandboxBillInput): Promise<BillLifecycleData> => {\n const response = await mutation(billPath(\"/simulate\"), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n }, \"Sandbox lifecycle could not be simulated.\");\n const body = await response.json() as { data?: unknown };\n return normalizeLifecycle(body.data);\n };\n return {\n getBillId() { return currentBillId; },\n clearSession() { session = null; sessionRequest = null; },\n getLifecycle: loadLifecycle,\n listClaimsAdministrators,\n searchClaimsAdministrators,\n getClaimsAdministratorDirectory,\n searchDiagnosisCodes,\n lookupPostalCode,\n async getDeliveryOptions() {\n const response = await request(billPath(\"/delivery-options\"));\n if (!response.ok) throw await responseError(response, \"Delivery options could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getDeliveryPreview(input) {\n const params = new URLSearchParams({ claimsAdministratorId: input.claimsAdministratorId.trim() });\n if (input.injuryState?.trim()) params.set(\"injuryState\", input.injuryState.trim());\n const response = await request(`/partner/v2/browser/delivery-preview?${params.toString()}`);\n if (!response.ok) throw await responseError(response, \"Delivery routes could not be loaded.\");\n const body = await response.json() as { data?: unknown };\n return normalizeDeliveryOptions(body.data ?? body);\n },\n async getAttachment(attachmentId) {\n const response = await request(billPath(`/documents/${encodeURIComponent(attachmentId)}`));\n if (!response.ok) throw await responseError(response, \"Document could not be opened.\");\n return response.blob();\n },\n async getEor(documentId) {\n const response = await request(billPath(`/eors/${encodeURIComponent(documentId)}`));\n if (!response.ok) throw await responseError(response, \"EOR could not be opened.\");\n return response.blob();\n },\n async getPacket() {\n const response = await request(billPath(\"/packet\"));\n if (!response.ok) throw await responseError(response, \"Submission packet could not be downloaded.\");\n return response.blob();\n },\n closeBill(input) { return action({ action: \"close\", ...input }, \"Bill could not be closed.\"); },\n reopenBill(input) { return action({ action: \"reopen\", ...input }, \"Bill could not be reopened.\"); },\n postPayment(input) { return action({ action: \"post_payment\", penaltyAmount: 0, interestAmount: 0, ...input, checkNumber: input.checkNumber ?? \"\" }, \"Payment could not be posted.\"); },\n submitSecondReview(input) { return action({ action: \"second_review\", ...input }, \"Second Review could not be submitted.\"); },\n resubmitBill(input) { return action({ action: \"resubmit\", ...input }, \"Bill could not be resubmitted.\"); },\n submitNewBill(input) { return action({ action: \"submit_new_bill\", ...input }, \"The new bill could not be submitted.\"); },\n sendDuplicateBill(input) { return action({ action: \"send_duplicate\", ...input }, \"Duplicate bill could not be sent.\"); },\n reportBillStatus(input) { return action({ action: \"report_bill_status\", ...input }, \"Bill status could not be reported.\"); },\n simulateSandbox,\n };\n}\n\n/**\n * Browser-safe client for reference data needed before a bill exists.\n *\n * Partners can pass the same short-lived session provider used by the submitted-bill\n * lifecycle without inventing a draft bill or exposing payer directory credentials.\n */\nexport function createBillReferenceClient(\n options: BillReferenceClientOptions = {},\n): BillReferenceClient {\n const lifecycle = createBillLifecycleClient({\n ...options,\n billId: \"pre-submission-reference-data\",\n });\n return {\n listClaimsAdministrators: lifecycle.listClaimsAdministrators,\n searchClaimsAdministrators: lifecycle.searchClaimsAdministrators,\n getClaimsAdministratorDirectory: lifecycle.getClaimsAdministratorDirectory,\n searchDiagnosisCodes: lifecycle.searchDiagnosisCodes,\n lookupPostalCode: lifecycle.lookupPostalCode,\n getDeliveryPreview: lifecycle.getDeliveryPreview,\n clearSession: lifecycle.clearSession,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Organization profile client (INC-1470): backs the embeddable\n// OrganizationOnboarding / BillingSettings components. Requires a browser\n// session minted with the OPTIONAL organization:manage permission; sessions\n// without it are rejected by the API and nothing else changes.\n\nexport type OrganizationPracticeIdentity = {\n name?: string; legalName?: string; taxId?: string; npi?: string;\n phone?: string; email?: string; website?: string;\n};\n\nexport type OrganizationBillingProviderInput = {\n id?: string; externalId?: string; name: string; taxId: string; npi: string;\n billType?: \"Professional\" | \"Institutional\"; phone?: string;\n billingStreet?: string; billingCity?: string; billingState?: string; billingZip?: string;\n};\n\nexport type OrganizationLocationInput = {\n id?: string; externalId?: string; name: string; street: string; city: string;\n state: string; zip: string; nickname?: string; posCode?: string;\n isPrimary?: boolean; active?: boolean;\n};\n\nexport type OrganizationChecklistItem = { id: string; label: string; complete: boolean };\n\nexport type OrganizationProfileData = {\n organizationId: string;\n practiceIdentity: OrganizationPracticeIdentity;\n billingProviders: Array<OrganizationBillingProviderInput & { id: string }>;\n locations: Array<OrganizationLocationInput & { id: string }>;\n w9: { filename: string; addDate: string; taxYear?: number } | null;\n onboarding: { status: string | null; complete: boolean; checklist: OrganizationChecklistItem[] };\n};\n\nexport type OrganizationClientOptions = {\n sessionEndpoint?: string;\n getSession?: BillLifecycleSessionProvider;\n apiBaseUrl?: string;\n fetch?: typeof globalThis.fetch;\n};\n\nexport type OrganizationClient = {\n getOrganization: () => Promise<OrganizationProfileData>;\n saveBillingProfile: (input: {\n practiceIdentity?: OrganizationPracticeIdentity;\n billingProviders?: OrganizationBillingProviderInput[];\n }) => Promise<OrganizationProfileData>;\n saveLocations: (locations: OrganizationLocationInput[]) => Promise<OrganizationProfileData>;\n saveW9: (input: { filename: string; contentBase64: string; taxYear?: number }) => Promise<OrganizationProfileData>;\n};\n\nexport function createOrganizationClient({\n sessionEndpoint = DEFAULT_SESSION_ENDPOINT,\n getSession,\n apiBaseUrl = DEFAULT_API_BASE_URL,\n fetch: fetchOverride,\n}: OrganizationClientOptions = {}): OrganizationClient {\n const fetcher = fetchOverride ?? globalThis.fetch;\n if (typeof fetcher !== \"function\") throw new Error(\"A Fetch API implementation is required.\");\n let session: BillLifecycleSession | null = null;\n\n const mintSession = async (force = false): Promise<BillLifecycleSession> => {\n if (!force && isSessionFresh(session)) return session as BillLifecycleSession;\n const pending = getSession\n ? getSession({ signal: new AbortController().signal })\n : fetcher(sessionEndpoint, {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({}),\n }).then(async (response) => {\n if (!response.ok) throw await responseError(response, \"The organization session could not be created.\");\n return response.json();\n });\n session = normalizeSession(await Promise.resolve(pending));\n return session;\n };\n\n const request = async (path: string, init: RequestInit = {}): Promise<OrganizationProfileData> => {\n let current = await mintSession();\n const perform = (active: BillLifecycleSession) => {\n const base = (active.apiBaseUrl ?? apiBaseUrl).replace(/\\/$/, \"\");\n const headers = new Headers(init.headers);\n headers.set(\"authorization\", `Bearer ${active.token}`);\n if (init.body) headers.set(\"content-type\", \"application/json\");\n return fetcher(`${base}${path}`, { ...init, headers });\n };\n let response = await perform(current);\n if (response.status === 401) {\n current = await mintSession(true);\n response = await perform(current);\n }\n if (!response.ok) throw await responseError(response, \"The organization request failed.\");\n const body = (await response.json()) as { data?: OrganizationProfileData };\n if (!body.data || typeof body.data !== \"object\") {\n throw new Error(\"The organization response was invalid.\");\n }\n return body.data;\n };\n\n return {\n getOrganization: () => request(\"/partner/v2/browser/organization\"),\n saveBillingProfile: (input) =>\n request(\"/partner/v2/browser/organization/billing-profile\", { method: \"PUT\", body: JSON.stringify(input) }),\n saveLocations: (locations) =>\n request(\"/partner/v2/browser/organization/locations\", { method: \"PUT\", body: JSON.stringify({ locations }) }),\n saveW9: (input) =>\n request(\"/partner/v2/browser/organization/w9\", { method: \"PUT\", body: JSON.stringify(input) }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Bill Tasks dashboard: a pure, framework-neutral\n// aggregation shared by the React and Angular components. Hosts flatten their\n// own work items and get back per-section rows bucketed by age in days.\n\nexport type BillTasksAgingBucket = {\n id: string;\n label: string;\n /** Exclusive lower bound in days. The first bucket also admits day 0. */\n minDays: number;\n /** Inclusive upper bound in days; null means unbounded. */\n maxDays: number | null;\n};\n\nexport const BILL_TASKS_AGING_BUCKETS: BillTasksAgingBucket[] = [\n { id: \"1-30\", label: \"1-30 Days Ago\", minDays: 0, maxDays: 30 },\n { id: \"31-60\", label: \"31-60 Days Ago\", minDays: 30, maxDays: 60 },\n { id: \"61-90\", label: \"61-90 Days Ago\", minDays: 60, maxDays: 90 },\n { id: \"91-180\", label: \"91-180 Days Ago\", minDays: 90, maxDays: 180 },\n { id: \"181+\", label: \"181+ Days Ago\", minDays: 180, maxDays: null },\n];\n\nexport type BillTasksDashboardItem = {\n sectionId: string;\n rowId: string;\n rowLabel: string;\n ageDays: number;\n balanceDue?: number;\n /** Opaque bill reference echoed back in click-through payloads. */\n ref?: string;\n};\n\nexport type BillTasksDashboardRow = {\n id: string;\n label: string;\n /** One count per aging bucket, in bucket order. */\n counts: number[];\n total: number;\n /** 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 empty: boolean;\n};\n\nexport type BillTasksDashboardData = {\n sections: BillTasksDashboardSection[];\n grandTotals: number[];\n grandTotal: 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 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\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 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 row.counts[bucketIndex] = (row.counts[bucketIndex] ?? 0) + 1;\n row.total += 1;\n if (item.ref) row.refs[bucketIndex]?.push(item.ref);\n section.totals[bucketIndex] = (section.totals[bucketIndex] ?? 0) + 1;\n section.total += 1;\n grandTotals[bucketIndex] = (grandTotals[bucketIndex] ?? 0) + 1;\n grandTotal += 1;\n }\n\n return { sections: built, grandTotals, grandTotal };\n}\n"],"mappings":";AAAO,IAAM,uBAAuB;AAC7B,IAAM,2BAA2B;AA+IjC,SAAS,6BACd,OAC8B;AAC9B,MAAI,CAAC,MAAM,uBAAwB,QAAO;AAC1C,SAAO,MAAM,QAAQ,KAAK,CAAC,WAAW,OAAO,OAAO,KAAK;AAC3D;AA4GA,SAAS,YACP,QACA,MACyB;AACzB,QAAM,SAAS;AACf,SAAO,OAAO;AAAA,IACZ,KAAK,QAAQ,CAAC,QAAQ,OAAO,GAAG,MAAM,SAAY,CAAC,IAAI,CAAC,CAAC,KAAK,OAAO,GAAG,CAAC,CAAC,CAAC;AAAA,EAC7E;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,MA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AC,CAAC;AAAA,MAC5B;AACA,eAAS,IAAI,KAAK,GAAG;AACrB,cAAQ,KAAK,KAAK,GAAG;AACrB,cAAQ,QAAQ;AAAA,IAClB;AACA,UAAM,cAAc,0BAA0B,KAAK,SAAS,OAAO;AACnE,QAAI,OAAO,WAAW,KAAK,IAAI,OAAO,WAAW,KAAK,KAAK;AAC3D,QAAI,SAAS;AACb,QAAI,KAAK,IAAK,KAAI,KAAK,WAAW,GAAG,KAAK,KAAK,GAAG;AAClD,YAAQ,OAAO,WAAW,KAAK,QAAQ,OAAO,WAAW,KAAK,KAAK;AACnE,YAAQ,SAAS;AACjB,gBAAY,WAAW,KAAK,YAAY,WAAW,KAAK,KAAK;AAC7D,kBAAc;AAAA,EAChB;AAEA,SAAO,EAAE,UAAU,OAAO,aAAa,WAAW;AACpD;","names":["request","value"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mindbill/browser",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "description": "Framework-neutral browser client for the MindBill bill lifecycle",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",