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