@apextelemed/partner-core 0.25.0-dev.91 → 0.25.1

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.
@@ -0,0 +1,2954 @@
1
+ import { Accessor, Resource } from 'solid-js';
2
+ import { l as AddressVerifyResult, bD as CheckoutAddress, b8 as CatalogAvailabilityResult, cM as User, bR as DeliveryInfo, ch as RenewalStatus, c9 as PendingRenewalSurvey, O as AdminLifecycleBucket, C as AdminCustomerOverview, aB as AdminSubscriptionDetail, F as AdminCustomerRequest, cz as SupportThreadCategory, cu as SupportChannel, bA as CatalogProduct, aP as AffiliateConversion, aT as AffiliateDownlineMember, aQ as AffiliateDashboardLinks, aS as AffiliateDashboardStats, cd as PromoValidationResponse, bW as MemberOffer, b9 as CatalogClassification, bq as CatalogDoseModel, Y as AdminOrphanedDosePrice, a7 as AdminProduct, bw as CatalogItem, br as CatalogDoseSuggestion, by as CatalogMappableDrug, bt as CatalogEquivalentSuggestions, bB as CatalogReadiness, bn as CatalogConversionUndoResult, bh as CatalogConversionPreview, bd as CatalogConversionDoseMatch, bj as CatalogConversionSource, bc as CatalogConversionDose, bm as CatalogConversionUndoOptions, bb as CatalogConversionCommitResult, be as CatalogConversionFinding, ba as CatalogConversionChoice, g as AddPharmacyPlan, i as AddPharmacyResult, f as AddPharmacyMatchSource, a as AddPharmacyBody, d as AddPharmacyFinding, cO as UserSmsState, cN as UserSmsEvent } from './client-BsSc6e_K.js';
3
+ import { C as CartItem } from './cart-o6DpAu5y.js';
4
+ import './surveyV2-BgQHK0GE.js';
5
+ import { EmbedEvent } from '@apextelemed/survey-solid';
6
+ import { FlatStep as FlatStep$1 } from '@apextelemed/survey-core';
7
+ import { d as ResumedDraft, a as CartSnapshotLine, R as ResumedCart } from './cart-BwUwSzWh.js';
8
+
9
+ interface SurveyOption {
10
+ id: string;
11
+ text: string;
12
+ value: string;
13
+ }
14
+ interface VisibilityCondition {
15
+ conditionId: string;
16
+ questionId: string;
17
+ operator: string;
18
+ value: string;
19
+ }
20
+ interface SurveyQuestion {
21
+ id: string;
22
+ type: string;
23
+ text: string;
24
+ required: boolean;
25
+ options?: SurveyOption[];
26
+ helpText?: string;
27
+ visibilityConditions?: VisibilityCondition[];
28
+ }
29
+ interface FlatStep {
30
+ sectionIndex: number;
31
+ stepIndex: number;
32
+ sectionTitle: string;
33
+ stepTitle?: string;
34
+ stepDescription?: string;
35
+ questions: SurveyQuestion[];
36
+ }
37
+ interface DrugResult {
38
+ drugId: string;
39
+ drugName: string;
40
+ qualified: boolean;
41
+ disqualificationReason?: string;
42
+ isRecommended?: boolean;
43
+ recommendationReasons?: string[];
44
+ }
45
+ type AnswerValue = string | string[] | number | boolean | Record<string, unknown>;
46
+ type SurveyOutcome = {
47
+ kind: 'loading';
48
+ } | {
49
+ kind: 'needs_medication_selection';
50
+ } | {
51
+ kind: 'load_failed';
52
+ error: string;
53
+ } | {
54
+ kind: 'in_progress';
55
+ } | {
56
+ kind: 'disqualified';
57
+ reason: string;
58
+ } | {
59
+ kind: 'drug_selection';
60
+ drugs: DrugResult[];
61
+ } | {
62
+ kind: 'completed';
63
+ };
64
+ declare function isQuestionVisible(question: SurveyQuestion, answers: Record<string, AnswerValue>): boolean;
65
+ interface UseSurveyFlowOptions {
66
+ /** ms to wait on the completion screen before firing `onComplete`. Default 3000. */
67
+ completionRedirectDelayMs?: number;
68
+ }
69
+ interface SurveyFlow {
70
+ outcome: Accessor<SurveyOutcome>;
71
+ surveyTitle: Accessor<string>;
72
+ totalSteps: Accessor<number>;
73
+ currentStep: Accessor<number>;
74
+ step: Accessor<FlatStep | null>;
75
+ visibleQuestions: Accessor<SurveyQuestion[]>;
76
+ answers: Accessor<Record<string, AnswerValue>>;
77
+ setAnswer: (questionId: string, value: AnswerValue) => void;
78
+ validationError: Accessor<string | null>;
79
+ submitting: Accessor<boolean>;
80
+ next: () => Promise<void>;
81
+ back: () => void;
82
+ isLastStep: Accessor<boolean>;
83
+ selectedDrugId: Accessor<string>;
84
+ setSelectedDrugId: (id: string) => void;
85
+ confirmDrugSelection: () => Promise<void>;
86
+ }
87
+ /**
88
+ * The v1 survey flow.
89
+ *
90
+ * @deprecated Use {@link useSurveyV2Flow} instead. v1 cannot compose a
91
+ * questionnaire until a medication has already been chosen — it resolves its
92
+ * target from the cart or `medicationStore` and otherwise reports
93
+ * `needs_medication_selection`. v2 takes `drugIds` explicitly and can qualify a
94
+ * guest before an account exists. Kept for sites that have not migrated.
95
+ */
96
+ declare function useSurveyFlow(options?: UseSurveyFlowOptions): SurveyFlow;
97
+
98
+ /**
99
+ * Provider-aware CARD TOKENIZER — not AuthNet-only, despite its history.
100
+ * Dispatches on GET /config/payment: Authorize.Net tenants load Accept.js;
101
+ * QuickBooks/Intuit tenants tokenize against the returned `tokenizeUrl`; MX
102
+ * Merchant tenants vault the card with MX using a per-card session token; NMI
103
+ * tenants enter the card in Collect.js's hosted fields (see `hostedFields`).
104
+ * (Renamed from useCardTokenizer/acceptJs.ts, whose name cost real debugging time
105
+ * by implying the AuthNet path was the only one.)
106
+ */
107
+
108
+ /** One of the three card inputs a gateway can host in its own iframe. */
109
+ type HostedCardField = 'number' | 'expiry' | 'cvv';
110
+ interface CollectJs {
111
+ configure: (config: Record<string, unknown>) => void;
112
+ startPaymentRequest: () => void;
113
+ clearInputs?: () => void;
114
+ }
115
+ interface AcceptJsResponse {
116
+ opaqueData?: {
117
+ dataDescriptor: string;
118
+ dataValue: string;
119
+ };
120
+ messages: {
121
+ resultCode: 'Ok' | 'Error';
122
+ message: Array<{
123
+ code: string;
124
+ text: string;
125
+ }>;
126
+ };
127
+ }
128
+ declare global {
129
+ interface Window {
130
+ Accept?: {
131
+ dispatchData: (secureData: Record<string, unknown>, callback: (response: AcceptJsResponse) => void) => void;
132
+ };
133
+ CollectJS?: CollectJs;
134
+ }
135
+ }
136
+
137
+ declare const US_STATES: readonly string[];
138
+ /** Options for a state `<Select>`, labeled by full name. */
139
+ declare const US_STATE_OPTIONS: Array<{
140
+ value: string;
141
+ label: string;
142
+ }>;
143
+ /** US_STATES minus the tenant's `unavailableStates` and any `extraExcluded`. */
144
+ declare function availableStates(extraExcluded?: readonly string[]): string[];
145
+ /** `availableStates()` as `<Select>` options — use for state dropdowns. */
146
+ declare function availableStateOptions(extraExcluded?: readonly string[]): Array<{
147
+ value: string;
148
+ label: string;
149
+ }>;
150
+ /** The tenant's configured availability note (e.g. "…cannot provide
151
+ * medications to customers in Delaware."), or null when unrestricted. */
152
+ declare function stateAvailabilityNote(): string | null;
153
+ /**
154
+ * Coerce a state value into a canonical 2-letter abbreviation for the `<Select>`.
155
+ * Accepts an abbreviation in any case (`tx` → `TX`) or a full name
156
+ * (`Texas` → `TX`). Returns `''` for anything unrecognized so the field falls
157
+ * back to its placeholder and validation prompts the user to pick a state.
158
+ */
159
+ declare function normalizeState(input: string | null | undefined): string;
160
+ interface AddressValue {
161
+ street: string;
162
+ street2?: string;
163
+ city: string;
164
+ state: string;
165
+ zip: string;
166
+ }
167
+ interface AddressErrors {
168
+ street?: string;
169
+ city?: string;
170
+ state?: string;
171
+ zip?: string;
172
+ }
173
+ interface ValidateAddressOptions {
174
+ /** Also reject states in the tenant's `unavailableStates`. Turn on for
175
+ * SHIPPING addresses only — the dropdown already omits them, but a saved
176
+ * profile address can arrive prefilled with one. Billing stays unrestricted. */
177
+ enforceAvailability?: boolean;
178
+ }
179
+ /** `label` (e.g. "Billing") prefixes the messages; omit for the shipping form. */
180
+ declare function validateAddress(a: AddressValue, label?: string, opts?: ValidateAddressOptions): AddressErrors;
181
+ declare function hasErrors(e: AddressErrors): boolean;
182
+ interface UseAddressPairOptions {
183
+ /** Prefill the shipping address (e.g. from the member profile). */
184
+ initialShipping?: Partial<AddressValue>;
185
+ /** Prefill billing when it starts as an override; usually omitted. */
186
+ initialBilling?: Partial<AddressValue>;
187
+ /** Start with "billing same as shipping" checked. Default FALSE — see the
188
+ * useAddressPair docs for why the billing address is surfaced rather than
189
+ * assumed (AVS declines are otherwise invisible to the customer). */
190
+ billingSameAsShippingDefault?: boolean;
191
+ /** Override the deliverability verifier (defaults to `addressesApi.verify`).
192
+ * Injectable for testing / alternate providers. */
193
+ verify?: (a: CheckoutAddress) => Promise<AddressVerifyResult>;
194
+ }
195
+ interface AddressPair {
196
+ shipping: Accessor<AddressValue>;
197
+ setShippingField: (field: keyof AddressValue, value: string) => void;
198
+ setShipping: (patch: Partial<AddressValue>) => void;
199
+ billingSameAsShipping: Accessor<boolean>;
200
+ setBillingSameAsShipping: (v: boolean) => void;
201
+ billing: Accessor<AddressValue>;
202
+ setBillingField: (field: keyof AddressValue, value: string) => void;
203
+ /** True only when billing is a distinct override the user actually entered —
204
+ * i.e. "same as" is unchecked AND a billing field has been edited. Until then
205
+ * `billing`/`effectiveBilling` track live shipping. */
206
+ billingIsOverride: Accessor<boolean>;
207
+ /** Address to bill/charge to: live shipping unless billing is an override. */
208
+ effectiveBilling: Accessor<AddressValue>;
209
+ shippingErrors: Accessor<AddressErrors>;
210
+ billingErrors: Accessor<AddressErrors>;
211
+ /** Validate shipping (always) + billing (only when it's an override). Publishes
212
+ * errors to shippingErrors()/billingErrors() for inline display. Returns true if ok. */
213
+ validate: () => boolean;
214
+ /** Last deliverability result for the shipping address; null until verified or
215
+ * after any shipping edit. */
216
+ deliverability: Accessor<AddressVerifyResult | null>;
217
+ verifying: Accessor<boolean>;
218
+ /** Verify the shipping address's deliverability. No-ops (returns null) when the
219
+ * address is syntactically incomplete. Fails open (`unchecked`) on any error. */
220
+ verifyShipping: () => Promise<AddressVerifyResult | null>;
221
+ /** Adopt the verifier's normalized address into the shipping fields (used for a
222
+ * `corrected` result's "use suggested address" action). */
223
+ applyNormalized: () => void;
224
+ }
225
+ /**
226
+ * Shared shipping + billing address state for checkout-bearing flows. Until the
227
+ * user actually edits a billing field, `billing` mirrors the LIVE shipping
228
+ * address — so the billing form always reads as populated, stays in sync if
229
+ * shipping is later corrected, and the address charged always matches what's
230
+ * displayed. The first billing edit "forks" billing into an independent
231
+ * override; from then on it holds the user's entered values.
232
+ *
233
+ * "Billing same as shipping" defaults OFF, and consumers render the billing
234
+ * fields unconditionally. The card's billing address is what the gateway runs
235
+ * AVS against, so a mismatch there is charged back to the customer as a bare
236
+ * "This transaction has been declined." Defaulting the box on and hiding the
237
+ * fields behind it meant a customer whose card bills to a different address
238
+ * had no obvious way to notice, let alone fix it. Showing the fields (mirrored
239
+ * from shipping, so the common case still needs no typing) makes the address
240
+ * being billed visible before the charge rather than after the decline.
241
+ */
242
+ declare function useAddressPair(options?: UseAddressPairOptions): AddressPair;
243
+
244
+ interface CatalogAvailabilityDecision {
245
+ /** Requested ids confirmed unavailable (available:false && checked:true),
246
+ * in the result's order. Always empty when `degraded`. */
247
+ unavailableIds: string[];
248
+ /** True only when at least one id is confirmed unavailable and the
249
+ * answer was NOT degraded — the one signal a caller should ever block on. */
250
+ blocking: boolean;
251
+ /** True when the backend fell back to fail-open because Apex was
252
+ * unreachable (every id answered `available: true`). Advisory: surfaces
253
+ * for telemetry/UI, never a reason to block. */
254
+ degraded: boolean;
255
+ }
256
+ /**
257
+ * Pure response → decision mapping, kept separate from the hook so it's
258
+ * unit-testable without Solid or a network mock. `null`/`undefined` (no
259
+ * result yet, or a request that errored) decides exactly like an empty,
260
+ * non-degraded result: nothing blocks.
261
+ */
262
+ declare function deriveCatalogAvailabilityDecision(result: CatalogAvailabilityResult | null | undefined): CatalogAvailabilityDecision;
263
+ interface CatalogAvailabilityState {
264
+ /** True while a check is in flight (including the debounce window). */
265
+ loading: Accessor<boolean>;
266
+ /** True only when at least one requested id is confirmed unavailable in the
267
+ * current state and the answer wasn't degraded. The one flag a submit/pay
268
+ * guard should gate on. */
269
+ blocking: Accessor<boolean>;
270
+ /** True when the last check fell back to fail-open (Apex unreachable).
271
+ * Never gate blocking on this — it means the opposite. */
272
+ degraded: Accessor<boolean>;
273
+ /** Requested ids currently confirmed unavailable, in result order. */
274
+ unavailableIds: Accessor<string[]>;
275
+ /** Per-id lookup over `unavailableIds`. */
276
+ isUnavailable: (id: string) => boolean;
277
+ /** Resolves once no check is pending (debouncing or in flight). A submit
278
+ * handler awaits this before reading `blocking()`: otherwise a patient who
279
+ * changes state and clicks Pay inside the debounce window pays unchecked.
280
+ * Never rejects. */
281
+ settled: () => Promise<void>;
282
+ }
283
+ /**
284
+ * Debounced (~300ms) per-item availability check, re-run whenever `ids` or
285
+ * `state` change. Skips the call entirely when there are no ids or `state`
286
+ * isn't a 2-letter code — no point asking, and it keeps an empty cart or an
287
+ * unfinished address field from firing a request. Last request wins: a
288
+ * response for a superseded (ids, state) pair is dropped instead of
289
+ * clobbering a newer one. Any thrown error (network, timeout, a thrown
290
+ * ApiError) is treated as "not blocking" — this check is advisory and must
291
+ * never itself stop a checkout the backend would otherwise allow.
292
+ */
293
+ declare function useCatalogAvailability(ids: Accessor<string[]>, state: Accessor<string | null | undefined>): CatalogAvailabilityState;
294
+ /**
295
+ * Standard copy for a line a patient can't have shipped to their chosen
296
+ * state: "<item> isn't available for delivery to <State>." `state` is a
297
+ * 2-letter code; rendered via address.ts's canonical full-name lookup so it
298
+ * reads the same as the rest of the address UI ("Arizona", not "AZ").
299
+ */
300
+ declare function catalogUnavailableMessage(itemName: string, state: string): string;
301
+
302
+ interface RequestStatus {
303
+ status: 'pending' | 'approved' | 'denied' | 'new';
304
+ drugName?: string;
305
+ drugId?: string;
306
+ dosage?: string;
307
+ price?: number;
308
+ /** Locked catalog price for this prescription (cents). */
309
+ priceCents?: number;
310
+ /** Locked discount applied at request creation (cents). */
311
+ discountCents?: number;
312
+ /** Locked total to charge (cents). */
313
+ finalCents?: number;
314
+ /** The request has already been paid for. Guards against re-charging a request
315
+ * that was paid up front (pay-before-review) if the checkout is revisited. */
316
+ paymentConfirmed?: boolean;
317
+ reason?: string;
318
+ requestId?: string;
319
+ [key: string]: unknown;
320
+ }
321
+ type CheckoutOutcome = {
322
+ kind: 'loading';
323
+ } | {
324
+ kind: 'load_failed';
325
+ error: string;
326
+ } | {
327
+ kind: 'no_prescription';
328
+ } | {
329
+ kind: 'pending_review';
330
+ prescription: RequestStatus;
331
+ } | {
332
+ kind: 'denied';
333
+ prescription: RequestStatus;
334
+ } | {
335
+ kind: 'awaiting_purchase';
336
+ prescription: RequestStatus;
337
+ } | {
338
+ kind: 'completed';
339
+ };
340
+ interface PricingBreakdown {
341
+ baseMedicationCents: number;
342
+ promoDiscountCents: number;
343
+ finalMedicationCents: number;
344
+ promoCode?: string;
345
+ }
346
+ declare function formatCardNumber(raw: string): string;
347
+ declare function formatExpiry(raw: string): string;
348
+ declare function formatCvv(raw: string): string;
349
+ interface UseCheckoutFlowOptions {
350
+ /** The prescription request ID to check out. Typically read from a URL query param by the site. If absent, the hook falls back to `user.apex_request_id` for legacy single-request flows. */
351
+ requestId?: string;
352
+ /** Specific drug (Apex drugId) within a multi-drug request to purchase. When set, the backend returns THAT line item's status + locked price, so an approved item in a partially-approved request is purchasable independently. */
353
+ drugId?: string;
354
+ /**
355
+ * Pay-before-review: treat a `pending` (not-yet-approved) request as
356
+ * purchasable, so the card form is shown immediately after the survey instead
357
+ * of only after a prescriber approves. Off by default — the standard flow
358
+ * collects payment only on an `approved` request. When on, the backend's
359
+ * approved+paid fulfillment gate still holds the order until a prescriber
360
+ * approves; this only moves WHEN the card is collected, not what ships.
361
+ */
362
+ allowPendingPurchase?: boolean;
363
+ }
364
+ interface CheckoutFlow {
365
+ outcome: Accessor<CheckoutOutcome>;
366
+ profile: Accessor<User | null>;
367
+ /** Shipping + billing address state (pre-filled from the profile). Render with
368
+ * <AddressFields address={flow.address} />. */
369
+ address: AddressPair;
370
+ pricing: Accessor<PricingBreakdown>;
371
+ /** Per-item deliverability for this request's drug in the current shipping
372
+ * state (a catalog item routed to a pharmacy that doesn't serve it). Per
373
+ * ITEM, on top of the tenant-level `unavailableStates` gating. Re-runs
374
+ * debounced on shipping-state changes; `submit()` refuses while
375
+ * `availability.blocking()` is true. */
376
+ availability: CatalogAvailabilityState;
377
+ hasPaymentMethod: Accessor<boolean>;
378
+ /** True once the card tokenizer is ready. Gate submission on this. */
379
+ tokenizerReady: Accessor<boolean>;
380
+ /** @deprecated alias of tokenizerReady (pre-rename name). */
381
+ acceptJsLoaded: Accessor<boolean>;
382
+ /** Non-null when payment setup failed to initialize (config/SDK load) —
383
+ * render as a banner; the pay button will never enable in this state. */
384
+ /** Tokenizer init failure, or null. */
385
+ tokenizerError: Accessor<string | null>;
386
+ /** @deprecated alias of tokenizerError (pre-rename name). */
387
+ acceptJsError: Accessor<string | null>;
388
+ cardNumber: Accessor<string>;
389
+ setCardNumber: (v: string) => void;
390
+ expiry: Accessor<string>;
391
+ setExpiry: (v: string) => void;
392
+ cvv: Accessor<string>;
393
+ /**
394
+ * True when the card is typed into the gateway's own hosted fields (NMI's
395
+ * Collect.js) instead of cardNumber/expiry/cvv: render three containers and
396
+ * pass each to registerCardField instead of card inputs.
397
+ */
398
+ hostedCardFields: Accessor<boolean>;
399
+ /** Ref callback for a hosted card field container: `ref={(el) => flow.registerCardField('number', el)}`. */
400
+ registerCardField: (field: HostedCardField, el: HTMLElement) => void;
401
+ setCvv: (v: string) => void;
402
+ paymentError: Accessor<string | null>;
403
+ processing: Accessor<boolean>;
404
+ canSubmit: Accessor<boolean>;
405
+ submit: () => Promise<void>;
406
+ }
407
+ declare function useCheckoutFlow(options?: UseCheckoutFlowOptions): CheckoutFlow;
408
+
409
+ type CartCheckoutOutcome =
410
+ /** Initial profile load in flight. */
411
+ {
412
+ kind: 'loading';
413
+ }
414
+ /** No authenticated session. Sites route to signup/login (for a model-3
415
+ * tenant, typically RegisterPage) and back here afterwards. */
416
+ | {
417
+ kind: 'needs_auth';
418
+ }
419
+ /** The cart holds no one-time-purchasable items (empty, or subscription
420
+ * items only). Sites route to the catalog. */
421
+ | {
422
+ kind: 'needs_cart';
423
+ }
424
+ /** Ready: order summary + address + card form are live. */
425
+ | {
426
+ kind: 'in_progress';
427
+ }
428
+ /** A submit failed ambiguously; the flow is checking the order history
429
+ * before letting the user near the Pay button again. */
430
+ | {
431
+ kind: 'reconciling';
432
+ }
433
+ /** Charge succeeded (or was confirmed via reconcile). */
434
+ | {
435
+ kind: 'completed';
436
+ orderId?: string;
437
+ amountCents?: number;
438
+ };
439
+ interface CartCheckoutPricing {
440
+ /** Quantity-honoring subtotal of the purchasable items, in cents. */
441
+ subtotalCents: number;
442
+ /** Client-side ESTIMATE from the applied promo — the server re-validates the
443
+ * code and stacks active sales itself, so the charged amount can differ.
444
+ * `completed.amountCents` carries the authoritative figure. */
445
+ promoDiscountCents: number;
446
+ estimatedTotalCents: number;
447
+ promoCode?: string;
448
+ }
449
+ interface CartCheckoutFlow {
450
+ outcome: Accessor<CartCheckoutOutcome>;
451
+ profile: Accessor<User | null>;
452
+ /** Shipping + billing address state (pre-filled from the profile). Render
453
+ * with <AddressFields address={flow.address} />. */
454
+ address: AddressPair;
455
+ /** The one-time-purchasable subset of the cart — what will actually be
456
+ * charged. Subscription-flagged items are excluded (the backend 400s a
457
+ * checkout containing one). */
458
+ items: Accessor<CartItem[]>;
459
+ /** Subscription-flagged cart items excluded from this purchase, so pages can
460
+ * tell the customer those aren't part of the order. */
461
+ skippedSubscriptionItems: Accessor<CartItem[]>;
462
+ /** Per-item deliverability for the cart's lines in the current shipping
463
+ * state — a catalog item routed to a pharmacy that doesn't serve that
464
+ * state. Per ITEM, on top of (not instead of) the tenant-level
465
+ * `unavailableStates` gating the address dropdown already applies. Re-runs
466
+ * debounced whenever the cart or shipping state changes; `submit()` refuses
467
+ * while `availability.blocking()` is true. */
468
+ availability: CatalogAvailabilityState;
469
+ pricing: Accessor<CartCheckoutPricing>;
470
+ /** True once the card tokenizer is ready. Gate submission on this. */
471
+ tokenizerReady: Accessor<boolean>;
472
+ /** @deprecated alias of tokenizerReady (pre-rename name). */
473
+ acceptJsLoaded: Accessor<boolean>;
474
+ /** Non-null when payment setup failed to initialize (config/SDK load) —
475
+ * render as a banner; the pay button will never enable in this state. */
476
+ /** Tokenizer init failure, or null. */
477
+ tokenizerError: Accessor<string | null>;
478
+ /** @deprecated alias of tokenizerError (pre-rename name). */
479
+ acceptJsError: Accessor<string | null>;
480
+ cardNumber: Accessor<string>;
481
+ setCardNumber: (v: string) => void;
482
+ expiry: Accessor<string>;
483
+ setExpiry: (v: string) => void;
484
+ cvv: Accessor<string>;
485
+ /**
486
+ * True when the card is typed into the gateway's own hosted fields (NMI's
487
+ * Collect.js) instead of cardNumber/expiry/cvv: render three containers and
488
+ * pass each to registerCardField instead of card inputs.
489
+ */
490
+ hostedCardFields: Accessor<boolean>;
491
+ /** Ref callback for a hosted card field container: `ref={(el) => flow.registerCardField('number', el)}`. */
492
+ registerCardField: (field: HostedCardField, el: HTMLElement) => void;
493
+ setCvv: (v: string) => void;
494
+ paymentError: Accessor<string | null>;
495
+ processing: Accessor<boolean>;
496
+ canSubmit: Accessor<boolean>;
497
+ submit: () => Promise<void>;
498
+ }
499
+ /**
500
+ * One-time cart checkout (model-3 support): charges the cart's non-subscription
501
+ * items once via POST /payments/checkout. No prescription, no recurring
502
+ * subscription, no card kept on file. Requires an authenticated member (the
503
+ * backend route is member-JWT only) — unauthenticated mounts emit `needs_auth`
504
+ * for the site to route to its signup/register page.
505
+ */
506
+ declare function useCartCheckoutFlow(): CartCheckoutFlow;
507
+
508
+ interface SmsConsentOffer {
509
+ /** The consent wording, verbatim. */
510
+ text: string;
511
+ /** Version of `text`; goes back with the grant. */
512
+ textVersion: string;
513
+ /** Sender name the wording refers to, when the tenant set one. */
514
+ brandName?: string;
515
+ termsUrl?: string;
516
+ privacyUrl?: string;
517
+ }
518
+ /** What flows put on the register / register-and-subscribe / PATCH /users/me wire. */
519
+ interface SmsConsentGrant {
520
+ granted: true;
521
+ textVersion: string;
522
+ }
523
+ interface SmsConsent {
524
+ /**
525
+ * The wording to show beside the checkbox. null while the tenant's config is
526
+ * loading, when texts are off, or when it couldn't be loaded — render nothing.
527
+ */
528
+ offer: Accessor<SmsConsentOffer | null>;
529
+ /** True when the person has ticked the box. Always false while `enabled()` is false. */
530
+ checked: Accessor<boolean>;
531
+ setChecked: (v: boolean) => void;
532
+ /** False while the phone is empty or invalid: show the box disabled, with `hint()`. */
533
+ enabled: Accessor<boolean>;
534
+ /** Why the box is disabled; null when it isn't. */
535
+ hint: Accessor<string | null>;
536
+ /** The grant to send, or undefined to send nothing (unchecked / disabled / no offer). */
537
+ grant: () => SmsConsentGrant | undefined;
538
+ /**
539
+ * What to persist in the flow's draft: the version of the wording the person
540
+ * ticked, or undefined. A version rather than a boolean so a restored draft
541
+ * only re-ticks the box when the wording is still the one they agreed to.
542
+ */
543
+ draftVersion: Accessor<string | undefined>;
544
+ }
545
+ declare function useSmsConsent(phone: Accessor<string>, restoredVersion?: string): SmsConsent;
546
+
547
+ type SignupOutcome = {
548
+ kind: 'in_progress';
549
+ }
550
+ /** `requireCart` is on and the cart is empty — the site should send the
551
+ * visitor to its catalog before any step is shown. */
552
+ | {
553
+ kind: 'needs_cart';
554
+ } | {
555
+ kind: 'submitting';
556
+ }
557
+ /** Register+charge response was lost mid-flight; we're checking whether the
558
+ * account was actually created before letting the user retry. */
559
+ | {
560
+ kind: 'reconciling';
561
+ } | {
562
+ kind: 'completed';
563
+ };
564
+ interface UseSignupFlowOptions {
565
+ /** Membership amount charged on signup, in cents. Required — sites set their own pricing. */
566
+ membershipAmountCents: number;
567
+ /** Billing interval in days. Default 30. */
568
+ membershipIntervalDays?: number;
569
+ /** Label used when the cart is empty. Defaults to "Membership". */
570
+ membershipProductLabel?: string;
571
+ /**
572
+ * Refuse to start with an empty cart. The backend only accepts a cart-less
573
+ * signup for a membership tenant (deferred fulfillment with a configured
574
+ * membership product); every other tenant fans out one subscription per
575
+ * cart item and rejects an empty cart at submit — after the visitor has
576
+ * already filled in account, address and card. With this on, the flow
577
+ * reports `needs_cart` on mount (and again at submit, in case a peer tab
578
+ * emptied the shared cart) so the site can redirect to its catalog first.
579
+ * Default false, which keeps the membership-tenant behavior.
580
+ */
581
+ requireCart?: boolean;
582
+ /**
583
+ * The verified savings member id to link to the new account (same payload
584
+ * field as the subscription-intake flow). Read at submit time; null/empty
585
+ * sends nothing.
586
+ */
587
+ savingsMemberId?: () => string | null;
588
+ }
589
+ interface SignupFlow {
590
+ step: Accessor<number>;
591
+ /** True only on the very last step (Confirm). */
592
+ isConfirmStep: Accessor<boolean>;
593
+ next: () => Promise<void>;
594
+ back: () => void;
595
+ error: Accessor<string | null>;
596
+ /** True while tokenizing the card on the Payment step. */
597
+ tokenizing: Accessor<boolean>;
598
+ /** True while submitting on the Confirm step. */
599
+ submitting: Accessor<boolean>;
600
+ outcome: Accessor<SignupOutcome>;
601
+ /** True once the card tokenizer is ready. The Payment step "Continue" button gates on this. */
602
+ /** True once the card tokenizer is ready (config loaded; for AuthNet, Accept.js loaded too). Gate submission on this. */
603
+ tokenizerReady: Accessor<boolean>;
604
+ /** @deprecated alias of tokenizerReady (pre-rename name). */
605
+ acceptJsReady: Accessor<boolean>;
606
+ /** Non-null when payment setup failed to initialize — render as a banner;
607
+ * the Payment step can never proceed in this state. */
608
+ /** Tokenizer init failure, or null. */
609
+ tokenizerError: Accessor<string | null>;
610
+ /** @deprecated alias of tokenizerError (pre-rename name). */
611
+ acceptJsError: Accessor<string | null>;
612
+ firstName: Accessor<string>;
613
+ setFirstName: (v: string) => void;
614
+ lastName: Accessor<string>;
615
+ setLastName: (v: string) => void;
616
+ email: Accessor<string>;
617
+ setEmail: (v: string) => void;
618
+ password: Accessor<string>;
619
+ setPassword: (v: string) => void;
620
+ dateOfBirth: Accessor<string>;
621
+ setDateOfBirth: (v: string) => void;
622
+ phone: Accessor<string>;
623
+ setPhone: (v: string) => void;
624
+ /**
625
+ * Optional opt-in to text messages. `smsConsent.offer()` is null unless the
626
+ * tenant texts customers; render the checkbox only when it isn't. Never
627
+ * required — leaving it unticked sends nothing and signup proceeds.
628
+ */
629
+ smsConsent: SmsConsent;
630
+ street: Accessor<string>;
631
+ setStreet: (v: string) => void;
632
+ city: Accessor<string>;
633
+ setCity: (v: string) => void;
634
+ state: Accessor<string>;
635
+ setState: (v: string) => void;
636
+ zip: Accessor<string>;
637
+ setZip: (v: string) => void;
638
+ cardNumber: Accessor<string>;
639
+ setCardNumber: (v: string) => void;
640
+ expiry: Accessor<string>;
641
+ setExpiry: (v: string) => void;
642
+ cvv: Accessor<string>;
643
+ setCvv: (v: string) => void;
644
+ /**
645
+ * True when the card is typed into the gateway's own hosted fields (NMI's
646
+ * Collect.js) instead of cardNumber/expiry/cvv: render three containers and
647
+ * pass each to registerCardField instead of card inputs.
648
+ */
649
+ hostedCardFields: Accessor<boolean>;
650
+ /** Ref callback for a hosted card field container: `ref={(el) => flow.registerCardField('number', el)}`. */
651
+ registerCardField: (field: HostedCardField, el: HTMLElement) => void;
652
+ /**
653
+ * Optional promo / referral code applied at submit. Not persisted to the
654
+ * draft — codes can change and shouldn't survive a refresh. Sites surface
655
+ * this via `<SignupPage promoField={...}>`.
656
+ */
657
+ promoCode: Accessor<string>;
658
+ setPromoCode: (v: string) => void;
659
+ /** Submit the signup at the Confirm step. */
660
+ submit: () => Promise<void>;
661
+ }
662
+ declare function useSignupFlow(options: UseSignupFlowOptions): SignupFlow;
663
+
664
+ type RegisterOutcome = {
665
+ kind: 'in_progress';
666
+ }
667
+ /** Emitted on mount when a session already exists — there is nothing to
668
+ * register. Sites route back to wherever sent the visitor here (for a
669
+ * model-3 tenant, typically the one-time checkout). */
670
+ | {
671
+ kind: 'already_authenticated';
672
+ } | {
673
+ kind: 'submitting';
674
+ }
675
+ /** Register response was lost mid-flight; we're checking whether the account
676
+ * was actually created (by logging in) before letting the user retry. */
677
+ | {
678
+ kind: 'reconciling';
679
+ } | {
680
+ kind: 'completed';
681
+ };
682
+ interface RegisterFlow {
683
+ step: Accessor<number>;
684
+ /** True only on the very last step (Confirm). */
685
+ isConfirmStep: Accessor<boolean>;
686
+ next: () => Promise<void>;
687
+ back: () => void;
688
+ error: Accessor<string | null>;
689
+ /** True while submitting on the Confirm step. */
690
+ submitting: Accessor<boolean>;
691
+ outcome: Accessor<RegisterOutcome>;
692
+ firstName: Accessor<string>;
693
+ setFirstName: (v: string) => void;
694
+ lastName: Accessor<string>;
695
+ setLastName: (v: string) => void;
696
+ email: Accessor<string>;
697
+ setEmail: (v: string) => void;
698
+ password: Accessor<string>;
699
+ setPassword: (v: string) => void;
700
+ dateOfBirth: Accessor<string>;
701
+ setDateOfBirth: (v: string) => void;
702
+ phone: Accessor<string>;
703
+ setPhone: (v: string) => void;
704
+ /**
705
+ * Optional opt-in to text messages. `smsConsent.offer()` is null unless the
706
+ * tenant texts customers; render the checkbox only when it isn't. Never
707
+ * required — leaving it unticked sends nothing and registration proceeds.
708
+ */
709
+ smsConsent: SmsConsent;
710
+ street: Accessor<string>;
711
+ setStreet: (v: string) => void;
712
+ city: Accessor<string>;
713
+ setCity: (v: string) => void;
714
+ state: Accessor<string>;
715
+ setState: (v: string) => void;
716
+ zip: Accessor<string>;
717
+ setZip: (v: string) => void;
718
+ /** Submit the registration at the Confirm step. */
719
+ submit: () => Promise<void>;
720
+ }
721
+ /**
722
+ * Non-subscribing signup (model-3 support): creates an account via
723
+ * POST /auth/register and establishes a session — no membership charge, no
724
+ * recurring subscription, no card collected. The subscribing signup
725
+ * (useSignupFlow / SignupPage) is untouched and remains the right surface for
726
+ * membership tenants.
727
+ *
728
+ * Backend note: POST /auth/register is functional but currently marked
729
+ * @deprecated server-side (its successor is the subscribing
730
+ * register-and-subscribe). Model-3 is exactly the use case that endpoint still
731
+ * serves; un-deprecating it is a tracked backend follow-up. It leaves the new
732
+ * user's `payment_status` as 'pending' — the one-time checkout charge does not
733
+ * change that today (see the "requirePaidSubscription 402" backend card).
734
+ */
735
+ declare function useRegisterFlow(): RegisterFlow;
736
+
737
+ type SubscribeOutcome = {
738
+ kind: 'loading';
739
+ } | {
740
+ kind: 'needs_auth';
741
+ } | {
742
+ kind: 'needs_cart';
743
+ } | {
744
+ kind: 'already_subscribed';
745
+ } | {
746
+ kind: 'in_progress';
747
+ }
748
+ /** Submit response was lost mid-flight; re-checking server state before we
749
+ * let the user retry, so we never double-charge a charge that succeeded. */
750
+ | {
751
+ kind: 'reconciling';
752
+ } | {
753
+ kind: 'completed';
754
+ };
755
+ interface UseSubscribeFlowOptions {
756
+ /**
757
+ * @deprecated The amount shown and charged now comes from the backend's
758
+ * quote (`POST /subscriptions/preview`), which prices the cart exactly as
759
+ * the charge will. This value is only used as a last-resort estimate for a
760
+ * backend that predates the preview endpoint AND a cart with no prices.
761
+ */
762
+ membershipAmountCents: number;
763
+ /** Billing interval in days. Default 30. */
764
+ membershipIntervalDays?: number;
765
+ }
766
+ /** What the page shows as "due today", and where the number came from. */
767
+ interface SubscribeQuote {
768
+ /** 'server': the backend's own quote — the number the card will be charged.
769
+ * 'estimate': computed from cart prices because the backend has no preview
770
+ * endpoint yet; correct for per-product tenants, which is every tenant
771
+ * without a membership product. */
772
+ source: 'server' | 'estimate';
773
+ model: 'membership' | 'per_product';
774
+ intervalDays: number;
775
+ lines: Array<{
776
+ productId: string;
777
+ productName: string;
778
+ dosage: string | null;
779
+ quantity: number;
780
+ amountCents: number;
781
+ }>;
782
+ subtotalCents: number;
783
+ discountCents: number;
784
+ totalCents: number;
785
+ }
786
+ interface SubscribeFlow {
787
+ outcome: Accessor<SubscribeOutcome>;
788
+ /** True once the card tokenizer is ready (config loaded; for AuthNet, Accept.js loaded too). Gate submission on this. */
789
+ tokenizerReady: Accessor<boolean>;
790
+ /** @deprecated alias of tokenizerReady (pre-rename name). */
791
+ acceptJsReady: Accessor<boolean>;
792
+ /** Non-null when payment setup failed to initialize — render as a banner. */
793
+ /** Tokenizer init failure, or null. */
794
+ tokenizerError: Accessor<string | null>;
795
+ /** @deprecated alias of tokenizerError (pre-rename name). */
796
+ acceptJsError: Accessor<string | null>;
797
+ error: Accessor<string | null>;
798
+ submitting: Accessor<boolean>;
799
+ /** The amount due today, server-quoted when the backend supports it. Null
800
+ * while it loads. */
801
+ quote: Accessor<SubscribeQuote | null>;
802
+ /** The backend refused to quote (e.g. this tenant needs a completed survey
803
+ * first). The same refusal the charge would give, surfaced before the
804
+ * customer types a card number. Submission is blocked while set. */
805
+ quoteError: Accessor<string | null>;
806
+ street: Accessor<string>;
807
+ setStreet: (v: string) => void;
808
+ city: Accessor<string>;
809
+ setCity: (v: string) => void;
810
+ state: Accessor<string>;
811
+ setState: (v: string) => void;
812
+ zip: Accessor<string>;
813
+ setZip: (v: string) => void;
814
+ /** Per-item deliverability for the cart's lines in the address state above
815
+ * — a catalog item routed to a pharmacy that doesn't serve it. Per ITEM,
816
+ * on top of the tenant-level `unavailableStates` gating `validate()`
817
+ * already applies. `submit()` refuses to charge while
818
+ * `availability.blocking()` is true. */
819
+ availability: CatalogAvailabilityState;
820
+ /** The state the Rx ships to, which is what `availability` checks. The-backend
821
+ * sends the profile address to Apex and falls back to the billing address only
822
+ * when the profile has none (the-backend `routes/subscriptions.ts`, create:
823
+ * `state: userRow.state || billingAddress?.state`), so editing the billing
824
+ * state here doesn't move the shipment. */
825
+ shipState: Accessor<string>;
826
+ cardNumber: Accessor<string>;
827
+ setCardNumber: (v: string) => void;
828
+ expiry: Accessor<string>;
829
+ setExpiry: (v: string) => void;
830
+ cvv: Accessor<string>;
831
+ setCvv: (v: string) => void;
832
+ /**
833
+ * True when the card is typed into the gateway's own hosted fields (NMI's
834
+ * Collect.js) instead of cardNumber/expiry/cvv: render three containers and
835
+ * pass each to registerCardField instead of card inputs.
836
+ */
837
+ hostedCardFields: Accessor<boolean>;
838
+ /** Ref callback for a hosted card field container: `ref={(el) => flow.registerCardField('number', el)}`. */
839
+ registerCardField: (field: HostedCardField, el: HTMLElement) => void;
840
+ submit: () => Promise<void>;
841
+ }
842
+ declare function useSubscribeFlow(options: UseSubscribeFlowOptions): SubscribeFlow;
843
+
844
+ interface DashboardSubscription {
845
+ id: string;
846
+ status: 'active' | 'paused' | 'cancelled';
847
+ nextBillingDate?: string;
848
+ amount?: number;
849
+ [key: string]: unknown;
850
+ }
851
+ type RxRequestStatus = 'pending' | 'approved' | 'denied' | 'shipped' | 'new' | 'processing' | 'completed';
852
+ interface DashboardRxStatus {
853
+ status: RxRequestStatus;
854
+ reason?: string;
855
+ delivery?: DeliveryInfo | null;
856
+ [key: string]: unknown;
857
+ }
858
+ interface DashboardRxListItem {
859
+ requestId: string;
860
+ status: RxRequestStatus;
861
+ drugId?: string;
862
+ drugName?: string;
863
+ dosage?: string;
864
+ priceCents?: number;
865
+ paymentConfirmed?: boolean;
866
+ pharmacySent?: boolean;
867
+ reason?: string;
868
+ createdAt: string;
869
+ delivery?: DeliveryInfo | null;
870
+ renewal?: {
871
+ renewalId: string;
872
+ cycleNumber: number;
873
+ status: RenewalStatus;
874
+ pharmacyFillDate: string | null;
875
+ } | null;
876
+ }
877
+ interface DashboardActivityItem {
878
+ id: string;
879
+ label: string;
880
+ /** Relative-time string like "5m ago" or a fallback like "Next bill: May 4". */
881
+ time: string;
882
+ /** Single-character symbol or short emoji indicating the kind of event. Sites can map these to icons. */
883
+ icon: string;
884
+ }
885
+ interface DashboardData {
886
+ profile: Resource<User | null>;
887
+ subscription: Resource<DashboardSubscription | null>;
888
+ rxStatus: Resource<DashboardRxStatus | null>;
889
+ rxList: Resource<DashboardRxListItem[]>;
890
+ /** Re-fetch the prescription list (e.g. after canceling a request). */
891
+ refetchRxList: () => void;
892
+ pendingSurveys: Resource<PendingRenewalSurvey[]>;
893
+ /** First name from profile or authStore, falling back to "Member". */
894
+ displayName: () => string;
895
+ /** Recent activity feed derived from profile + subscription + rxStatus. */
896
+ activity: () => DashboardActivityItem[];
897
+ /**
898
+ * Non-null when any dashboard read failed. A transient 500 used to render as
899
+ * genuine emptiness ("No prescriptions"); surface this and offer `retry()`
900
+ * instead of presenting a failure as truth. Individual resources also carry
901
+ * a real `.error` now — but their value reads stay safe (empty/null
902
+ * fallback), so existing consumers never crash on an errored read.
903
+ */
904
+ error: () => string | null;
905
+ /** Re-fetch every dashboard resource (use from the error state's retry CTA). */
906
+ retry: () => void;
907
+ }
908
+ declare function formatRelativeTime(dateStr: string): string;
909
+ /**
910
+ * Loads the data needed for the patient dashboard. No JSX — sites compose
911
+ * their own layouts on top of this. Auth/admin guards are intentionally
912
+ * not bundled here; the consuming site handles routing.
913
+ *
914
+ * Pass `opts.authToken` (a reactive accessor) to load the whole dashboard AS
915
+ * another user — e.g. an admin "view as customer" preview using a short-lived
916
+ * impersonation token. When provided, every read carries that token instead of
917
+ * the auth store's session, so it never touches the caller's own login.
918
+ */
919
+ declare function useDashboardData(opts?: {
920
+ authToken?: () => string | undefined;
921
+ }): DashboardData;
922
+
923
+ type TrackingUrlCarrier = 'fedex' | 'ups' | 'usps';
924
+ declare function buildTrackingUrl(delivery: DeliveryInfo | null | undefined): string | null;
925
+
926
+ /**
927
+ * Pure derivation logic for the member portal order tracker and refill timeline.
928
+ *
929
+ * Design intent ("Apothecary" direction): one continuous vertical thread of
930
+ * fulfillment "beads". The thread fills to wherever REAL backend data reaches and
931
+ * never fabricates a state. Today the backend reliably exposes
932
+ * pending/approved/denied/call_requested (+ shipped/delivery/renewal when present),
933
+ * so beads beyond the known state render as honest "upcoming" nodes.
934
+ *
935
+ * No JSX and no data-fetching: the `MemberPortal` page maps its dashboard
936
+ * resources into the small `TrackerRequest`/`TrackerSubscription` input shapes
937
+ * below and renders the returned view. Kept framework-light and fully testable
938
+ * (`now` is injected — no `Date.now()` inside the derivations).
939
+ */
940
+
941
+ type TrackerRequestStatus = 'pending' | 'approved' | 'denied' | 'call_requested' | 'pharmacy' | 'shipped';
942
+ interface TrackerRequest {
943
+ status: TrackerRequestStatus;
944
+ createdAt: string | null;
945
+ updatedAt: string | null;
946
+ dosage?: string;
947
+ delivery: DeliveryInfo | null;
948
+ /**
949
+ * The day this Rx is due at the pharmacy (`YYYY-MM-DD`), from the backend's
950
+ * renewal schedule. An approved renewal is transmitted on its fill date, not
951
+ * at approval, so this bead can be the member's view for days — without the
952
+ * date it reads as a stall rather than a plan.
953
+ *
954
+ * The backend sends it only while the Rx is approved and still waiting, and
955
+ * withholds a date that has already passed, so it is safe to render as-is.
956
+ */
957
+ pharmacySendDate?: string | null;
958
+ }
959
+ type TrackerSubscriptionStatus = 'active' | 'paused' | 'past_due' | 'cancelled' | 'suspended' | 'expired';
960
+ interface TrackerSubscription {
961
+ status: TrackerSubscriptionStatus;
962
+ /**
963
+ * BILLING mirror — it moves only when a charge succeeds. Kept as the fallback
964
+ * estimate for partners without renewals, but it is NOT a fill date: a $0
965
+ * comped subscription never charges and freezes this at signup, and an
966
+ * ARB→platform migration deliberately leaves it stale. Prefer `nextFillDate`.
967
+ */
968
+ currentPeriodEnd: string | null;
969
+ intervalDays?: number;
970
+ /**
971
+ * The real next-fill date (`YYYY-MM-DD`), from the backend's renewal schedule:
972
+ * the live cycle's own date, or — while that cycle awaits a fill — the day the
973
+ * in-flight order is due at the pharmacy. Null only when the schedule is
974
+ * genuinely unknown (the order shipped but the next cycle isn't anchored yet,
975
+ * or its date has slipped), and on partners without renewals.
976
+ */
977
+ nextFillDate?: string | null;
978
+ /** When the check-in opens, from the same renewal row. */
979
+ checkInDueAt?: string | null;
980
+ /**
981
+ * The live renewal's status, or null when no cycle is running. Distinguishes
982
+ * "no renewals here" (fall back to the estimate) from "a cycle is running but
983
+ * its fill date isn't knowable yet" (say so rather than guess).
984
+ */
985
+ checkInStatus?: string | null;
986
+ }
987
+ type StageState = 'done' | 'active' | 'upcoming' | 'consult' | 'denied';
988
+ interface FulfillmentStage {
989
+ key: string;
990
+ /** Small-caps "lab label" shown on every bead. */
991
+ label: string;
992
+ /** Large display word — only set on the active / branch bead. */
993
+ heroWord?: string;
994
+ /** Plain-language one-liner under the hero word. */
995
+ subCaption?: string;
996
+ state: StageState;
997
+ /** Absolute timestamp string we actually have (createdAt / updatedAt). */
998
+ timestamp?: string | null;
999
+ }
1000
+ interface ShipmentInfo {
1001
+ carrier: string | null;
1002
+ trackingNumber: string | null;
1003
+ trackingUrl: string | null;
1004
+ /** Honest ETA copy — relative reassurance when no real estimate exists. */
1005
+ etaLabel: string;
1006
+ }
1007
+ interface TrackerView {
1008
+ stages: FulfillmentStage[];
1009
+ /** Index of the active/branch bead, for the "pour" fill height. */
1010
+ activeIndex: number;
1011
+ shipment: ShipmentInfo | null;
1012
+ /** True for denied/consult so the UI can pick supportive treatment. */
1013
+ branch: 'consult' | 'denied' | null;
1014
+ }
1015
+ /**
1016
+ * Build the full tracker view from a prescription request. Branches
1017
+ * (consultation needed / not approved) stay on the same thread, reframed as a
1018
+ * pause rather than an error.
1019
+ */
1020
+ declare function buildTrackerView(rx: TrackerRequest): TrackerView;
1021
+ interface RefillEvent {
1022
+ key: 'fill' | 'survey' | 'shipment';
1023
+ label: string;
1024
+ date: Date | null;
1025
+ /** Soft relative copy, e.g. "in 6 days". */
1026
+ relative: string;
1027
+ /** Nearest upcoming event gets the highlight dot. */
1028
+ nearest: boolean;
1029
+ }
1030
+ interface RefillView {
1031
+ events: RefillEvent[];
1032
+ /** "Day 18 of 30" cycle counter. Meaningless when `pendingFill` — hide it. */
1033
+ cycleDay: number;
1034
+ cycleLength: number;
1035
+ /** 0–1 progress through the current cycle. */
1036
+ progress: number;
1037
+ /**
1038
+ * True when the dates are the backend's real schedule; false when they are the
1039
+ * legacy estimate derived from the billing period. Lets the UI soften its copy
1040
+ * ("around the 14th") only where it is actually guessing.
1041
+ */
1042
+ precise: boolean;
1043
+ /**
1044
+ * A cycle is running but its next-fill date is not knowable yet (the current
1045
+ * order has not shipped). Events carry no dates — say "once your order ships",
1046
+ * never a fabricated one.
1047
+ */
1048
+ pendingFill: boolean;
1049
+ }
1050
+ /**
1051
+ * Derive the refill/renewal strip from a subscription, in three cases:
1052
+ *
1053
+ * 1. `nextFillDate` present — the backend's REAL schedule from the live renewal
1054
+ * row. Used as-is (`precise: true`).
1055
+ * 2. A cycle is running (`checkInStatus`) but has no fill date yet — it is
1056
+ * awaiting the pharmacy. Dates are genuinely unknown, so report none
1057
+ * (`pendingFill: true`) rather than inventing them.
1058
+ * 3. No renewal information at all — a partner without renewals. Falls back to
1059
+ * the legacy estimate off `currentPeriodEnd` (`precise: false`), unchanged.
1060
+ *
1061
+ * Case 3 used to be the only path, and it is why a comped member's plan read
1062
+ * "Day 30 of 30, check-in due 67d ago" forever: `currentPeriodEnd` only advances
1063
+ * on a successful charge, and a $0 subscription never has one.
1064
+ *
1065
+ * `now` is injected so this stays a pure function (testable; no Date.now()).
1066
+ */
1067
+ declare function buildRefillView(sub: TrackerSubscription | null | undefined, now?: number): RefillView | null;
1068
+ declare function formatStageDate(value?: string | null): string;
1069
+ declare function formatEventDate(date: Date | null): string;
1070
+
1071
+ /**
1072
+ * Pure derivations for the admin customer 360 view.
1073
+ *
1074
+ * The backend decides the lifecycle BUCKET (one rule table drives both the list
1075
+ * filter and the label, so they cannot disagree). This module turns bucket +
1076
+ * the raw records into what a support rep reads: the one-sentence reason, the
1077
+ * "needs attention" list, the journey stepper, and a merged timeline.
1078
+ *
1079
+ * No JSX, no fetching, `now` injected — same discipline as `tracker.ts`.
1080
+ *
1081
+ * Honesty rule: a step we have no data for renders as `unknown`, never as
1082
+ * "not done". Funnel telemetry and cart recovery are per-tenant features and
1083
+ * are OFF for some tenants; the overview says which, and this module respects
1084
+ * it.
1085
+ */
1086
+
1087
+ type Severity = 'danger' | 'warning' | 'info';
1088
+ type Tone = 'success' | 'warning' | 'danger' | 'info' | 'neutral';
1089
+ /** Fallback labels when the backend omits `lifecycle.label`. */
1090
+ declare const LIFECYCLE_LABEL: Record<AdminLifecycleBucket, string>;
1091
+ declare const LIFECYCLE_TONE: Record<AdminLifecycleBucket, Tone>;
1092
+ declare const LIFECYCLE_BUCKETS: AdminLifecycleBucket[];
1093
+ type AccountSource = 'savings' | 'register_and_subscribe' | 'register' | 'unknown';
1094
+ /** The subscription a rep cares about: a live one first, else the newest. */
1095
+ declare function primarySubscription(subs: AdminSubscriptionDetail[]): AdminSubscriptionDetail | null;
1096
+ /**
1097
+ * Where the account came from. Savings members carry `savingsMemberId`; a
1098
+ * fan-out signup creates the subscription in the same request as the user,
1099
+ * so a subscription born within two minutes of the account is that path.
1100
+ */
1101
+ declare function accountSource(o: Pick<AdminCustomerOverview, 'customer' | 'subscriptions'>): AccountSource;
1102
+ type ReasonInput = Pick<AdminCustomerOverview, 'customer' | 'lifecycle' | 'subscriptions' | 'payments' | 'requests' | 'funnel' | 'tenant'>;
1103
+ /**
1104
+ * One plain sentence answering "why is this customer in this bucket". This is
1105
+ * the line that answers the truemeds question: an account with no subscription
1106
+ * says whether the person never completed intake, completed it and never paid,
1107
+ * or tried to pay and was declined.
1108
+ */
1109
+ declare function lifecycleReason(o: ReasonInput): string;
1110
+ type AttentionActionKind = 'resolve_attempt' | 'edit_schedule' | 'cancel_unapproved' | 'open_thread' | 'open_subscription' | 'open_payment' | 'open_request';
1111
+ interface AttentionAction {
1112
+ kind: AttentionActionKind;
1113
+ label: string;
1114
+ subscriptionId?: string;
1115
+ attemptId?: string;
1116
+ threadId?: string;
1117
+ paymentId?: string;
1118
+ requestId?: string;
1119
+ }
1120
+ interface AttentionItem {
1121
+ id: string;
1122
+ severity: Severity;
1123
+ title: string;
1124
+ detail?: string;
1125
+ action?: AttentionAction;
1126
+ }
1127
+ /**
1128
+ * Things a rep should act on, worst first. Every rule names the record it
1129
+ * came from so the UI can jump to it. Rules are deliberately conservative:
1130
+ * they fire only on states the backend records, never on inference.
1131
+ */
1132
+ declare function deriveAttention(o: AdminCustomerOverview, now?: Date): AttentionItem[];
1133
+ type JourneyStepKey = 'account' | 'intake' | 'checkout' | 'prescriber' | 'pharmacy' | 'shipped' | 'renewing';
1134
+ type JourneyState = 'done' | 'active' | 'blocked' | 'upcoming' | 'unknown';
1135
+ interface JourneyStep {
1136
+ key: JourneyStepKey;
1137
+ label: string;
1138
+ state: JourneyState;
1139
+ /** ISO timestamp we actually have for this step, or null. */
1140
+ date: string | null;
1141
+ /** One short line under the label. */
1142
+ detail: string | null;
1143
+ }
1144
+ declare function deriveJourney(o: AdminCustomerOverview): JourneyStep[];
1145
+ /** Adapt an overview request to the member-portal tracker input. */
1146
+ declare function toTrackerRequest(r: AdminCustomerRequest): TrackerRequest;
1147
+ type TimelineKind = 'account' | 'intake' | 'subscription' | 'payment' | 'attempt' | 'request' | 'shipment' | 'support' | 'renewal' | 'cart';
1148
+ interface TimelineEvent {
1149
+ id: string;
1150
+ at: string;
1151
+ kind: TimelineKind;
1152
+ title: string;
1153
+ detail?: string | null;
1154
+ tone: Tone;
1155
+ }
1156
+ /**
1157
+ * Every dated record, newest first. Payments and billing attempts both carry
1158
+ * money events; attempts are only listed when they failed or are unresolved,
1159
+ * since a succeeded attempt is already visible as its payment.
1160
+ */
1161
+ declare function buildTimeline(o: AdminCustomerOverview, limit?: number): TimelineEvent[];
1162
+
1163
+ /**
1164
+ * Data source for the customer member portal. Headless (no JSX): the
1165
+ * `MemberPortal` page composes its layout on top of this.
1166
+ *
1167
+ * Business-model-flexible by design — capabilities are inferred from the data,
1168
+ * not hardcoded to one partner's model:
1169
+ * - RX requests are a LIST (a member may have several in flight at once).
1170
+ * - Subscriptions are OPTIONAL (some partners are one-time-purchase only).
1171
+ * The page reads `hasBilling()` / `rxRequests()` to decide which tabs/sections
1172
+ * to show, so a no-subscription, multi-RX partner and a single-RX +
1173
+ * subscription partner both render correctly from the same component.
1174
+ *
1175
+ * Sources: `/members/me` (member + subscriptions) and `/members/me/requests`
1176
+ * (the RX list — the endpoint the pre-redesign dashboard used successfully).
1177
+ */
1178
+
1179
+ /** A subscription row from `/members/me` (see `MembersMeResponse.subscriptions`). */
1180
+ interface MemberPortalSubscription {
1181
+ id: string;
1182
+ productId: string;
1183
+ /** Apex drug id (a code). */
1184
+ medication: string;
1185
+ /** Friendly product name resolved server-side; falls back to `medication`. */
1186
+ medicationName?: string;
1187
+ dosage: string;
1188
+ status: string;
1189
+ amountCents: number;
1190
+ intervalDays: number;
1191
+ /** Billing mirror — advances only on a successful charge. Not a fill date. */
1192
+ currentPeriodEnd: string;
1193
+ /** Real next-fill date (`YYYY-MM-DD`) from the live renewal; null when none. */
1194
+ nextFillDate?: string | null;
1195
+ /** When the check-in opens, from the same renewal row. */
1196
+ checkInDueAt?: string | null;
1197
+ /** Live renewal status, or null when no cycle is running. */
1198
+ checkInStatus?: string | null;
1199
+ createdAt: string;
1200
+ }
1201
+ /** A prescription request, flattened for the portal. */
1202
+ interface MemberPortalRx {
1203
+ requestId: string;
1204
+ status: TrackerRequestStatus;
1205
+ drugName?: string;
1206
+ dosage?: string;
1207
+ createdAt: string | null;
1208
+ updatedAt: string | null;
1209
+ delivery: DeliveryInfo | null;
1210
+ /** The day an approved Rx is due at the pharmacy (`YYYY-MM-DD`), else null. */
1211
+ pharmacySendDate: string | null;
1212
+ /** Open check-in renewal id, if any (drives the "Complete check-in" link). */
1213
+ renewalId: string | null;
1214
+ }
1215
+ interface MemberPortalData {
1216
+ /** Raw member record (`/members/me` → `member`); shape is backend-defined. */
1217
+ member: () => Record<string, unknown> | null;
1218
+ subscriptions: () => MemberPortalSubscription[];
1219
+ /** The subscription the portal treats as primary (live one first, else first). */
1220
+ primarySubscription: () => MemberPortalSubscription | null;
1221
+ /** True when this member/partner has any subscription (gates the Plan tab). */
1222
+ hasBilling: () => boolean;
1223
+ /** All RX requests, newest first. */
1224
+ rxRequests: () => MemberPortalRx[];
1225
+ /** The RX to feature (newest in-flight, else newest overall). */
1226
+ primaryRx: () => MemberPortalRx | null;
1227
+ /** The remaining RX requests (everything but the primary), newest first. */
1228
+ otherRx: () => MemberPortalRx[];
1229
+ pendingSurveys: () => PendingRenewalSurvey[];
1230
+ /** First name from the member record (camel or snake), else "Member". */
1231
+ firstName: () => string;
1232
+ loading: () => boolean;
1233
+ /** Present when the RX list or member load failed — surfaced, not swallowed. */
1234
+ error: () => string | null;
1235
+ refetch: () => void;
1236
+ /** Adapt an RX into the tracker flow's input contract. */
1237
+ toTrackerRequest: (rx: MemberPortalRx) => TrackerRequest;
1238
+ /** The subscription driving the refill strip (only when hasBilling). */
1239
+ trackerSubscription: () => TrackerSubscription | null;
1240
+ }
1241
+ declare function useMemberPortalData(): MemberPortalData;
1242
+
1243
+ /**
1244
+ * Headless flow for updating a subscription's payment method (card on file).
1245
+ * Composes the provider-aware tokenizer (useCardTokenizer) with
1246
+ * subscriptionsApi.updatePaymentMethod: the raw PAN is tokenized client-side and
1247
+ * only the opaque token is sent to the backend.
1248
+ *
1249
+ * The card-entry UI (UpdatePaymentMethod page) renders these signals; the
1250
+ * subscription id is provided reactively so the page can resolve it (e.g. the
1251
+ * member's primary subscription) before the card is submitted.
1252
+ */
1253
+
1254
+ interface UpdatePaymentMethodFlow {
1255
+ cardNumber: Accessor<string>;
1256
+ setCardNumber: (v: string) => void;
1257
+ expiry: Accessor<string>;
1258
+ setExpiry: (v: string) => void;
1259
+ cvv: Accessor<string>;
1260
+ /**
1261
+ * True when the card is typed into the gateway's own hosted fields (NMI's
1262
+ * Collect.js) instead of cardNumber/expiry/cvv: render three containers and
1263
+ * pass each to registerCardField instead of card inputs.
1264
+ */
1265
+ hostedCardFields: Accessor<boolean>;
1266
+ /** Ref callback for a hosted card field container: `ref={(el) => flow.registerCardField('number', el)}`. */
1267
+ registerCardField: (field: HostedCardField, el: HTMLElement) => void;
1268
+ setCvv: (v: string) => void;
1269
+ /** True once the tenant's tokenizer is loaded. */
1270
+ ready: Accessor<boolean>;
1271
+ submitting: Accessor<boolean>;
1272
+ /** User-facing error from tokenization or the update call. */
1273
+ error: Accessor<string | null>;
1274
+ /** Whether submit is currently allowed (ready, all fields present, idle). */
1275
+ canSubmit: Accessor<boolean>;
1276
+ /** Tokenize + PUT the new card. Resolves true on success, false on failure. */
1277
+ submit: () => Promise<boolean>;
1278
+ /**
1279
+ * Billing address sent as the card's billTo.
1280
+ *
1281
+ * This screen used to send the card alone, leaving the backend to bill
1282
+ * against the member's SHIPPING profile with nothing shown and nothing
1283
+ * editable. The gateway validates the card live on update, so a card that
1284
+ * bills to a different address failed AVS — surfacing as a bare "declined"
1285
+ * that named nothing and offered no control to fix. The member could not
1286
+ * update their card on file at all.
1287
+ *
1288
+ * Prefilled from `GET /payment-method` with whatever is already on file at
1289
+ * the gateway (falling back to the profile address), so the common case is
1290
+ * still confirm-and-save.
1291
+ */
1292
+ billing: AddressPair;
1293
+ /** True once the address on file has loaded (fields prefill on arrival). */
1294
+ billingLoaded: Accessor<boolean>;
1295
+ }
1296
+ declare function useUpdatePaymentMethodFlow(subscriptionId: () => string | null): UpdatePaymentMethodFlow;
1297
+
1298
+ /**
1299
+ * Which backend a conversation belongs to.
1300
+ *
1301
+ * `clinical` is Apex's patient <-> prescriber messaging, proxied by the backend.
1302
+ * `support` is the backend's own customer <-> support threads. The member sees
1303
+ * one merged inbox; everything below routes each operation to the right API
1304
+ * based on this discriminator, so the two never cross.
1305
+ */
1306
+ type ConversationSource = 'clinical' | 'support';
1307
+ /**
1308
+ * Which side of the merged inbox a message is destined for. Distinct from
1309
+ * `ConversationSource` (which describes an EXISTING conversation) — this is
1310
+ * the caller's intent BEFORE any conversation exists yet, e.g. "open compose
1311
+ * pre-set to support" from a CTA that has no conversation id to point at.
1312
+ */
1313
+ type MessagesChannel = 'care' | 'support';
1314
+ /**
1315
+ * Pre-selection for the Messages tab: lets any entry point (a CTA, a deep
1316
+ * link) say which destination to land on instead of the merged conversation
1317
+ * list. All fields are optional so "no intent" (today's default: show the
1318
+ * list) is just `undefined`/`{}`.
1319
+ *
1320
+ * `threadId` takes priority over `channel`/`category` when a caller has an
1321
+ * exact conversation to open (its source implies the channel, so `channel`
1322
+ * is redundant and ignored here). Otherwise `channel: 'care'` re-runs the
1323
+ * existing "pick care team" logic (latest clinical conversation, or the care
1324
+ * compose form) and `channel: 'support'` opens the support compose form,
1325
+ * pre-set with `category`/`prefill` when given. `category` and `prefill` are
1326
+ * meaningless for `channel: 'care'` and are ignored there.
1327
+ */
1328
+ interface MessagesIntent {
1329
+ channel?: MessagesChannel;
1330
+ /** Support only — ignored when `channel` is `'care'`. */
1331
+ category?: SupportThreadCategory;
1332
+ /** Optional body text to pre-fill the support compose form with. */
1333
+ prefill?: string;
1334
+ /** Open this exact conversation/thread; wins over `channel`/`category`. */
1335
+ threadId?: string;
1336
+ }
1337
+ /** Normalized conversation. The backend passes Apex's record through verbatim
1338
+ * (the-backend routes/messages.ts → apexMessaging.Conversation), which names
1339
+ * three of these fields differently; `normalizeConversation` reconciles them so
1340
+ * consumers only ever see this shape. Support threads are mapped onto the same
1341
+ * shape by `normalizeSupportThread`. */
1342
+ interface Conversation {
1343
+ id: string;
1344
+ source: ConversationSource;
1345
+ participantName?: string;
1346
+ participantRole?: string;
1347
+ lastMessage?: string;
1348
+ lastMessageAt?: string;
1349
+ unreadCount?: number;
1350
+ /** Support threads only — open | pending | closed. */
1351
+ status?: string;
1352
+ /** Support threads only — the customer-picked category, when set. */
1353
+ category?: SupportThreadCategory | null;
1354
+ [key: string]: unknown;
1355
+ }
1356
+ /**
1357
+ * One attachment on a message, normalized across sources.
1358
+ *
1359
+ * `url` present means the source handed us a directly-usable link (Apex's
1360
+ * clinical messages do this). Absent means it must be exchanged for a
1361
+ * short-lived signed URL by id — how support attachments work, since their
1362
+ * bucket is private.
1363
+ */
1364
+ interface ThreadAttachment {
1365
+ id: string;
1366
+ filename: string;
1367
+ mimeType: string;
1368
+ sizeBytes: number;
1369
+ url?: string;
1370
+ }
1371
+ interface ThreadMessage {
1372
+ id: string;
1373
+ senderId: string;
1374
+ senderRole: string;
1375
+ senderName?: string;
1376
+ type: 'text' | 'system' | 'html';
1377
+ text: string;
1378
+ content?: string;
1379
+ createdAt: string;
1380
+ /** Empty for sources that don't carry attachments. */
1381
+ attachments?: ThreadAttachment[];
1382
+ [key: string]: unknown;
1383
+ }
1384
+ declare function formatConversationTime(iso: string | undefined): string;
1385
+ declare function formatMessageTime(iso: string): string;
1386
+ interface UseMessagesThreadOptions {
1387
+ /** Override poll intervals. Defaults: conversations 30s, messages 10s. */
1388
+ pollIntervalMs?: {
1389
+ conversations?: number;
1390
+ messages?: number;
1391
+ };
1392
+ /** When set to false, the hook does not auto-poll. Useful for tests or when the consumer wants to drive refresh manually. Default true. */
1393
+ autoPoll?: boolean;
1394
+ }
1395
+ /**
1396
+ * Outcome of opening a support thread. Two flags rather than a boolean because
1397
+ * "the thread exists but the file didn't attach" is a real, recoverable state
1398
+ * the UI must not report as outright failure — retrying the whole thing would
1399
+ * open a second thread.
1400
+ */
1401
+ interface StartThreadResult {
1402
+ created: boolean;
1403
+ attachmentFailed: boolean;
1404
+ }
1405
+ /**
1406
+ * Outcome of starting a care-team conversation. `reason` discriminates the two
1407
+ * ways `created` can be false: `'no_care_team'` is the documented 409 — the
1408
+ * member has never had a prescriber assigned, so there's nowhere to route the
1409
+ * message — and the caller should offer the support escape hatch. `'error'`
1410
+ * covers everything else (network, 400, 502) and should keep the draft for a
1411
+ * retry rather than switch away.
1412
+ */
1413
+ interface StartCareTeamResult {
1414
+ created: boolean;
1415
+ attachmentFailed: boolean;
1416
+ reason?: 'no_care_team' | 'error';
1417
+ }
1418
+ interface MessagesThread {
1419
+ conversations: Accessor<Conversation[]>;
1420
+ loadingConversations: Accessor<boolean>;
1421
+ selectedId: Accessor<string | null>;
1422
+ messages: Accessor<ThreadMessage[]>;
1423
+ loadingMessages: Accessor<boolean>;
1424
+ draft: Accessor<string>;
1425
+ setDraft: (v: string) => void;
1426
+ sending: Accessor<boolean>;
1427
+ /** True while a new support thread is being opened. */
1428
+ startingThread: Accessor<boolean>;
1429
+ /** True while a new care-team conversation is being started. */
1430
+ startingCareTeamThread: Accessor<boolean>;
1431
+ /** Source of the open conversation, or null when none is selected. */
1432
+ selectedSource: Accessor<ConversationSource | null>;
1433
+ /** How this tenant answers support. 'email' bypasses the conversation view:
1434
+ * show only the Support form and submit it with `sendSupportEmail`. 'portal'
1435
+ * until the list has loaded, and on a backend without the setting. */
1436
+ supportChannel: Accessor<SupportChannel>;
1437
+ /** Select a conversation. Loads messages, marks as read, starts the message-poll loop. */
1438
+ selectConversation: (id: string) => Promise<void>;
1439
+ /** Clear the active selection (useful for "back to list" on mobile). */
1440
+ clearSelection: () => void;
1441
+ /** Send the current draft as a message. Optimistically appends; rolls back if the request fails. */
1442
+ send: () => Promise<void>;
1443
+ /** Manually refetch the conversation list. */
1444
+ refreshConversations: () => Promise<void>;
1445
+ /** Open a new support thread with a subject and first message, then select it.
1446
+ * Support-only — clinical conversations are started by the prescriber, never
1447
+ * the member. An optional file is uploaded as a follow-up request; see
1448
+ * StartThreadResult for the partial-success case. An optional category
1449
+ * routes the thread on the backend side. */
1450
+ startSupportThread: (subject: string, body: string, file?: File, category?: SupportThreadCategory | null) => Promise<StartThreadResult>;
1451
+ /** Send the Support form on an email-channel tenant (see `supportChannel`).
1452
+ * Nothing is stored and no conversation opens — the tenant replies by email.
1453
+ * Resolves false when it didn't send, so the caller keeps the draft.
1454
+ * `startingThread` is true while it's in flight. */
1455
+ sendSupportEmail: (subject: string, body: string, file?: File, category?: SupportThreadCategory | null) => Promise<boolean>;
1456
+ /** Start (or reuse) the member's care-team conversation with an opening
1457
+ * message, then select it. No subject — Apex conversations don't have one.
1458
+ * An optional file is uploaded as a follow-up request; see
1459
+ * StartCareTeamResult for the partial-success case. A 409 (the member has
1460
+ * never had a prescriber assigned) reports back as `reason: 'no_care_team'`
1461
+ * rather than throwing, so the caller can offer the support escape hatch. */
1462
+ startCareTeamThread: (text: string, file?: File) => Promise<StartCareTeamResult>;
1463
+ /** Send a file to the open support thread, with optional accompanying text. */
1464
+ sendAttachment: (file: File, text?: string) => Promise<boolean>;
1465
+ /** Exchange an attachment id for a short-lived viewable URL, or null.
1466
+ * Pass force to bypass the cache after an expired-URL load failure. */
1467
+ resolveAttachmentUrl: (attachmentId: string, force?: boolean) => Promise<string | null>;
1468
+ }
1469
+ /**
1470
+ * Conversation list + active-thread state with polling. Tier 2 hook —
1471
+ * sites compose their own split-pane / mobile UI on top.
1472
+ */
1473
+ declare function useMessagesThread(options?: UseMessagesThreadOptions): MessagesThread;
1474
+
1475
+ /** Lowest price across the product's available doses (overlay-or-base each),
1476
+ * falling back to the product-level price. Returns null for free / unpriced products. */
1477
+ declare function lowestPrice(product: CatalogProduct): number | null;
1478
+ /**
1479
+ * Sale price for an arbitrary base price on a product, re-deriving the same
1480
+ * percent/fixed discount the backend applied at the product level.
1481
+ *
1482
+ * Returns null when no active sale, no discount, or insufficient data.
1483
+ */
1484
+ declare function salePriceForBase(product: CatalogProduct, basePrice: number | null): number | null;
1485
+ /**
1486
+ * Lowest sale price for a tiered product. Used so the strikethrough lands on
1487
+ * the displayed (lowest-tier) value — `salePriceForBase` applied to the
1488
+ * product's cheapest dose.
1489
+ */
1490
+ declare function lowestSalePrice(product: CatalogProduct, basePrice: number | null): number | null;
1491
+ interface CatalogFlow {
1492
+ products: Resource<CatalogProduct[]>;
1493
+ /** Products in the "weight-loss" category. */
1494
+ weightLoss: Accessor<CatalogProduct[]>;
1495
+ /** Products NOT in "weight-loss" (peptides, recovery, etc). */
1496
+ peptides: Accessor<CatalogProduct[]>;
1497
+ /** Filter products by an arbitrary category slug. */
1498
+ filterByCategory: (slug: string) => CatalogProduct[];
1499
+ }
1500
+ /** Fetches the product catalog and exposes a couple of common derivations. */
1501
+ declare function useCatalog(): CatalogFlow;
1502
+ interface ProductDetailFlow {
1503
+ product: Resource<CatalogProduct | null>;
1504
+ dosageOptions: Accessor<Array<{
1505
+ dosage: string;
1506
+ price: number;
1507
+ savingsPrice: number | null;
1508
+ }>>;
1509
+ selectedDosage: Accessor<string>;
1510
+ setSelectedDosage: (v: string) => void;
1511
+ /** Effective base price for the currently-selected dosage. */
1512
+ selectedPrice: Accessor<number | null>;
1513
+ /** Sale price for the selected dosage, if a sale is active. */
1514
+ selectedSalePrice: Accessor<number | null>;
1515
+ /** 'per_dose' (default) or 'flat_fee'. When 'flat_fee', `dosageOptions` is
1516
+ * collapsed to a single entry and consumer UI should hide the dose picker. */
1517
+ pricingMode: Accessor<'per_dose' | 'flat_fee'>;
1518
+ /** True if the product+dosage combination is already in cart. */
1519
+ inCart: Accessor<boolean>;
1520
+ addToCart: () => void;
1521
+ }
1522
+ /**
1523
+ * Single-product page state. Loads the catalog and finds the product by id.
1524
+ * Tracks dosage selection, derives current/sale price, exposes addToCart.
1525
+ */
1526
+ declare function useProductDetail(productId: Accessor<string>): ProductDetailFlow;
1527
+ interface MedicationSelectFlow {
1528
+ products: Resource<CatalogProduct[]>;
1529
+ weightLoss: Accessor<CatalogProduct[]>;
1530
+ peptides: Accessor<CatalogProduct[]>;
1531
+ /** Pick a specific product as the patient's selected medication and proceed. The site fires the navigation in the optional `onSelected` callback. */
1532
+ selectMedication: (product: CatalogProduct) => void;
1533
+ /** Pick "general consultation" — a null drugId, indicating no pre-selected drug. */
1534
+ selectGeneralConsultation: () => void;
1535
+ }
1536
+ interface UseMedicationSelectOptions {
1537
+ /** Called after a selection is made. Sites typically navigate to their survey route. */
1538
+ onSelected?: () => void;
1539
+ /** Override the label used for the general-consultation selection. Default "General Consultation". */
1540
+ generalConsultationLabel?: string;
1541
+ }
1542
+ /**
1543
+ * Catalog browse + select-for-survey. The selection is written to
1544
+ * medicationStore (legacy single-item flow); the site navigates afterward
1545
+ * via the onSelected callback.
1546
+ */
1547
+ declare function useMedicationSelect(options?: UseMedicationSelectOptions): MedicationSelectFlow;
1548
+
1549
+ /** Why a line was dropped from the cart. */
1550
+ type CartDropReason =
1551
+ /** No product with this id in the catalog — deleted, or no longer active. */
1552
+ 'unavailable'
1553
+ /** In the catalog, but no price resolves for this dose (an unpriced stub).
1554
+ * Left in, it would submit as a $0 order: the backend snapshots
1555
+ * `Number(price ?? 0)`. A deliberate 0.00 is priced, and is kept. */
1556
+ | 'unpriced'
1557
+ /** In the catalog, but not linked to an Apex drug, so it cannot be
1558
+ * prescribed. Only ever reported when `requireApexDrug` is set. */
1559
+ | 'not_prescribable';
1560
+ interface DroppedCartLine {
1561
+ item: CartItem;
1562
+ reason: CartDropReason;
1563
+ }
1564
+ interface CartReconciliation {
1565
+ /** The cart as it should now be — survivors, with refreshed snapshots. */
1566
+ items: CartItem[];
1567
+ dropped: DroppedCartLine[];
1568
+ /** Survivors whose stored snapshot no longer matched the catalog. */
1569
+ refreshed: CartItem[];
1570
+ /** False when the catalog could not be read; the cart was left untouched. */
1571
+ checked: boolean;
1572
+ }
1573
+ interface ReconcileOptions {
1574
+ /**
1575
+ * Drop lines with no linked Apex drug. Set on the prescription path (the v2
1576
+ * survey), where every cart line becomes a prescription request and an
1577
+ * unlinked product is a guaranteed failure at submit time. Off by default:
1578
+ * a cart may legitimately hold non-Apex items on sites that also sell them.
1579
+ */
1580
+ requireApexDrug?: boolean;
1581
+ }
1582
+ /**
1583
+ * Pure reconciliation of cart lines against a catalog snapshot.
1584
+ *
1585
+ * Deliberately keeps a line whose *dose* is no longer offered: the backend
1586
+ * reconciles a requested dose against the drug's canonical Apex dosages at
1587
+ * request time, so it is not a dead line — it just re-prices here (the dose
1588
+ * overlay is gone, so the product's base price applies).
1589
+ */
1590
+ declare function reconcileCartLines(items: CartItem[], products: CatalogProduct[], opts?: ReconcileOptions): CartReconciliation;
1591
+ /**
1592
+ * Reconcile the live cart against the catalog and write the result back.
1593
+ *
1594
+ * Fails OPEN in every direction: an empty cart short-circuits without a
1595
+ * request, and a catalog fetch that errors leaves the cart exactly as it was
1596
+ * (`checked: false`). Shopping must never break because this could not run —
1597
+ * the backend stays the authority on what is actually submittable.
1598
+ */
1599
+ declare function reconcileCartAgainstCatalog(opts?: ReconcileOptions): Promise<CartReconciliation>;
1600
+ interface CartReconcileState {
1601
+ /** Lines removed because the catalog no longer offers them. */
1602
+ dropped: Accessor<DroppedCartLine[]>;
1603
+ /** Lines kept, with a snapshot refreshed from the catalog. */
1604
+ refreshed: Accessor<CartItem[]>;
1605
+ /** True while the catalog is being read. */
1606
+ pending: Accessor<boolean>;
1607
+ }
1608
+ /**
1609
+ * Reconcile the persisted cart against the catalog once, on mount.
1610
+ *
1611
+ * Mount it in the app shell (the layout that renders the cart drawer) so it
1612
+ * runs once per session, before the shopper can act on a stale line. Surface
1613
+ * `dropped` — a shopper whose item vanishes without a word will assume the
1614
+ * site lost it.
1615
+ */
1616
+ declare function useCartReconcile(opts?: ReconcileOptions): CartReconcileState;
1617
+
1618
+ interface AffiliateStatsFlow {
1619
+ stats: Resource<AffiliateDashboardStats | null>;
1620
+ refetch: () => void;
1621
+ }
1622
+ interface AffiliateConversionsFlow {
1623
+ conversions: Resource<AffiliateConversion[]>;
1624
+ refetch: () => void;
1625
+ }
1626
+ interface AffiliateLinksFlow {
1627
+ links: Resource<AffiliateDashboardLinks | null>;
1628
+ refetch: () => void;
1629
+ }
1630
+ interface AffiliateDownlineFlow {
1631
+ downline: Resource<AffiliateDownlineMember[]>;
1632
+ refetch: () => void;
1633
+ }
1634
+ /**
1635
+ * Wraps GET /affiliates/dashboard/stats as a resource. Gated on the
1636
+ * affiliate auth store so the fetcher only fires when the affiliate is
1637
+ * authenticated; otherwise the resource resolves to `null`.
1638
+ */
1639
+ declare function useAffiliateStats(): AffiliateStatsFlow;
1640
+ declare function useAffiliateConversions(opts?: {
1641
+ limit?: number;
1642
+ }): AffiliateConversionsFlow;
1643
+ declare function useAffiliateDownline(): AffiliateDownlineFlow;
1644
+ declare function useAffiliateLinks(): AffiliateLinksFlow;
1645
+
1646
+ /**
1647
+ * Deterministic procedural color for product categories.
1648
+ *
1649
+ * Sites want a stable color per category id without curating maps. The hash
1650
+ * is stable across reloads, so the same id always picks the same slot. Sites
1651
+ * override the palette to brand-align — default palette works out of the box.
1652
+ */
1653
+ /** Default palette. Reads on light or dark; sites that want brand alignment
1654
+ * pass their own array (e.g. CSS var refs). */
1655
+ declare const DEFAULT_COLOR_PALETTE: readonly string[];
1656
+ interface CategoryColorOpts {
1657
+ palette?: readonly string[];
1658
+ }
1659
+ declare function categoryColor(id: string, opts?: CategoryColorOpts): string;
1660
+ /**
1661
+ * True when `value` can go straight into a CSS color property: a hex, a color
1662
+ * function (`rgb()`, `hsl()`, `oklch()`, …) or a bare `var(--x)`. A category's
1663
+ * `color` is a free admin-entered string, so anything else — a Tailwind class,
1664
+ * or text carrying `;` / `url(` — is not a style value.
1665
+ */
1666
+ declare function isCssColorValue(value: string): boolean;
1667
+ /**
1668
+ * The color to use for a category: the admin-set `color` from the backend
1669
+ * when it is a CSS color value (see `isCssColorValue`), otherwise the
1670
+ * deterministic hash. Always returns something safe to put in a `style`
1671
+ * color property. Pass the same `opts` you would pass to `categoryColor` so
1672
+ * the fallback stays brand-aligned.
1673
+ *
1674
+ * A site that stores class names in `color` (e.g. `bg-emerald-500`) should read
1675
+ * `category.color` directly and apply it as a class; this falls back to the
1676
+ * hash for those.
1677
+ */
1678
+ declare function resolveCategoryColor(category: {
1679
+ id: string;
1680
+ color?: string | null;
1681
+ }, opts?: CategoryColorOpts): string;
1682
+
1683
+ interface SurveyResult {
1684
+ surveyResponseId: string;
1685
+ /**
1686
+ * v2 survey response id. When set, the Rx is linked to the Apex survey
1687
+ * snapshot and Apex generates the prescriber case notes from it (no local
1688
+ * caseNotes synthesis). Leave unset for the legacy v1 flow.
1689
+ */
1690
+ v2SurveyResponseId?: string;
1691
+ caseNotes?: string;
1692
+ drugId: string;
1693
+ drugName: string;
1694
+ dosage: string;
1695
+ }
1696
+ interface MedicationPricing {
1697
+ productId: string;
1698
+ productName: string;
1699
+ priceCents: number;
1700
+ savingsPriceCents?: number | null;
1701
+ }
1702
+ type SubscriptionIntakeOutcome = {
1703
+ kind: 'in_progress';
1704
+ } | {
1705
+ kind: 'tokenizing';
1706
+ } | {
1707
+ kind: 'submitting';
1708
+ }
1709
+ /**
1710
+ * The member already holds a live subscription, so this intake must not create
1711
+ * a second one. Emitted ONLY under `singleSubscription` — without that option
1712
+ * the flow behaves exactly as before, so existing consumers that switch on
1713
+ * 'completed' alone are unaffected.
1714
+ *
1715
+ * Deliberately NOT 'completed': that kind means *this* purchase succeeded, and
1716
+ * hosts navigate onward celebrating it. This one means the member arrived
1717
+ * already subscribed and needs telling, not congratulating.
1718
+ */
1719
+ | {
1720
+ kind: 'already_subscribed';
1721
+ productId?: string;
1722
+ } | {
1723
+ kind: 'completed';
1724
+ };
1725
+ interface UseSubscriptionIntakeFlowOptions {
1726
+ surveyResult: SurveyResult;
1727
+ pricing: MedicationPricing;
1728
+ intervalDays?: number;
1729
+ /**
1730
+ * Whether the member is enrolled in the savings program — read reactively, so
1731
+ * a verification that completes mid-intake re-quotes. When true and the
1732
+ * product defines `savingsPriceCents`, that rate is quoted instead of list.
1733
+ *
1734
+ * Must track the same member the SERVER will resolve at charge time (the
1735
+ * persisted savings link), or the quote and the charge disagree.
1736
+ */
1737
+ isSavingsMember?: () => boolean;
1738
+ /**
1739
+ * The verified savings member id to send on the unauthenticated signup path,
1740
+ * so an account created AT checkout is linked and charged the savings rate
1741
+ * (the backend accepts and links `savingsMemberId` on register-and-subscribe,
1742
+ * but it was never sent). Read at submit time; null/empty sends nothing. The
1743
+ * authenticated path ignores it — the server prices off the persisted link.
1744
+ */
1745
+ savingsMemberId?: () => string | null;
1746
+ /**
1747
+ * Single-subscription tenants: the site sells ONE subscription program, so a
1748
+ * member may hold at most one live subscription — of ANY product.
1749
+ *
1750
+ * Widens the mount reconcile below from "already subscribed to THIS product"
1751
+ * to "already subscribed to anything", and turns the server's
1752
+ * `SUBSCRIPTION_EXISTS` rejection into an `already_subscribed` outcome instead
1753
+ * of a raw error banner. Mirrors `features.singleSubscription` on the tenant;
1754
+ * setting it here without the tenant flag still guards the common paths, but
1755
+ * the server is what actually enforces it.
1756
+ */
1757
+ singleSubscription?: boolean;
1758
+ }
1759
+ interface PromoPricing {
1760
+ baseCents: number;
1761
+ /** What is actually taken off: the promo's discount or the offer's, never both. */
1762
+ discountCents: number;
1763
+ finalCents: number;
1764
+ /** Set when the typed promo code is the discount applied. */
1765
+ promoCode?: string;
1766
+ /**
1767
+ * Set ONLY when the member's own offer is the discount applied — it beat the
1768
+ * typed promo code, or there was none. Absent whenever `promoCode` is set.
1769
+ */
1770
+ offer?: {
1771
+ label: string;
1772
+ /** "$10" / "15%". */
1773
+ amountText: string;
1774
+ /** The last day to claim it, ready to print ("November 11, 2026"). */
1775
+ deadlineText: string;
1776
+ recurringIndefinite: boolean;
1777
+ /** Rebills after the first charge that carry the discount. */
1778
+ recurringCharges: number;
1779
+ discountCents: number;
1780
+ };
1781
+ }
1782
+ /** Shown when a typed code is valid but the member's offer is worth more. */
1783
+ declare const OFFER_BEATS_PROMO_NOTICE = "Your offer is the better discount, so it is the one applied. A promo code does not combine with an offer.";
1784
+ interface SubscriptionIntakeFlow {
1785
+ step: Accessor<number>;
1786
+ stepCount: 3;
1787
+ next: () => Promise<void>;
1788
+ back: () => void;
1789
+ outcome: Accessor<SubscriptionIntakeOutcome>;
1790
+ error: Accessor<string | null>;
1791
+ submitting: Accessor<boolean>;
1792
+ tokenizing: Accessor<boolean>;
1793
+ /** True once the card tokenizer is ready (config loaded; for AuthNet, Accept.js loaded too). Gate submission on this. */
1794
+ tokenizerReady: Accessor<boolean>;
1795
+ /** @deprecated alias of tokenizerReady (pre-rename name). */
1796
+ acceptJsReady: Accessor<boolean>;
1797
+ /** Non-null when payment setup failed to initialize — render as a banner. */
1798
+ /** Tokenizer init failure, or null. */
1799
+ tokenizerError: Accessor<string | null>;
1800
+ /** @deprecated alias of tokenizerError (pre-rename name). */
1801
+ acceptJsError: Accessor<string | null>;
1802
+ firstName: Accessor<string>;
1803
+ setFirstName: (v: string) => void;
1804
+ lastName: Accessor<string>;
1805
+ setLastName: (v: string) => void;
1806
+ email: Accessor<string>;
1807
+ setEmail: (v: string) => void;
1808
+ password: Accessor<string>;
1809
+ setPassword: (v: string) => void;
1810
+ dateOfBirth: Accessor<string>;
1811
+ setDateOfBirth: (v: string) => void;
1812
+ phone: Accessor<string>;
1813
+ setPhone: (v: string) => void;
1814
+ /**
1815
+ * Optional opt-in to text messages. `smsConsent.offer()` is null unless the
1816
+ * tenant texts customers; render the checkbox only when it isn't. Never
1817
+ * required — leaving it unticked sends nothing and the purchase proceeds. A
1818
+ * guest's grant rides the register-and-subscribe call; a signed-in member's
1819
+ * rides the profile PATCH the intake already makes.
1820
+ */
1821
+ smsConsent: SmsConsent;
1822
+ address: AddressPair;
1823
+ /** Per-item deliverability for `medication.productId` in the address's
1824
+ * shipping state — a catalog item routed to a pharmacy that doesn't serve
1825
+ * that state. Per ITEM, on top of the tenant-level `unavailableStates`
1826
+ * gating the address step already applies. `submit()` refuses to charge
1827
+ * while `availability.blocking()` is true. */
1828
+ availability: CatalogAvailabilityState;
1829
+ cardNumber: Accessor<string>;
1830
+ setCardNumber: (v: string) => void;
1831
+ expiry: Accessor<string>;
1832
+ setExpiry: (v: string) => void;
1833
+ cvv: Accessor<string>;
1834
+ setCvv: (v: string) => void;
1835
+ /**
1836
+ * True when the card is typed into the gateway's own hosted fields (NMI's
1837
+ * Collect.js) instead of cardNumber/expiry/cvv: render three containers and
1838
+ * pass each to registerCardField instead of card inputs.
1839
+ */
1840
+ hostedCardFields: Accessor<boolean>;
1841
+ /** Ref callback for a hosted card field container: `ref={(el) => flow.registerCardField('number', el)}`. */
1842
+ registerCardField: (field: HostedCardField, el: HTMLElement) => void;
1843
+ promoCode: Accessor<string>;
1844
+ setPromoCode: (v: string) => void;
1845
+ promoValidating: Accessor<boolean>;
1846
+ promoError: Accessor<string | null>;
1847
+ promoApplied: Accessor<PromoValidationResponse | null>;
1848
+ applyPromo: () => Promise<void>;
1849
+ clearPromo: () => void;
1850
+ /**
1851
+ * Plain words for the member when their valid promo code is NOT the discount
1852
+ * applied because their offer is worth more; null otherwise. Render it by the
1853
+ * promo field so a code that "did nothing" is explained.
1854
+ */
1855
+ promoNotice: Accessor<string | null>;
1856
+ pricing: Accessor<PromoPricing>;
1857
+ surveyResult: SurveyResult;
1858
+ medication: MedicationPricing;
1859
+ submit: () => Promise<void>;
1860
+ }
1861
+ declare function useSubscriptionIntakeFlow(options: UseSubscriptionIntakeFlowOptions): SubscriptionIntakeFlow;
1862
+
1863
+ interface OfferDiscount {
1864
+ offer: MemberOffer;
1865
+ /** What the offer takes off `baseCents`. Always > 0. */
1866
+ discountCents: number;
1867
+ }
1868
+ /**
1869
+ * The best discount the buyer's offers give this cart, or null when none
1870
+ * applies.
1871
+ *
1872
+ * `baseCents` is the cart subtotal the discount is taken from — AFTER savings
1873
+ * pricing has been substituted, because that is the subtotal the server
1874
+ * discounts. `productIds` is every product in the cart.
1875
+ *
1876
+ * The server's rule, mirrored exactly:
1877
+ * - an offer limited to products applies when the cart holds at least one of
1878
+ * them, and then discounts the whole subtotal (the product list is a gate,
1879
+ * not a scope);
1880
+ * - fixed takes `min(base, cents)`, percent `round(base × pct / 100)`;
1881
+ * - offers never combine: the largest wins, the first listed on a tie.
1882
+ *
1883
+ * An offer and a typed promo code do not combine either — see
1884
+ * `offerBeatsPromo` for which of the two applies.
1885
+ */
1886
+ declare function bestOfferDiscount(offers: readonly MemberOffer[] | null | undefined, cart: {
1887
+ productIds: readonly string[];
1888
+ baseCents: number;
1889
+ }): OfferDiscount | null;
1890
+ /**
1891
+ * Whether the offer is the one applied when the buyer has also typed a valid
1892
+ * promo code. The better of the two wins; on a tie the code they typed does.
1893
+ */
1894
+ declare function offerBeatsPromo(offerDiscountCents: number, promoDiscountCents: number): boolean;
1895
+ /**
1896
+ * How long an offer's discount runs, to finish the sentence "$10 off …".
1897
+ * "every month" for an open-ended one; otherwise the charges it covers.
1898
+ */
1899
+ declare function offerDurationText(o: {
1900
+ recurringIndefinite: boolean;
1901
+ recurringCharges?: number | null;
1902
+ }): string;
1903
+ /** "$10 off every month" — the offer as one order-summary phrase. */
1904
+ declare function offerSummaryText(o: {
1905
+ amountText: string;
1906
+ recurringIndefinite: boolean;
1907
+ recurringCharges?: number | null;
1908
+ }): string;
1909
+
1910
+ /**
1911
+ * One editor for a catalog-backed product: pricing and storefront metadata
1912
+ * (the-backend's) laid over ONE Apex catalog item (Apex's).
1913
+ *
1914
+ * Apex owns the structure — the item's strengths (doses, `cdose_…`), which
1915
+ * pharmacy drug fills the item at each pharmacy, and the pharmacies' preference
1916
+ * order. the-backend owns what each strength costs, keyed by the Apex dose id
1917
+ * inside `product.dosagePrices[].apexSkuId`. An admin should not need to know
1918
+ * two systems are involved, so this flow presents them as one and takes care of
1919
+ * the seam:
1920
+ *
1921
+ * - Writes are not atomic across the two systems. EVERY sequence writes Apex
1922
+ * first and the-backend second, so a failure between them leaves a state the
1923
+ * same screen can finish: a strength that exists and "needs a price", an item
1924
+ * that exists and is "Available to add". A priced product never points at
1925
+ * something Apex doesn't have.
1926
+ * - A write is never retried blindly. When the outcome is ambiguous (network
1927
+ * drop, 5xx, timeout) the editor re-reads from the server and only offers a
1928
+ * retry once it has seen that the write did not land — or adopts the result
1929
+ * if it did. If it can't re-read, it offers nothing and says why.
1930
+ * - Fails closed for STRUCTURE: when Apex can't be asked, strengths and
1931
+ * fulfillments become read-only. Pricing and metadata stay editable.
1932
+ * - Apex's own 4xx messages (classification must agree, one fulfillment per
1933
+ * pharmacy, …) are shown next to the control that caused them, verbatim.
1934
+ * - `dosagePrices` is round-tripped, never rebuilt from the ladder: PATCH
1935
+ * replaces the whole array, and a price whose dose Apex stopped offering
1936
+ * (an orphan) lives only there until an admin explicitly removes it.
1937
+ *
1938
+ * The pure decision logic (error classification, row building, price edits,
1939
+ * reorder maths, readiness reading) is exported separately and unit-tested
1940
+ * without a component tree.
1941
+ */
1942
+
1943
+ /** The `code`s the admin catalog proxy answers when Apex itself is the problem. */
1944
+ type ApexBlockCode = 'apex_unavailable' | 'apex_credentials_rejected' | 'apex_not_configured';
1945
+ type CatalogFailure =
1946
+ /** Apex (or the backend) refused: a definitive "it did not happen". `message`
1947
+ * is Apex's own invariant text and is shown unchanged. */
1948
+ {
1949
+ kind: 'rejected';
1950
+ message: string;
1951
+ status?: number;
1952
+ }
1953
+ /** Apex can't be used at all right now. `definitive`: the request was refused
1954
+ * before anything could happen (bad credentials, not linked). */
1955
+ | {
1956
+ kind: 'blocked';
1957
+ code: ApexBlockCode;
1958
+ message: string;
1959
+ definitive: boolean;
1960
+ }
1961
+ /** The request may or may not have landed (dropped connection, 5xx, timeout). */
1962
+ | {
1963
+ kind: 'ambiguous';
1964
+ message: string;
1965
+ };
1966
+ /**
1967
+ * Sort a thrown error into what the editor can do about it. Duck-typed on
1968
+ * `status` / `code` / `ambiguous` (what `ApiError` carries) so it has no
1969
+ * dependency on the class identity; branches on codes and statuses, never on
1970
+ * message prose.
1971
+ */
1972
+ declare function classifyCatalogError(err: unknown): CatalogFailure;
1973
+ type StoredDosePrice = AdminProduct['dosagePrices'][number];
1974
+ /** A strength as the editor lists it: Apex's dose joined to our price for it. */
1975
+ interface StrengthRow {
1976
+ /** The Apex dose id, or `label:<dosage>` for a stored row with no id. */
1977
+ key: string;
1978
+ doseId: string | null;
1979
+ label: string;
1980
+ value: number | null;
1981
+ unit: string | null;
1982
+ /** False for a dose Apex has withdrawn: listed, never sold, no price to set. */
1983
+ active: boolean;
1984
+ /** This dose's own stored price (null: it charges the product base price). */
1985
+ ownPrice: number | null;
1986
+ }
1987
+ /** The stored entry a dose's price lives on: bound to its id, else a label-only
1988
+ * entry saved before anything was bound (the only handle that entry has). */
1989
+ declare function findStoredDosePrice(stored: readonly StoredDosePrice[], doseId: string | null, label: string): StoredDosePrice | undefined;
1990
+ /**
1991
+ * The strengths list. Apex's catalog read is the authority for which doses
1992
+ * exist (inactive ones included); the product's own `strengths` fills in when
1993
+ * the catalog read is unavailable, and the stored `dosagePrices` is the last
1994
+ * resort so pricing stays editable even then.
1995
+ */
1996
+ declare function buildStrengthRows(product: AdminProduct, readiness: CatalogReadiness | null): StrengthRow[];
1997
+ interface ResolvedStrength {
1998
+ row: StrengthRow;
1999
+ /** What a customer would be charged for this strength. */
2000
+ price: number | null;
2001
+ source: 'dose' | 'base' | null;
2002
+ /** No price from the dose or the base: it can't be sold. Withdrawn doses never need one. */
2003
+ needsPrice: boolean;
2004
+ }
2005
+ /**
2006
+ * Each strength's effective price with the admin's unsaved edits applied —
2007
+ * the backend's own rule (a dose's price, else the base price), so "needs a
2008
+ * price" on screen is what will be true after Save. A flat-fee product charges
2009
+ * the base price for every strength.
2010
+ */
2011
+ declare function resolveStrengthPrices(rows: readonly StrengthRow[], drafts: Readonly<Record<string, string>>, base: number | null, flatFee: boolean): ResolvedStrength[];
2012
+ /**
2013
+ * The `dosagePrices` array after applying unsaved price edits, or `null` when
2014
+ * nothing would change. Edits an entry in place (matched by Apex dose id) and
2015
+ * leaves every other entry — orphans included, unknown keys included — exactly
2016
+ * as stored: this is the round-trip that PATCH-replaces-the-array demands. It
2017
+ * never rebuilds from the ladder.
2018
+ */
2019
+ declare function applyPriceDrafts(stored: readonly StoredDosePrice[], rows: readonly StrengthRow[], drafts: Readonly<Record<string, string>>): StoredDosePrice[] | null;
2020
+ /** Adds or updates one dose's price in the stored array, touching nothing else. */
2021
+ declare function upsertDosePrice(stored: readonly StoredDosePrice[], dose: {
2022
+ dosage: string;
2023
+ apexSkuId: string;
2024
+ price: number | null;
2025
+ }): StoredDosePrice[];
2026
+ /** The stored array minus ONE orphaned entry (the explicit "remove" action). */
2027
+ declare function removeStoredDosePrice(stored: readonly StoredDosePrice[], orphan: Pick<AdminOrphanedDosePrice, 'dosage' | 'apexSkuId'>): StoredDosePrice[];
2028
+ /** True for an Apex partner-catalog item id (`cat_…`), as opposed to a legacy
2029
+ * pharmacy drug id. The only place this package looks at an Apex id's shape. */
2030
+ declare function isCatalogItemId(id: string | null | undefined): id is string;
2031
+ /**
2032
+ * The binding mode that goes with a dose-keyed `dosagePrices`: `bound` once any
2033
+ * entry carries an Apex dose id (so the id is forwarded with the order),
2034
+ * `prescriber_picks` is the admin's explicit choice and is never overridden.
2035
+ */
2036
+ declare function skuBindingModeFor(dosagePrices: readonly StoredDosePrice[], current: AdminProduct['skuBindingMode']): AdminProduct['skuBindingMode'];
2037
+ declare const ORPHAN_REASON: Record<AdminOrphanedDosePrice['reason'], string>;
2038
+ interface FulfillmentRow {
2039
+ id: string;
2040
+ rank: number;
2041
+ pharmacyId: string;
2042
+ pharmacyName: string;
2043
+ drugId: string;
2044
+ drugName: string;
2045
+ enabled: boolean;
2046
+ excludedStates: string[];
2047
+ /** Setup problems that block this whole mapping (missing credentials, …). */
2048
+ problems: string[];
2049
+ }
2050
+ /** One row per pharmacy, in preference order (Apex orders by rank, then pharmacy). */
2051
+ declare function buildFulfillmentRows(readiness: CatalogReadiness | null, drugs: readonly CatalogMappableDrug[]): FulfillmentRow[];
2052
+ /** `ids` with `id` moved one place; the same array when it can't move. */
2053
+ declare function moveInOrder(ids: readonly string[], id: string, direction: 'up' | 'down'): string[];
2054
+ /** Excluded states as Apex wants them: two-letter, upper-case, unique, sorted. */
2055
+ declare function normalizeStates(states: readonly string[]): string[];
2056
+ type ReadinessStatus = 'ready' | 'incomplete' | 'unfillable';
2057
+ /**
2058
+ * One traffic light for the item, read the way Apex's own editor reads it:
2059
+ * unfillable with no enabled pharmacy; ready when every dose is producible
2060
+ * somewhere and no mapping has setup problems; incomplete otherwise.
2061
+ */
2062
+ declare function readinessStatus(readiness: CatalogReadiness): ReadinessStatus;
2063
+ declare const READINESS_LABEL: Record<ReadinessStatus, string>;
2064
+ interface MatrixView {
2065
+ doses: Array<{
2066
+ id: string;
2067
+ label: string;
2068
+ active: boolean;
2069
+ }>;
2070
+ columns: FulfillmentRow[];
2071
+ cells: Record<string, Record<string, {
2072
+ producible: boolean;
2073
+ detail?: string;
2074
+ }>>;
2075
+ /** "New Life can't make 7.5 mg" — one sentence per cell that can't be made. */
2076
+ problems: Array<{
2077
+ pharmacyName: string;
2078
+ dose: string;
2079
+ sentence: string;
2080
+ detail?: string;
2081
+ }>;
2082
+ }
2083
+ /** The dose × pharmacy grid in preference order, plus the misses spelled out. */
2084
+ declare function buildMatrixView(readiness: CatalogReadiness | null, columns: readonly FulfillmentRow[]): MatrixView;
2085
+ /** Mappable drugs grouped by pharmacy (name order), minus pharmacies already mapped. */
2086
+ declare function groupDrugsByPharmacy(drugs: readonly CatalogMappableDrug[], mappedPharmacyIds?: ReadonlySet<string>): Array<{
2087
+ pharmacyId: string;
2088
+ pharmacyName: string;
2089
+ drugs: CatalogMappableDrug[];
2090
+ }>;
2091
+ type StructureState = {
2092
+ kind: 'loading';
2093
+ } | {
2094
+ kind: 'editable';
2095
+ }
2096
+ /** Apex can't be asked: structure is read-only; pricing and metadata are not. */
2097
+ | {
2098
+ kind: 'read_only';
2099
+ message: string;
2100
+ }
2101
+ /** Apex no longer lists this product's catalog item. */
2102
+ | {
2103
+ kind: 'missing';
2104
+ };
2105
+ type AddStrengthOutcome =
2106
+ /** The strength exists (and is priced, when a price was given). */
2107
+ {
2108
+ kind: 'added';
2109
+ doseId: string;
2110
+ }
2111
+ /** The strength exists in Apex but its price did not save: it shows "needs a
2112
+ * price" and the attempted price is kept as a draft to save again. */
2113
+ | {
2114
+ kind: 'added_unpriced';
2115
+ doseId: string;
2116
+ message: string;
2117
+ } | {
2118
+ kind: 'rejected' | 'not_done' | 'unknown' | 'blocked' | 'busy';
2119
+ message: string;
2120
+ };
2121
+ interface AddStrengthInput {
2122
+ label?: string;
2123
+ value?: number;
2124
+ unit?: string;
2125
+ /** Dollars as typed; blank adds the strength without its own price. */
2126
+ price?: string;
2127
+ }
2128
+ interface UseProductCatalogEditorOptions {
2129
+ /** The product being edited (its `apexDrugId` is the catalog item). */
2130
+ product: Accessor<AdminProduct>;
2131
+ /** Called with the product the server returned after a write the editor made. */
2132
+ onProductChanged?: (product: AdminProduct) => void;
2133
+ /** False for a product that isn't catalog-backed: nothing is loaded or called. Default true. */
2134
+ enabled?: Accessor<boolean>;
2135
+ }
2136
+ interface ProductCatalogEditor {
2137
+ product: Accessor<AdminProduct>;
2138
+ item: Accessor<CatalogItem | null>;
2139
+ structure: Accessor<StructureState>;
2140
+ loading: Accessor<boolean>;
2141
+ /** The control being written right now (all structure controls disable on it). */
2142
+ busy: Accessor<string | null>;
2143
+ /** Re-read the item, the pharmacy drugs and the product. Clears a read-only state if Apex answers. */
2144
+ reload: () => Promise<void>;
2145
+ /** Server messages by control: `strength:add`, `strength:<rowKey>`, `orphan:<key>`,
2146
+ * `fulfillment:add`, `fulfillment:<id>`, `suggest:doses`, `suggest:equivalents`. */
2147
+ errors: Accessor<Readonly<Record<string, string>>>;
2148
+ clearError: (key: string) => void;
2149
+ rows: Accessor<StrengthRow[]>;
2150
+ orphans: Accessor<AdminOrphanedDosePrice[]>;
2151
+ priceDrafts: Accessor<Readonly<Record<string, string>>>;
2152
+ setPriceDraft: (rowKey: string, value: string) => void;
2153
+ clearPriceDrafts: () => void;
2154
+ /** `dosagePrices` with the unsaved price edits applied to the stored array, or null if none. */
2155
+ dosagePricesUpdate: () => StoredDosePrice[] | null;
2156
+ addStrength: (input: AddStrengthInput) => Promise<AddStrengthOutcome>;
2157
+ removeStrength: (doseId: string) => Promise<boolean>;
2158
+ removeOrphan: (orphan: AdminOrphanedDosePrice) => Promise<boolean>;
2159
+ doseSuggestions: Accessor<CatalogDoseSuggestion[] | null>;
2160
+ loadDoseSuggestions: () => Promise<void>;
2161
+ addSuggestedDoses: (picked: CatalogDoseSuggestion[]) => Promise<{
2162
+ added: number;
2163
+ stoppedAt?: string;
2164
+ }>;
2165
+ drugs: Accessor<CatalogMappableDrug[]>;
2166
+ fulfillments: Accessor<FulfillmentRow[]>;
2167
+ addFulfillment: (pharmacyId: string, drugId: string) => Promise<boolean>;
2168
+ setFulfillmentEnabled: (fulfillmentId: string, enabled: boolean) => Promise<boolean>;
2169
+ setExcludedStates: (fulfillmentId: string, states: string[]) => Promise<boolean>;
2170
+ removeFulfillment: (fulfillmentId: string) => Promise<boolean>;
2171
+ moveFulfillment: (fulfillmentId: string, direction: 'up' | 'down') => Promise<boolean>;
2172
+ equivalents: Accessor<CatalogEquivalentSuggestions | null>;
2173
+ loadEquivalents: () => Promise<void>;
2174
+ readiness: Accessor<CatalogReadiness | null>;
2175
+ status: Accessor<ReadinessStatus | null>;
2176
+ matrix: Accessor<MatrixView>;
2177
+ warnings: Accessor<string[]>;
2178
+ }
2179
+ declare function useProductCatalogEditor(opts: UseProductCatalogEditorOptions): ProductCatalogEditor;
2180
+ type NewCatalogProductInput = {
2181
+ mode: 'from_drug';
2182
+ drugId: string;
2183
+ } | {
2184
+ mode: 'blank';
2185
+ name: string;
2186
+ classification: CatalogClassification;
2187
+ doseModel: CatalogDoseModel;
2188
+ description?: string;
2189
+ };
2190
+ type CreateCatalogProductOutcome =
2191
+ /** The item exists in Apex and the product exists in the-backend (hidden, unpriced). */
2192
+ {
2193
+ kind: 'created';
2194
+ productId: string;
2195
+ itemId: string;
2196
+ name: string;
2197
+ warning?: string;
2198
+ }
2199
+ /** The item exists in Apex but no product points at it yet. It now appears
2200
+ * under "Available to add"; `addCatalogItemAsProduct` finishes the job (safe:
2201
+ * it creates no second item). */
2202
+ | {
2203
+ kind: 'item_only';
2204
+ itemId: string;
2205
+ name: string;
2206
+ message: string;
2207
+ }
2208
+ /** Nothing was created (Apex refused, or an ambiguous failure was shown not to have landed). */
2209
+ | {
2210
+ kind: 'failed';
2211
+ message: string;
2212
+ retryable: boolean;
2213
+ }
2214
+ /** An ambiguous failure that could not be re-read: whether an item exists is
2215
+ * unknown, so no retry is offered. */
2216
+ | {
2217
+ kind: 'unknown';
2218
+ message: string;
2219
+ };
2220
+ /**
2221
+ * Add the-backend product for an Apex catalog item that has none yet. Used as
2222
+ * step two of `createCatalogProduct` and on its own to finish after a partial
2223
+ * failure. It creates no catalog item, so retrying it can't duplicate one.
2224
+ */
2225
+ declare function addCatalogItemAsProduct(itemId: string, name: string): Promise<{
2226
+ kind: 'created';
2227
+ productId: string;
2228
+ } | {
2229
+ kind: 'failed';
2230
+ message: string;
2231
+ maybeCreated: boolean;
2232
+ }>;
2233
+ /**
2234
+ * "New prescription product": create the catalog item in Apex (blank, or seeded
2235
+ * from a pharmacy drug), THEN the product in the-backend. Apex first, always,
2236
+ * so a product can never point at an item that failed to create; if the second
2237
+ * step fails the item stays and is offered under "Available to add".
2238
+ */
2239
+ declare function createCatalogProduct(input: NewCatalogProductInput): Promise<CreateCatalogProductOutcome>;
2240
+
2241
+ /**
2242
+ * "Convert to catalog product": move ONE legacy prescribed product (its
2243
+ * `apexDrugId` is an individual pharmacy drug) onto a partner catalog item, and
2244
+ * back — the headless flow behind the product editor's guided panel.
2245
+ *
2246
+ * The backend owns the state machine and reports the stage the product is in on
2247
+ * every read; this flow only ever renders that stage. What the admin sees is
2248
+ * decided by the server's preview, never by what this screen remembers:
2249
+ *
2250
+ * not_started → `ready` the catalog item doesn't exist yet: PREPARE creates it
2251
+ * INACTIVE (nothing is sold from it, the product is untouched)
2252
+ * ready_to_commit → `reviewing` the item exists: match strengths, then CONVERT
2253
+ * active_not_committed → `reviewing` (`unfinished`) a conversion switched the item on and the
2254
+ * re-point didn't land; converting again re-points only
2255
+ * committed_not_active → `finish_activation` re-pointed, but the item isn't listed
2256
+ * converted → `converted` undo is available while the backend records the run
2257
+ * not_convertible / any blocker → `blocked`
2258
+ *
2259
+ * Rules this flow keeps:
2260
+ *
2261
+ * - A write is never retried blindly. After ANY failure — a refusal, a 5xx, a
2262
+ * dropped connection, a proxy timeout — the preview is re-read and the stage
2263
+ * it reports is what gets rendered. A write is offered again only from a
2264
+ * stage in which it is a fresh decision, and prepare/convert only ever with
2265
+ * the `planHash` of the preview the admin is looking at.
2266
+ * - When the answer to a convert was lost the server may STILL be working (it
2267
+ * takes about 35 seconds). That is `watching`: read-only polling for a
2268
+ * bounded time, no write offered, until the stage settles.
2269
+ * - `plan_changed` shows the fresh preview and puts the admin back in review.
2270
+ * The old matches are dropped, never resubmitted.
2271
+ * - Every source (a price entry, the single-dose binding, a label subscribers
2272
+ * hold) must end with a strength of the new item or an explicit "not carried
2273
+ * over" before Convert can be sent. A suggestion pre-selects; no suggestion
2274
+ * leaves the row undecided. The two rules the backend would refuse a `null`
2275
+ * for are mirrored here so they aren't offered.
2276
+ * - Reviewing and confirming are separate acts (`confirmReview`), and a changed
2277
+ * plan clears the confirmation.
2278
+ *
2279
+ * The decision logic (matches, blockers, the confirm summary, error sorting) is
2280
+ * exported as pure functions and tested without a component tree.
2281
+ */
2282
+
2283
+ /** A legacy prescribed product: it has an Apex pointer, and the pointer is a
2284
+ * pharmacy drug rather than a catalog item. Non-Rx and catalog products never
2285
+ * show "Convert to catalog product". */
2286
+ declare function canOfferConversion(product: Pick<AdminProduct, 'apexDrugId' | 'catalogOverlay'>): boolean;
2287
+ type ConversionFailure =
2288
+ /** The server said no, and said it before doing anything: 4xx. */
2289
+ {
2290
+ kind: 'refused';
2291
+ message: string;
2292
+ status: number;
2293
+ code?: string;
2294
+ }
2295
+ /** `plan_changed`: what the admin reviewed is no longer the plan. */
2296
+ | {
2297
+ kind: 'plan_changed';
2298
+ message: string;
2299
+ }
2300
+ /** `conversion_in_progress`: a step for this product is running on the server right now. */
2301
+ | {
2302
+ kind: 'in_progress';
2303
+ message: string;
2304
+ }
2305
+ /** The request may or may not have landed (dropped connection, proxy timeout, 5xx).
2306
+ * `serverFinished`: the backend answered with its own `code`, so its attempt is over;
2307
+ * without one the answer never reached us and the server may still be working. */
2308
+ | {
2309
+ kind: 'ambiguous';
2310
+ message: string;
2311
+ serverFinished: boolean;
2312
+ code?: string;
2313
+ };
2314
+ /**
2315
+ * Sort a thrown error into what the flow can do about it. Duck-typed on
2316
+ * `status` / `code` / `ambiguous` (what `ApiError` carries); branches on codes
2317
+ * and statuses, never on message prose.
2318
+ */
2319
+ declare function classifyConversionError(err: unknown): ConversionFailure;
2320
+ interface FindingCopy {
2321
+ /** A plain-language headline for a code we know. Null: the backend's text is all there is. */
2322
+ title: string | null;
2323
+ /** The backend's own explanation, verbatim. */
2324
+ message: string;
2325
+ }
2326
+ /** Warnings that describe the SUGGESTED matches; once the admin changes one they
2327
+ * no longer describe what will happen (the review step recomputes them). */
2328
+ declare const MATCH_DEPENDENT_WARNINGS: readonly string[];
2329
+ declare function explainFinding(finding: Pick<CatalogConversionFinding, 'code' | 'message'>): FindingCopy;
2330
+ /** A choice for one source: a dose id of the new item; `null` = not carried over;
2331
+ * absent from the record = not decided yet. */
2332
+ type MatchChoice = string | null;
2333
+ type MatchRecord = Readonly<Record<string, MatchChoice | undefined>>;
2334
+ /** The key a source goes by: the same pair the backend identifies it with. */
2335
+ declare const sourceKey: (source: Pick<CatalogConversionSource, "dosage" | "apexSkuId">) => string;
2336
+ /** What the admin knows a source as. */
2337
+ declare function sourceLabel(source: CatalogConversionSource): string;
2338
+ declare const SOURCE_FIELD_NOTE: Record<CatalogConversionSource['field'], string | null>;
2339
+ declare const MATCH_HOW_LABEL: Record<NonNullable<CatalogConversionDoseMatch['how']>, string>;
2340
+ /** The strengths a match may name: the item's LIVE doses, in the order given. */
2341
+ declare const liveDoses: (preview: Pick<CatalogConversionPreview, "doses">) => CatalogConversionDose[];
2342
+ /**
2343
+ * Whether "not carried over" is a choice the backend would accept for a source.
2344
+ * It refuses the single-dose binding (a legacy pack id on a catalog product is
2345
+ * refused at intake), and a source with no id whose label a live dose carries
2346
+ * exactly (it would keep matching by label whatever is chosen).
2347
+ */
2348
+ declare function canLeaveUnmatched(match: CatalogConversionDoseMatch, doses: readonly CatalogConversionDose[]): boolean;
2349
+ /** The pre-fill: each suggestion chosen, every other source undecided. */
2350
+ declare function initialMatches(preview: Pick<CatalogConversionPreview, 'doseMatches'>): MatchRecord;
2351
+ type MatchProblem = 'undecided' | 'not_offered' | 'cannot_be_left';
2352
+ /** What stops a source's choice being sent. Empty: it can go. */
2353
+ declare function matchProblem(match: CatalogConversionDoseMatch, choice: MatchChoice | undefined, doses: readonly CatalogConversionDose[]): MatchProblem | null;
2354
+ declare const matchesComplete: (preview: CatalogConversionPreview, matches: MatchRecord) => boolean;
2355
+ /** The body `commit` is sent, or null while any source is undecided or invalid. */
2356
+ declare function toChoices(preview: CatalogConversionPreview, matches: MatchRecord): CatalogConversionChoice[] | null;
2357
+ /** Sources with subscribers that would be left behind: flagged for review at their next renewal. */
2358
+ declare function flaggedSubscribers(preview: Pick<CatalogConversionPreview, 'doseMatches'>, matches: MatchRecord): Array<{
2359
+ source: CatalogConversionSource;
2360
+ subscribers: number;
2361
+ }>;
2362
+ interface ConversionSummary {
2363
+ itemId: string | null;
2364
+ itemName: string | null;
2365
+ carried: Array<{
2366
+ label: string;
2367
+ price: number | null;
2368
+ doseLabel: string;
2369
+ subscribers: number;
2370
+ }>;
2371
+ /** Not carried over: kept on file, never sold. `price` null for a source with no price. */
2372
+ left: Array<{
2373
+ label: string;
2374
+ price: number | null;
2375
+ subscribers: number;
2376
+ }>;
2377
+ /** Subscribers who will be flagged for review at their next renewal. */
2378
+ flaggedSubscribers: number;
2379
+ /** What the new item's strengths sell for after the switch. */
2380
+ strengthsAfter: Array<{
2381
+ label: string;
2382
+ doseId: string;
2383
+ price: number | null;
2384
+ fromBase: boolean;
2385
+ needsPrice: boolean;
2386
+ }>;
2387
+ }
2388
+ /**
2389
+ * What converting with THESE matches does, worked out the way the backend prices
2390
+ * a catalog product: a strength sells at the first priced entry matched to it,
2391
+ * else at the product's base price (a flat-fee product always charges the base
2392
+ * price); with neither it needs a price.
2393
+ */
2394
+ declare function describeConversion(preview: CatalogConversionPreview, matches: MatchRecord, basePrice: number | null): ConversionSummary;
2395
+ declare const hasBlockers: (p: CatalogConversionPreview) => boolean;
2396
+ /** A conversion in force for this product (the run an undo would reverse). */
2397
+ declare const hasConversion: (p: CatalogConversionPreview | null) => boolean;
2398
+ type ConversionNotice = {
2399
+ tone: 'info' | 'success' | 'warn' | 'danger';
2400
+ message: string;
2401
+ /** The backend's refusal code, when there was one. */
2402
+ code?: string;
2403
+ };
2404
+ type ConversionState =
2405
+ /** Not enabled: nothing has been read. */
2406
+ {
2407
+ kind: 'idle';
2408
+ }
2409
+ /** Reading the server's state (the first read, a re-read after a write, or "check again"). */
2410
+ | {
2411
+ kind: 'loading';
2412
+ reason: 'initial' | 'reconcile' | 'refresh';
2413
+ }
2414
+ /** The server's state couldn't be read, so nothing is offered but another read. */
2415
+ | {
2416
+ kind: 'unreadable';
2417
+ message: string;
2418
+ afterWrite: boolean;
2419
+ }
2420
+ /** Not convertible right now (not_convertible, or any blocker). Blockers are on the preview. */
2421
+ | {
2422
+ kind: 'blocked';
2423
+ }
2424
+ /** `not_started`: the catalog item doesn't exist yet. */
2425
+ | {
2426
+ kind: 'ready';
2427
+ } | {
2428
+ kind: 'preparing';
2429
+ }
2430
+ /** `ready_to_commit` / `active_not_committed`: match strengths, then convert. */
2431
+ | {
2432
+ kind: 'reviewing';
2433
+ unfinished: boolean;
2434
+ confirming: boolean;
2435
+ }
2436
+ /** The long one (about 35 seconds). `resume`: activation only, no re-point. */
2437
+ | {
2438
+ kind: 'committing';
2439
+ resume: 'convert' | 'activation';
2440
+ }
2441
+ /** The answer was lost and the server may still be working: read-only polling. */
2442
+ | {
2443
+ kind: 'watching';
2444
+ reason: 'dropped' | 'in_progress';
2445
+ }
2446
+ /** `committed_not_active`: re-pointed at an item Apex doesn't list. */
2447
+ | {
2448
+ kind: 'finish_activation';
2449
+ } | {
2450
+ kind: 'converted';
2451
+ origin: 'committed' | 'recovered' | 'existing';
2452
+ } | {
2453
+ kind: 'undoing';
2454
+ }
2455
+ /** The product is back on its legacy drug. `result` is null when the reply was lost. */
2456
+ | {
2457
+ kind: 'undone';
2458
+ result: CatalogConversionUndoResult | null;
2459
+ };
2460
+ interface ConversionConverted {
2461
+ productId: string;
2462
+ origin: 'committed' | 'recovered';
2463
+ warnings: CatalogConversionFinding[];
2464
+ }
2465
+ interface UseCatalogConversionOptions {
2466
+ /** The product being converted (or whose conversion is being managed). */
2467
+ product: Accessor<AdminProduct>;
2468
+ /** False: nothing is read. Default true. */
2469
+ enabled?: Accessor<boolean>;
2470
+ /** Called once when a conversion is confirmed done — this session's convert, or one found finished after a lost answer. */
2471
+ onConverted?: (info: ConversionConverted) => void;
2472
+ /** Called once when an undo is confirmed done. */
2473
+ onUndone?: (info: {
2474
+ productId: string;
2475
+ result: CatalogConversionUndoResult | null;
2476
+ }) => void;
2477
+ /** While `watching`, how often the preview is re-read. Default 5 s. */
2478
+ pollIntervalMs?: number;
2479
+ /** While `watching`, how long to wait before handing the decision back. Default 2 min. */
2480
+ watchWindowMs?: number;
2481
+ }
2482
+ interface CatalogConversion {
2483
+ state: Accessor<ConversionState>;
2484
+ /** The server's last answer. The only source of truth for the stage. */
2485
+ preview: Accessor<CatalogConversionPreview | null>;
2486
+ /** The latest thing worth telling the admin (a refusal, what a lost answer turned out to be). */
2487
+ notice: Accessor<ConversionNotice | null>;
2488
+ dismissNotice: () => void;
2489
+ /** A step is running: nothing else can be started. */
2490
+ busy: Accessor<boolean>;
2491
+ /** Re-read the preview ("check again"). Safe to repeat. */
2492
+ reload: () => Promise<void>;
2493
+ rows: Accessor<MatchRow[]>;
2494
+ /** The strengths of the new item a source can be matched to. */
2495
+ doses: Accessor<CatalogConversionDose[]>;
2496
+ setMatch: (key: string, choice: MatchChoice) => void;
2497
+ /** Mark every undecided source "not carried over" (only those that may be). */
2498
+ leaveUndecidedUnmatched: () => void;
2499
+ resetToSuggestions: () => void;
2500
+ undecidedCount: Accessor<number>;
2501
+ complete: Accessor<boolean>;
2502
+ flagged: Accessor<Array<{
2503
+ source: CatalogConversionSource;
2504
+ subscribers: number;
2505
+ }>>;
2506
+ summary: Accessor<ConversionSummary | null>;
2507
+ /** Review done: show the confirm step. Needs a complete set of matches. */
2508
+ confirmReview: () => boolean;
2509
+ /** Back from the confirm step to the strengths. */
2510
+ backToReview: () => void;
2511
+ prepare: () => Promise<void>;
2512
+ commit: () => Promise<void>;
2513
+ /** `committed_not_active` only: activation, no matches involved. */
2514
+ finishActivation: () => Promise<void>;
2515
+ /** Undo is offered while the backend records a conversion of this product. */
2516
+ canUndo: Accessor<boolean>;
2517
+ undo: (options?: CatalogConversionUndoOptions) => Promise<void>;
2518
+ /** While `watching`: read now instead of waiting for the next poll. */
2519
+ checkNow: () => Promise<void>;
2520
+ /** The convert answer, once it arrived: the warnings that stood for the matches applied. */
2521
+ lastCommit: Accessor<CatalogConversionCommitResult | null>;
2522
+ }
2523
+ interface MatchRow {
2524
+ key: string;
2525
+ match: CatalogConversionDoseMatch;
2526
+ source: CatalogConversionSource;
2527
+ label: string;
2528
+ /** undefined: not decided. null: not carried over. */
2529
+ choice: MatchChoice | undefined;
2530
+ /** Differs from what the backend suggested. */
2531
+ changed: boolean;
2532
+ canLeaveUnmatched: boolean;
2533
+ /** Subscribers who'd be flagged for review at their next renewal. */
2534
+ flagged: boolean;
2535
+ problem: MatchProblem | null;
2536
+ }
2537
+ declare function useCatalogConversion(opts: UseCatalogConversionOptions): CatalogConversion;
2538
+
2539
+ /**
2540
+ * "Add pharmacy": the one way an admin gives a prescribed product another
2541
+ * pharmacy, whatever the product is today — the headless flow behind the
2542
+ * product editor's Pharmacies section.
2543
+ *
2544
+ * idle → picking → planning → reviewing → saving → done
2545
+ * ↘ failed ↙ ↖ (plan changed: planning again)
2546
+ *
2547
+ * The server decides what an add takes. On a product that fills at a single
2548
+ * pharmacy it also moves the product onto a multi-pharmacy item, behind the
2549
+ * scenes; the plan says so only as `kind: 'convert'`, and nothing here (or in
2550
+ * the screen) says it to the admin. What the admin sees is the pharmacy, the
2551
+ * strengths and prices before and after, and any decision they owe.
2552
+ *
2553
+ * Rules this flow keeps:
2554
+ *
2555
+ * - The server's plan is the only thing that decides what can be saved. The
2556
+ * save carries the plan's `planHash`; when the plan moved on (`plan_changed`,
2557
+ * `plan_first`) the flow plans again by itself and returns to review with a
2558
+ * notice. Prices typed for a strength that is still owed are kept.
2559
+ * - A save is never retried blindly. After a failure whose outcome is not
2560
+ * known (a dropped connection, a proxy timeout, a 5xx) the product is
2561
+ * re-read: if the pharmacy is on it now the add is done; if not, the admin
2562
+ * is offered a re-check, or to start again from a fresh plan.
2563
+ * - A plan that needs no decision (no blockers, no admin-facing warnings, no
2564
+ * price owed, strengths unchanged) is a single confirm step: `needsReview`.
2565
+ * - `ops` findings are for operators and never reach the screen.
2566
+ * - Subscribers on a strength that matched no new one ("match questions") are
2567
+ * the admin's to place. Each answer re-plans (debounced; only the latest
2568
+ * response is adopted; saving waits), because an answered strength carries
2569
+ * its price over and so changes what is owed. Typed prices are kept. The
2570
+ * answers ride along on the save, and on a `plan_changed` re-plan.
2571
+ *
2572
+ * The decision logic (what to show, what is missing, the save body, error
2573
+ * sorting) is exported as pure functions and tested without a component tree.
2574
+ */
2575
+
2576
+ /** The admin's answers to match questions, by `matchKey`. A key is present once answered; null = leave for review. */
2577
+ type MatchAnswers = Readonly<Record<string, string | null>>;
2578
+ /** The warnings an admin should read. `ops` findings are for operators. */
2579
+ declare function visibleWarnings(plan: Pick<AddPharmacyPlan, 'warnings'>): AddPharmacyFinding[];
2580
+ /** A price as typed: a positive amount of at most two decimals. Null = blank or not valid. */
2581
+ declare function parseMoney(raw: string | undefined): number | null;
2582
+ /** The doses the plan asks a price for that have no valid one typed yet. */
2583
+ declare function missingPrices(plan: Pick<AddPharmacyPlan, 'pricesRequired'>, prices: Readonly<Record<string, string>>): string[];
2584
+ /** Whether the strengths a customer can buy differ after the save (by dosage, then price). */
2585
+ declare function strengthsChanged(plan: Pick<AddPharmacyPlan, 'strengthsBefore' | 'strengthsAfter'>): boolean;
2586
+ /**
2587
+ * True when the admin has something to read or decide: a blocker, an
2588
+ * admin-facing warning, a price owed, or strengths that change. False means one
2589
+ * confirm step is enough.
2590
+ */
2591
+ declare function needsReview(plan: AddPharmacyPlan): boolean;
2592
+ interface StrengthComparison {
2593
+ dosage: string;
2594
+ /** What a customer pays now: a price, `null` for a strength with no price, `undefined` for one not sold yet. */
2595
+ before: number | null | undefined;
2596
+ /** What a customer pays after the save: a price, or `null` when it still needs one. */
2597
+ after: number | null;
2598
+ /** Not sold now, sold after. */
2599
+ isNew: boolean;
2600
+ }
2601
+ /** "Now" against "after saving", one row per strength: today's strengths first, then the new ones. */
2602
+ declare function compareStrengths(plan: Pick<AddPharmacyPlan, 'strengthsBefore' | 'strengthsAfter'>): StrengthComparison[];
2603
+ /** The name the admin knows the pharmacy by. */
2604
+ declare function pharmacyLabel(plan: Pick<AddPharmacyPlan, 'pharmacy'>): string;
2605
+ /**
2606
+ * The save body for a plan: the plan's hash (absent on a plain add) and a price
2607
+ * for every strength the plan asked for, with the optional member price only
2608
+ * when one was typed, and the admin's answers to the plan's match questions
2609
+ * (only those answered). `autoPrices` are the server's to apply and are not sent.
2610
+ */
2611
+ declare function buildSaveBody(plan: AddPharmacyPlan, prices: Readonly<Record<string, string>>, savingsPrices?: Readonly<Record<string, string>>, matchAnswers?: MatchAnswers): AddPharmacyBody;
2612
+ /** Whether the product, as the server reports it now, already has the planned pharmacy drug. */
2613
+ declare function pharmacyIsOnProduct(product: Pick<AdminProduct, 'pharmacies'> | null | undefined, plan: Pick<AddPharmacyPlan, 'pharmacy'>): boolean;
2614
+ type AddPharmacyFailure =
2615
+ /** `plan_changed` / `plan_first`: what the admin reviewed is no longer the plan. */
2616
+ {
2617
+ kind: 'replan';
2618
+ message: string;
2619
+ code: string;
2620
+ }
2621
+ /** `prices_required`: `missing` are the dose ids the server says have no price. */
2622
+ | {
2623
+ kind: 'prices_required';
2624
+ message: string;
2625
+ missing: string[];
2626
+ }
2627
+ /** The server said no before doing anything. `retryable`: a fresh plan could get a different answer. */
2628
+ | {
2629
+ kind: 'refused';
2630
+ message: string;
2631
+ status: number;
2632
+ code?: string;
2633
+ retryable: boolean;
2634
+ }
2635
+ /** The request may or may not have landed. `serverFinished`: the backend answered with its own
2636
+ * `code`, so its attempt is over; without one the answer never reached us. */
2637
+ | {
2638
+ kind: 'ambiguous';
2639
+ message: string;
2640
+ serverFinished: boolean;
2641
+ code?: string;
2642
+ };
2643
+ /**
2644
+ * Sort a thrown error into what the flow can do about it. Duck-typed on
2645
+ * `status` / `code` / `ambiguous` / `details` (what `ApiError` carries);
2646
+ * branches on codes and statuses, never on message prose.
2647
+ */
2648
+ declare function classifyAddPharmacyError(err: unknown): AddPharmacyFailure;
2649
+ interface AddedPharmacy {
2650
+ productId: string;
2651
+ pharmacyName: string;
2652
+ /** `recovered`: the answer was lost, and a re-read of the product showed the pharmacy on it. */
2653
+ origin: 'saved' | 'recovered';
2654
+ /** What the server did; the screen never says which. */
2655
+ status: AddPharmacyResult['status'];
2656
+ }
2657
+ interface AddPharmacyNotice {
2658
+ tone: 'info' | 'warn' | 'danger';
2659
+ code: string;
2660
+ message: string;
2661
+ }
2662
+ type AddPharmacyState = {
2663
+ kind: 'idle';
2664
+ }
2665
+ /** Choosing a pharmacy drug. */
2666
+ | {
2667
+ kind: 'picking';
2668
+ } | {
2669
+ kind: 'planning';
2670
+ drugId: string;
2671
+ } | {
2672
+ kind: 'reviewing';
2673
+ plan: AddPharmacyPlan;
2674
+ }
2675
+ /** The save is running (about 40 seconds on a single-pharmacy product): no way to interrupt it. */
2676
+ | {
2677
+ kind: 'saving';
2678
+ plan: AddPharmacyPlan;
2679
+ } | {
2680
+ kind: 'done';
2681
+ added: AddedPharmacy;
2682
+ } | {
2683
+ kind: 'failed';
2684
+ message: string;
2685
+ drugId: string;
2686
+ plan: AddPharmacyPlan | null;
2687
+ /** The outcome of the save is not known: re-check the product, don't save again. */
2688
+ unconfirmed: boolean;
2689
+ /** A fresh plan could get a different answer. */
2690
+ canRetry: boolean;
2691
+ };
2692
+ interface UseAddPharmacyOptions {
2693
+ /** The product being edited. */
2694
+ productId: Accessor<string>;
2695
+ /** The pharmacy is on the product (the host reloads it and its lists). */
2696
+ onAdded?: (added: AddedPharmacy) => void;
2697
+ }
2698
+ interface AddPharmacy {
2699
+ state: Accessor<AddPharmacyState>;
2700
+ /** True while a request is in flight (planning or saving). */
2701
+ busy: Accessor<boolean>;
2702
+ notice: Accessor<AddPharmacyNotice | null>;
2703
+ dismissNotice: () => void;
2704
+ /** Every pharmacy drug this site may map; the host filters out pharmacies already on the product. */
2705
+ drugs: Accessor<CatalogMappableDrug[]>;
2706
+ drugsStatus: Accessor<'idle' | 'loading' | 'ready' | 'failed'>;
2707
+ selected: Accessor<string>;
2708
+ select: (drugId: string) => void;
2709
+ /** Start choosing, optionally with a drug already chosen (a suggestion). */
2710
+ open: (drugId?: string) => void;
2711
+ cancel: () => void;
2712
+ /** Back to choosing a different pharmacy. */
2713
+ backToPicking: () => void;
2714
+ /** Plan adding the selected drug. */
2715
+ plan: () => Promise<void>;
2716
+ prices: Accessor<Readonly<Record<string, string>>>;
2717
+ savingsPrices: Accessor<Readonly<Record<string, string>>>;
2718
+ setPrice: (doseId: string, value: string) => void;
2719
+ setSavingsPrice: (doseId: string, value: string) => void;
2720
+ /** Doses owed a price that has none yet. */
2721
+ missing: Accessor<string[]>;
2722
+ /** Doses the server said were missing a price when the last save was refused. */
2723
+ flagged: Accessor<ReadonlySet<string>>;
2724
+ /** A member price was typed that is not an amount. */
2725
+ savingsInvalid: Accessor<string[]>;
2726
+ canSave: Accessor<boolean>;
2727
+ /** The answers the admin has given to the plan's match questions. */
2728
+ matchAnswers: Accessor<MatchAnswers>;
2729
+ /** Answer a match question: a dose id, or null to leave those subscribers for review. Re-plans after a short pause. */
2730
+ setMatchAnswer: (source: AddPharmacyMatchSource, doseId: string | null) => void;
2731
+ /** The plan is being recomputed for a changed answer; saving waits. */
2732
+ replanning: Accessor<boolean>;
2733
+ save: () => Promise<void>;
2734
+ /** Plan again (after a refusal a new plan can change), or re-check the product when the save's outcome is unknown. */
2735
+ retry: () => Promise<void>;
2736
+ /** Discard what is on screen and plan the same pharmacy again from scratch. */
2737
+ startOver: () => Promise<void>;
2738
+ }
2739
+ declare function useAddPharmacy(opts: UseAddPharmacyOptions): AddPharmacy;
2740
+
2741
+ /**
2742
+ * Shared vocabulary for reading a subscription's status.
2743
+ *
2744
+ * Two DIFFERENT questions get asked about the same field, and conflating them
2745
+ * is how members get stuck:
2746
+ *
2747
+ * - **"Did my create land?"** (`isReconcilable`) — asked after an ambiguous
2748
+ * failure, when we need to know whether the server committed something. Any
2749
+ * non-terminal row counts, including the transient `pending` / `incomplete` /
2750
+ * `trialing` states a just-created subscription passes through, because
2751
+ * matching only `active` would report "nothing happened" and scare the member
2752
+ * into retrying a purchase that actually succeeded. Errs toward "it exists".
2753
+ *
2754
+ * - **"Is this member already subscribed?"** (`isLive`) — asked to BLOCK a new
2755
+ * subscribe on a single-subscription tenant. Must mirror the server's rule
2756
+ * exactly (`LIVE_SUBSCRIPTION_STATUSES` in the-backend's subscriptions route),
2757
+ * or the two disagree in the worst direction: an `incomplete` row from a
2758
+ * declined card would make this client refuse an intake the server would have
2759
+ * accepted, and the member could never subscribe at all. Errs toward "let them
2760
+ * through" — the server has the final say and cannot be bypassed.
2761
+ */
2762
+ /** Statuses that mean NO live subscription resulted — a terminal, dead record. */
2763
+ declare const TERMINAL_SUBSCRIPTION_STATUSES: ReadonlySet<string>;
2764
+ /**
2765
+ * Statuses the billing engine still acts on (or is waiting on the member to
2766
+ * make actable). Mirrors the-backend `LIVE_SUBSCRIPTION_STATUSES` — keep the two
2767
+ * lists in step.
2768
+ */
2769
+ declare const LIVE_SUBSCRIPTION_STATUSES: ReadonlySet<string>;
2770
+ /** True when this row proves a create committed (see the module docstring). */
2771
+ declare function isReconcilable(status: string | undefined | null): boolean;
2772
+ /** True when this row means the member currently HOLDS a subscription. */
2773
+ declare function isLive(status: string | undefined | null): boolean;
2774
+
2775
+ /** What the forwarder reads from the running survey to describe a page. */
2776
+ interface FunnelStepSource {
2777
+ flatSteps: () => FlatStep$1[];
2778
+ stepIndex: () => number;
2779
+ }
2780
+ interface FunnelTelemetry {
2781
+ /** Forward an engine event (no-op until config resolves; drops if disabled). */
2782
+ onEvent: (e: EmbedEvent) => void;
2783
+ /**
2784
+ * Give the forwarder the running survey, so page events can carry the page's
2785
+ * id and text. The flow is built after the forwarder (it takes onEvent), so
2786
+ * this is wired once it exists; events before then go out undescribed.
2787
+ */
2788
+ attach: (source: FunnelStepSource) => void;
2789
+ }
2790
+ /**
2791
+ * Create a telemetry forwarder. Events arriving before the tenant's funnel
2792
+ * config resolves are buffered (bounded) and flushed once it does; if the
2793
+ * tenant never enabled telemetry the buffer is discarded.
2794
+ */
2795
+ declare function createFunnelTelemetry(): FunnelTelemetry;
2796
+ /**
2797
+ * Post the pre-survey email gate's captured address into the session.
2798
+ * Rides the telemetry endpoint (email:captured), so it requires
2799
+ * features.funnelTelemetry on the backend as well as funnelEmailGate.
2800
+ */
2801
+ declare function captureFunnelEmail(email: string): void;
2802
+ /** True once the visitor has answered (or skipped) the email gate. */
2803
+ declare function emailGateAnswered(): boolean;
2804
+ declare function markEmailGateAnswered(): void;
2805
+ /**
2806
+ * Redeem the `?resume=` token in the URL — at most once per page load, no
2807
+ * matter how many callers ask.
2808
+ *
2809
+ * Two things need the answer and they run in the wrong order: the email gate
2810
+ * decides whether to render BEFORE the survey mounts, and the draft store only
2811
+ * loads once it has. Leaving the exchange inside the draft store meant the gate
2812
+ * couldn't see it, so a patient following a recovery email on a new device was
2813
+ * asked for the address we had already emailed — and, worse, answered it under
2814
+ * a freshly minted session id, forking their row and earning a second reminder
2815
+ * chain. Both now await this, so the session is adopted before anything can be
2816
+ * posted under the wrong one.
2817
+ *
2818
+ * Resolves null instantly when there is no token, so it is safe to call
2819
+ * unconditionally.
2820
+ */
2821
+ declare function redeemResumeLink(): Promise<ResumedDraft | null>;
2822
+ /** Test seam: forget the redemption so the next call re-reads the URL. */
2823
+ declare function resetResumeRedemption(): void;
2824
+
2825
+ interface CartCaptureOptions {
2826
+ /** Debounce for snapshot writes. Quantity steppers fire fast. */
2827
+ debounceMs?: number;
2828
+ /**
2829
+ * Address for an anonymous shopper, if the site collected one outside the
2830
+ * survey's email gate (e.g. checkout step 1). Logged-in shoppers need
2831
+ * nothing here — the backend reads their email off the token.
2832
+ */
2833
+ email?: () => string | null | undefined;
2834
+ /**
2835
+ * Where the basket lives, for a site that has no catalog cart.
2836
+ *
2837
+ * Abandonment is not a storefront-only event: a single-subscription partner
2838
+ * (mytruemeds, axiom-md) lets a patient choose a medication and a dose and
2839
+ * then walk away from the payment step, which is the same loss and the same
2840
+ * recoverable moment — but the selection lives in that site's own intake
2841
+ * state, not in `stores/cart`, so the default wiring watches an empty store
2842
+ * forever.
2843
+ *
2844
+ * Read and write are one option rather than two on purpose: a site that
2845
+ * supplies its own items must also say how a resumed cart gets back in, or
2846
+ * the `?cart=` link would rebuild into core's cart store, which such a site
2847
+ * never renders. Omit entirely to drive core's cart store (the default).
2848
+ */
2849
+ source?: CartSource;
2850
+ }
2851
+ /** A site's own basket, in the shape the wire already speaks. */
2852
+ interface CartSource {
2853
+ /** Current lines. Must be reactive — this is tracked. */
2854
+ items: () => CartSnapshotLine[];
2855
+ /** Promo code riding on the cart, if the site has one. */
2856
+ promoCode?: () => string | null | undefined;
2857
+ /**
2858
+ * Rebuild the site's own state from a cart resumed off a `?cart=` link. The
2859
+ * lines are re-priced against today's catalog; the promo code (if any) is
2860
+ * NOT re-validated for a custom source — `validateResumedPromo` does that
2861
+ * for a site that wants it.
2862
+ */
2863
+ restore: (cart: ResumedCart) => void;
2864
+ }
2865
+ interface ValidatedResumedPromo {
2866
+ code: string;
2867
+ discountType: 'percent' | 'fixed';
2868
+ discountValueCents: number;
2869
+ discountCents: number;
2870
+ }
2871
+ /**
2872
+ * Re-check the promo code a resumed cart was carrying, against today's rules
2873
+ * and today's lines. Null when there was no code, when it no longer validates,
2874
+ * or when the check itself fails — the cart is restored either way.
2875
+ *
2876
+ * Exported because a site with its own `CartSource` needs the same guarantee
2877
+ * without core's cart store: showing a discount checkout won't honor is worse
2878
+ * than showing none.
2879
+ */
2880
+ declare function validateResumedPromo(resumed: ResumedCart): Promise<ValidatedResumedPromo | null>;
2881
+ /**
2882
+ * Redeem a `?cart=` token if the URL carries one.
2883
+ *
2884
+ * Exported for sites that want to act on the restore — opening their cart
2885
+ * drawer on arrival, say, or waiting for their catalog first.
2886
+ *
2887
+ * Single-flight: `startCartCapture()` restores on its own, so a site calling
2888
+ * this directly would otherwise race it — both read the token before either
2889
+ * strips it, and the cart gets rebuilt twice. Concurrent callers share one
2890
+ * restore and one result.
2891
+ */
2892
+ declare function restoreCartFromLink(): Promise<ResumedCart | null>;
2893
+ /**
2894
+ * Start mirroring the cart. Call once at app boot; returns a disposer.
2895
+ *
2896
+ * No-ops for tenants that never opted in (`GET /config/cart`), so it is safe to
2897
+ * call unconditionally from shared site scaffolding.
2898
+ */
2899
+ declare function startCartCapture(opts?: CartCaptureOptions): () => void;
2900
+
2901
+ declare const PHONE_ERROR = "Enter a valid 10-digit US phone number.";
2902
+ declare function isValidUsPhone(raw: string): boolean;
2903
+ /**
2904
+ * "(512) 555-1234" for a US number (E.164 or as typed); anything else comes
2905
+ * back untouched. Display only — never send the result anywhere.
2906
+ */
2907
+ declare function formatUsPhone(raw: string): string;
2908
+
2909
+ type SmsNoticeKind = 'needs_consent' | 'stale_text' | 'no_phone' | 'unavailable';
2910
+ /** Something the member should be told that isn't an error: what just happened to their consent. */
2911
+ interface SmsNotice {
2912
+ kind: SmsNoticeKind;
2913
+ message: string;
2914
+ }
2915
+ interface SmsPreferencesFlow {
2916
+ /** True until the first load settles. */
2917
+ loading: Accessor<boolean>;
2918
+ /** The member's state, or null before it loads or when it could not be loaded. */
2919
+ state: Accessor<UserSmsState | null>;
2920
+ /** Render the section only when this is true — the tenant texts customers and the state loaded. */
2921
+ available: Accessor<boolean>;
2922
+ /** The member's number (E.164), or null when none is on file. */
2923
+ phone: Accessor<string | null>;
2924
+ consented: Accessor<boolean>;
2925
+ /** The member replied STOP. A carrier-level block: the site can't lift it, only explain it. */
2926
+ optedOutByStop: Accessor<boolean>;
2927
+ /** The number texts come from — what a STOP-ed member texts START to. */
2928
+ fromNumber: Accessor<string | undefined>;
2929
+ /** The events the tenant switched on, with this member's setting for each. */
2930
+ events: Accessor<UserSmsEvent[]>;
2931
+ /** Per-event switches apply only while the member is consented and hasn't STOP-ed. */
2932
+ showEvents: Accessor<boolean>;
2933
+ /**
2934
+ * The consent wording to show beside the "turn on" switch, or null when the
2935
+ * tenant's config is unavailable (then turning on is not offered at all).
2936
+ * Replaced with the new words after a stale-text refusal.
2937
+ */
2938
+ consentOffer: Accessor<SmsConsentOffer | null>;
2939
+ /** An action is in flight. */
2940
+ busy: Accessor<boolean>;
2941
+ error: Accessor<string | null>;
2942
+ notice: Accessor<SmsNotice | null>;
2943
+ reload: () => Promise<void>;
2944
+ /** Change the number. Ends consent for the old one, so the member is told to turn texts on again. */
2945
+ setPhone: (raw: string) => Promise<boolean>;
2946
+ /** Turn texts on, agreeing to `consentOffer()` as shown. */
2947
+ optIn: () => Promise<boolean>;
2948
+ optOut: () => Promise<boolean>;
2949
+ /** Switch ONE event; every other event is left exactly as it is. */
2950
+ setEvent: (key: string, enabled: boolean) => Promise<boolean>;
2951
+ }
2952
+ declare function useSmsPreferences(): SmsPreferencesFlow;
2953
+
2954
+ export { type FindingCopy as $, type AddressPair as A, type CatalogAvailabilityDecision as B, type CartCaptureOptions as C, type CatalogAvailabilityState as D, type CatalogConversion as E, type CatalogFailure as F, type CatalogFlow as G, type HostedCardField as H, type CategoryColorOpts as I, type CheckoutFlow as J, type CheckoutOutcome as K, type Conversation as L, type ConversionConverted as M, type ConversionFailure as N, type ConversionNotice as O, type ConversionState as P, type ConversionSummary as Q, type CreateCatalogProductOutcome as R, type SmsConsent as S, DEFAULT_COLOR_PALETTE as T, type DashboardActivityItem as U, type DashboardData as V, type DashboardRxListItem as W, type DashboardRxStatus as X, type DashboardSubscription as Y, type DroppedCartLine as Z, type DrugResult as _, type AccountSource as a, type SubscriptionIntakeOutcome as a$, type FlatStep as a0, type FulfillmentRow as a1, type FulfillmentStage as a2, type FunnelTelemetry as a3, type JourneyState as a4, type JourneyStep as a5, type JourneyStepKey as a6, LIFECYCLE_BUCKETS as a7, LIFECYCLE_LABEL as a8, LIFECYCLE_TONE as a9, type ReadinessStatus as aA, type ReconcileOptions as aB, type RefillEvent as aC, type RefillView as aD, type RegisterFlow as aE, type RegisterOutcome as aF, type RequestStatus as aG, type ResolvedStrength as aH, type RxRequestStatus as aI, SOURCE_FIELD_NOTE as aJ, type Severity as aK, type ShipmentInfo as aL, type SignupFlow as aM, type SignupOutcome as aN, type SmsConsentGrant as aO, type SmsConsentOffer as aP, type SmsNotice as aQ, type SmsNoticeKind as aR, type SmsPreferencesFlow as aS, type StageState as aT, type StoredDosePrice as aU, type StrengthComparison as aV, type StrengthRow as aW, type StructureState as aX, type SubscribeFlow as aY, type SubscribeOutcome as aZ, type SubscriptionIntakeFlow as a_, LIVE_SUBSCRIPTION_STATUSES as aa, MATCH_DEPENDENT_WARNINGS as ab, MATCH_HOW_LABEL as ac, type MatchChoice as ad, type MatchProblem as ae, type MatchRecord as af, type MatchRow as ag, type MatrixView as ah, type MedicationPricing as ai, type MedicationSelectFlow as aj, type MemberPortalData as ak, type MemberPortalRx as al, type MemberPortalSubscription as am, type MessagesChannel as an, type MessagesIntent as ao, type MessagesThread as ap, type NewCatalogProductInput as aq, OFFER_BEATS_PROMO_NOTICE as ar, ORPHAN_REASON as as, type OfferDiscount as at, PHONE_ERROR as au, type PricingBreakdown as av, type ProductCatalogEditor as aw, type ProductDetailFlow as ax, type PromoPricing as ay, READINESS_LABEL as az, type AddPharmacy as b, explainFinding as b$, type SurveyFlow as b0, type SurveyOption as b1, type SurveyOutcome as b2, type SurveyQuestion as b3, type SurveyResult as b4, TERMINAL_SUBSCRIPTION_STATUSES as b5, type ThreadMessage as b6, type TimelineEvent as b7, type TimelineKind as b8, type Tone as b9, availableStateOptions as bA, availableStates as bB, bestOfferDiscount as bC, buildFulfillmentRows as bD, buildMatrixView as bE, buildRefillView as bF, buildSaveBody as bG, buildStrengthRows as bH, buildTimeline as bI, buildTrackerView as bJ, buildTrackingUrl as bK, canLeaveUnmatched as bL, canOfferConversion as bM, captureFunnelEmail as bN, catalogUnavailableMessage as bO, categoryColor as bP, classifyAddPharmacyError as bQ, classifyCatalogError as bR, classifyConversionError as bS, compareStrengths as bT, createCatalogProduct as bU, createFunnelTelemetry as bV, deriveAttention as bW, deriveCatalogAvailabilityDecision as bX, deriveJourney as bY, describeConversion as bZ, emailGateAnswered as b_, type TrackerRequest as ba, type TrackerRequestStatus as bb, type TrackerSubscription as bc, type TrackerSubscriptionStatus as bd, type TrackerView as be, type TrackingUrlCarrier as bf, US_STATES as bg, US_STATE_OPTIONS as bh, type UpdatePaymentMethodFlow as bi, type UseAddPharmacyOptions as bj, type UseAddressPairOptions as bk, type UseCatalogConversionOptions as bl, type UseCheckoutFlowOptions as bm, type UseMedicationSelectOptions as bn, type UseMessagesThreadOptions as bo, type UseProductCatalogEditorOptions as bp, type UseSignupFlowOptions as bq, type UseSubscribeFlowOptions as br, type UseSubscriptionIntakeFlowOptions as bs, type UseSurveyFlowOptions as bt, type ValidateAddressOptions as bu, type ValidatedResumedPromo as bv, type VisibilityCondition as bw, accountSource as bx, addCatalogItemAsProduct as by, applyPriceDrafts as bz, type AddPharmacyFailure as c, useAffiliateDownline as c$, findStoredDosePrice as c0, flaggedSubscribers as c1, formatCardNumber as c2, formatConversationTime as c3, formatCvv as c4, formatEventDate as c5, formatExpiry as c6, formatMessageTime as c7, formatRelativeTime as c8, formatStageDate as c9, offerSummaryText as cA, parseMoney as cB, pharmacyIsOnProduct as cC, pharmacyLabel as cD, primarySubscription as cE, readinessStatus as cF, reconcileCartAgainstCatalog as cG, reconcileCartLines as cH, redeemResumeLink as cI, removeStoredDosePrice as cJ, resetResumeRedemption as cK, resolveCategoryColor as cL, resolveStrengthPrices as cM, restoreCartFromLink as cN, salePriceForBase as cO, skuBindingModeFor as cP, sourceKey as cQ, sourceLabel as cR, startCartCapture as cS, stateAvailabilityNote as cT, strengthsChanged as cU, toChoices as cV, toTrackerRequest as cW, upsertDosePrice as cX, useAddPharmacy as cY, useAddressPair as cZ, useAffiliateConversions as c_, formatUsPhone as ca, groupDrugsByPharmacy as cb, hasBlockers as cc, hasConversion as cd, hasErrors as ce, initialMatches as cf, isCatalogItemId as cg, isCssColorValue as ch, isLive as ci, isQuestionVisible as cj, isReconcilable as ck, isValidUsPhone as cl, lifecycleReason as cm, liveDoses as cn, lowestPrice as co, lowestSalePrice as cp, markEmailGateAnswered as cq, matchProblem as cr, matchesComplete as cs, missingPrices as ct, moveInOrder as cu, needsReview as cv, normalizeState as cw, normalizeStates as cx, offerBeatsPromo as cy, offerDurationText as cz, type AddPharmacyNotice as d, useAffiliateLinks as d0, useAffiliateStats as d1, useCartCheckoutFlow as d2, useCartReconcile as d3, useCatalog as d4, useCatalogAvailability as d5, useCatalogConversion as d6, useCheckoutFlow as d7, useDashboardData as d8, useMedicationSelect as d9, useMemberPortalData as da, useMessagesThread as db, useProductCatalogEditor as dc, useProductDetail as dd, useRegisterFlow as de, useSignupFlow as df, useSmsConsent as dg, useSmsPreferences as dh, useSubscribeFlow as di, useSubscriptionIntakeFlow as dj, useSurveyFlow as dk, useUpdatePaymentMethodFlow as dl, validateAddress as dm, validateResumedPromo as dn, visibleWarnings as dp, type AddPharmacyState as e, type AddStrengthInput as f, type AddStrengthOutcome as g, type AddedPharmacy as h, type AddressErrors as i, type AddressValue as j, type AffiliateConversionsFlow as k, type AffiliateDownlineFlow as l, type AffiliateLinksFlow as m, type AffiliateStatsFlow as n, type AnswerValue as o, type ApexBlockCode as p, type AttentionAction as q, type AttentionActionKind as r, type AttentionItem as s, type CartCheckoutFlow as t, type CartCheckoutOutcome as u, type CartCheckoutPricing as v, type CartDropReason as w, type CartReconcileState as x, type CartReconciliation as y, type CartSource as z };