@apextelemed/partner-core 0.2.0 → 0.3.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.
- package/dist/api/index.d.ts +14 -1
- package/dist/api/index.js +2 -2
- package/dist/api/index.jsx +8 -2
- package/dist/chunk/{SNAV6DII.jsx → 2EVGOW2Z.jsx} +26 -4
- package/dist/chunk/{KFJXIKD4.js → 5RQ4ZIYB.js} +48 -9
- package/dist/chunk/5RQ4ZIYB.js.map +1 -0
- package/dist/chunk/{FJZHH5T4.jsx → AC7FFU4J.jsx} +312 -6
- package/dist/chunk/ACE7M2YA.jsx +1 -0
- package/dist/chunk/{EIXV4DCU.js → D6GCJFQD.js} +26 -6
- package/dist/chunk/D6GCJFQD.js.map +1 -0
- package/dist/chunk/{OEXSGX5F.js → J4G52ET6.js} +665 -337
- package/dist/chunk/J4G52ET6.js.map +1 -0
- package/dist/chunk/JSHO46VZ.js +3 -0
- package/dist/chunk/JSHO46VZ.js.map +1 -0
- package/dist/chunk/{MEWFN6IW.jsx → M6DZVPYZ.jsx} +49 -8
- package/dist/chunk/{6TFBQECC.jsx → NP4CMOLW.jsx} +41 -1
- package/dist/chunk/{J6KNY37T.js → XMYPS7PT.js} +40 -3
- package/dist/chunk/XMYPS7PT.js.map +1 -0
- package/dist/flows/index.js +3 -3
- package/dist/flows/index.jsx +3 -3
- package/dist/index/index.d.ts +1 -1
- package/dist/index/index.js +5 -5
- package/dist/index/index.jsx +11 -5
- package/dist/pages/index.js +2 -2
- package/dist/pages/index.jsx +2 -2
- package/dist/testing/storage.d.ts +1 -1
- package/dist/testing/storage.d.ts.map +1 -1
- package/dist/testing/storage.js +1 -0
- package/dist/testing/storage.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk/AN3WPMEP.js +0 -3
- package/dist/chunk/AN3WPMEP.js.map +0 -1
- package/dist/chunk/EIXV4DCU.js.map +0 -1
- package/dist/chunk/J6KNY37T.js.map +0 -1
- package/dist/chunk/KFJXIKD4.js.map +0 -1
- package/dist/chunk/O3QK7YZR.jsx +0 -1
- package/dist/chunk/OEXSGX5F.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/flows/products.ts","../../src/flows/categoryVisual.ts","../../src/flows/subscriptionIntake.ts","../../src/flows/cartCapture.ts"],"names":["createSignal","createEffect"],"mappings":";;;;;;;AAWO,SAAS,cAAA,CAAe,SAAyB,MAAA,EAA+B;AACrF,EAAA,MAAM,OAAA,GAAA,CAAW,OAAA,CAAQ,aAAA,IAAiB,EAAC,EAAG,KAAK,CAAC,CAAA,KAAM,CAAA,CAAE,MAAA,KAAW,MAAM,CAAA;AAC7E,EAAA,IAAI,OAAA,IAAW,OAAA,CAAQ,KAAA,IAAS,IAAA,SAAa,OAAA,CAAQ,KAAA;AACrD,EAAA,OAAO,OAAA,CAAQ,KAAA;AACjB;AAIO,SAAS,YAAY,OAAA,EAAwC;AAClE,EAAA,MAAM,SAAA,GAAY,OAAA,CAAQ,iBAAA,IAAqB,EAAC;AAChD,EAAA,IAAI,SAAA,CAAU,MAAA,KAAW,CAAA,EAAG,OAAO,OAAA,CAAQ,KAAA;AAC3C,EAAA,IAAI,GAAA,GAAqB,IAAA;AACzB,EAAA,KAAA,MAAW,QAAQ,SAAA,EAAW;AAC5B,IAAA,MAAM,CAAA,GAAI,cAAA,CAAe,OAAA,EAAS,IAAI,CAAA;AACtC,IAAA,IAAI,KAAK,IAAA,KAAS,GAAA,IAAO,IAAA,IAAQ,CAAA,GAAI,MAAM,GAAA,GAAM,CAAA;AAAA,EACnD;AACA,EAAA,OAAO,OAAO,OAAA,CAAQ,KAAA;AACxB;AASO,SAAS,eAAA,CAAgB,SAAyB,SAAA,EAAyC;AAChG,EAAA,IAAI,SAAA,IAAa,IAAA,IAAQ,CAAC,OAAA,CAAQ,YAAY,OAAO,IAAA;AACrD,EAAA,MAAM,OAAO,OAAA,CAAQ,UAAA;AACrB,EAAA,MAAM,SAAA,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AAA;AAAA,IACnD;AACA,IAAA,OAAA,EAAQ;AACR,IAAA,OAAA,GAAU,KAAA;AAAA,EACZ,CAAA;AACF","file":"EIXV4DCU.js","sourcesContent":["import { createMemo, createResource, createSignal, type Accessor, type Resource } from 'solid-js';\nimport { productsApi, type CatalogProduct } from '../api/client';\nimport cartStore from '../stores/cart';\nimport medicationStore from '../stores/medication';\n\nexport type { CatalogProduct } from '../api/client';\n\n// ── Pricing helpers (pure) ──────────────────────────────────────────\n\n/** Effective price for a single dose: the overlay price if present, else the\n * product's base price (null when neither is set — dose not purchasable). */\nexport function priceForDosage(product: CatalogProduct, dosage: string): number | null {\n const overlay = (product.dosage_prices ?? []).find((d) => d.dosage === dosage);\n if (overlay && overlay.price != null) return overlay.price;\n return product.price;\n}\n\n/** Lowest price across the product's available doses (overlay-or-base each),\n * falling back to the product-level price. Returns null for free / unpriced products. */\nexport function lowestPrice(product: CatalogProduct): number | null {\n const available = product.available_dosages ?? [];\n if (available.length === 0) return product.price;\n let min: number | null = null;\n for (const dose of available) {\n const p = priceForDosage(product, dose);\n if (p != null && (min == null || p < min)) min = p;\n }\n return min ?? product.price;\n}\n\n/**\n * Lowest sale price for a tiered product, computed by re-deriving the same\n * percent/fixed discount the backend applied at the product level. Used so\n * the strikethrough lands on the displayed (lowest-tier) value.\n *\n * Returns null when no active sale, no discount, or insufficient data.\n */\nexport function lowestSalePrice(product: CatalogProduct, basePrice: number | null): number | null {\n if (basePrice == null || !product.activeSale) return null;\n const sale = product.activeSale;\n const baseCents = Math.round(basePrice * 100);\n if (sale.discountCents <= 0) return null;\n if (\n product.salePriceCents != null &&\n product.price != null &&\n Math.abs(product.price - basePrice) < 0.001\n ) {\n return product.salePriceCents / 100;\n }\n if (product.price != null && product.salePriceCents != null && product.price > 0) {\n const ratio = product.salePriceCents / Math.round(product.price * 100);\n return Math.max(0, basePrice * ratio);\n }\n return Math.max(0, (baseCents - sale.discountCents) / 100);\n}\n\n// ── useCatalog ──────────────────────────────────────────────────────\n\nexport interface CatalogFlow {\n products: Resource<CatalogProduct[]>;\n /** Products in the \"weight-loss\" category. */\n weightLoss: Accessor<CatalogProduct[]>;\n /** Products NOT in \"weight-loss\" (peptides, recovery, etc). */\n peptides: Accessor<CatalogProduct[]>;\n /** Filter products by an arbitrary category slug. */\n filterByCategory: (slug: string) => CatalogProduct[];\n}\n\n/** Fetches the product catalog and exposes a couple of common derivations. */\nexport function useCatalog(): CatalogFlow {\n const [products] = createResource<CatalogProduct[]>(async () => {\n try {\n const res = await productsApi.list();\n return res.products;\n } catch {\n return [];\n }\n });\n\n const weightLoss = () =>\n (products() ?? []).filter((p) => (p.categories ?? []).includes('weight-loss'));\n const peptides = () =>\n (products() ?? []).filter((p) => !(p.categories ?? []).includes('weight-loss'));\n const filterByCategory = (slug: string) =>\n (products() ?? []).filter((p) => (p.categories ?? []).includes(slug));\n\n return { products, weightLoss, peptides, filterByCategory };\n}\n\n// ── useProductDetail ────────────────────────────────────────────────\n\nexport interface ProductDetailFlow {\n product: Resource<CatalogProduct | null>;\n dosageOptions: Accessor<Array<{ dosage: string; price: number; savingsPrice: number | null }>>;\n selectedDosage: Accessor<string>;\n setSelectedDosage: (v: string) => void;\n /** Effective base price for the currently-selected dosage. */\n selectedPrice: Accessor<number | null>;\n /** Sale price for the selected dosage, if a sale is active. */\n selectedSalePrice: Accessor<number | null>;\n /** 'per_dose' (default) or 'flat_fee'. When 'flat_fee', `dosageOptions` is\n * collapsed to a single entry and consumer UI should hide the dose picker. */\n pricingMode: Accessor<'per_dose' | 'flat_fee'>;\n /** True if the product+dosage combination is already in cart. */\n inCart: Accessor<boolean>;\n addToCart: () => void;\n}\n\n/**\n * Single-product page state. Loads the catalog and finds the product by id.\n * Tracks dosage selection, derives current/sale price, exposes addToCart.\n */\nexport function useProductDetail(productId: Accessor<string>): ProductDetailFlow {\n const [product] = createResource<CatalogProduct | null, string>(productId, async (id) => {\n if (!id) return null;\n try {\n const res = await productsApi.list();\n return res.products.find((p) => p.id === id) ?? null;\n } catch {\n return null;\n }\n });\n\n const pricingMode = createMemo<'per_dose' | 'flat_fee'>(\n () => product()?.pricing_mode ?? 'per_dose',\n );\n\n const dosageOptions = createMemo(() => {\n const p = product();\n if (!p) return [];\n // Doses come from the linked Apex drug (available_dosages); dosage_prices is\n // only a price overlay. A dose with no resolvable price (no overlay + no\n // base price) is dropped — it isn't purchasable.\n const all = (p.available_dosages ?? [])\n .map((dosage) => {\n const overlay = (p.dosage_prices ?? []).find((d) => d.dosage === dosage);\n const price = overlay && overlay.price != null ? overlay.price : p.price;\n return { dosage, price, savingsPrice: overlay?.savingsPrice ?? null };\n })\n .filter((o): o is { dosage: string; price: number; savingsPrice: number | null } => o.price != null);\n if (pricingMode() !== 'flat_fee' || all.length === 0) return all;\n // flat_fee: collapse to a single entry — prefer dosage_override, else first.\n const override = p.dosage_override;\n const chosen = (override && all.find((d) => d.dosage === override)) || all[0];\n return [chosen];\n });\n const [selectedDosage, setSelectedDosage] = createSignal<string>('');\n\n // Auto-select the first dosage once options arrive\n createMemo(() => {\n const opts = dosageOptions();\n if (opts.length > 0 && !selectedDosage()) setSelectedDosage(opts[0].dosage);\n });\n\n const selectedPrice = createMemo<number | null>(() => {\n const opts = dosageOptions();\n const chosen = opts.find((d) => d.dosage === selectedDosage());\n if (chosen) return chosen.price;\n return product()?.price ?? null;\n });\n\n const selectedSalePrice = createMemo<number | null>(() => {\n const p = product();\n const base = selectedPrice();\n if (!p || base == null || !p.activeSale) return null;\n if (p.salePriceCents != null && p.price != null && p.price > 0) {\n const ratio = p.salePriceCents / Math.round(p.price * 100);\n return Math.max(0, base * ratio);\n }\n return Math.max(0, base - p.activeSale.discountCents / 100);\n });\n\n const inCart = createMemo(() => {\n const p = product();\n if (!p) return false;\n const dosage = selectedDosage() || (dosageOptions()[0]?.dosage ?? '');\n const key = cartStore.itemKey(p.id, dosage);\n return cartStore.items().some((i) => cartStore.itemKey(i.productId, i.dosage) === key);\n });\n\n function addToCart() {\n const p = product();\n if (!p) return;\n const dosage = selectedDosage() || (dosageOptions()[0]?.dosage ?? '');\n const effective = selectedSalePrice() ?? selectedPrice() ?? 0;\n const priceCents = Math.round(effective * 100);\n cartStore.add({\n productId: p.id,\n productName: p.name,\n dosage,\n quantity: 1,\n priceCents,\n drugId: p.id,\n apexDrugId: p.apex_drug_id ?? null,\n categories: p.categories ?? [],\n thumbnailUrl: p.thumbnail_url ?? undefined,\n hideDoseLabel: pricingMode() === 'flat_fee' ? true : undefined,\n isSubscription: p.is_subscription ? true : undefined,\n });\n cartStore.open();\n }\n\n return {\n product,\n dosageOptions,\n selectedDosage,\n setSelectedDosage,\n selectedPrice,\n selectedSalePrice,\n pricingMode,\n inCart,\n addToCart,\n };\n}\n\n// ── useMedicationSelect ─────────────────────────────────────────────\n\nexport interface MedicationSelectFlow {\n products: Resource<CatalogProduct[]>;\n weightLoss: Accessor<CatalogProduct[]>;\n peptides: Accessor<CatalogProduct[]>;\n /** Pick a specific product as the patient's selected medication and proceed. The site fires the navigation in the optional `onSelected` callback. */\n selectMedication: (product: CatalogProduct) => void;\n /** Pick \"general consultation\" — a null drugId, indicating no pre-selected drug. */\n selectGeneralConsultation: () => void;\n}\n\nexport interface UseMedicationSelectOptions {\n /** Called after a selection is made. Sites typically navigate to their survey route. */\n onSelected?: () => void;\n /** Override the label used for the general-consultation selection. Default \"General Consultation\". */\n generalConsultationLabel?: string;\n}\n\n/**\n * Catalog browse + select-for-survey. The selection is written to\n * medicationStore (legacy single-item flow); the site navigates afterward\n * via the onSelected callback.\n */\nexport function useMedicationSelect(\n options: UseMedicationSelectOptions = {},\n): MedicationSelectFlow {\n const catalog = useCatalog();\n\n function selectMedication(product: CatalogProduct) {\n medicationStore.select({ drugId: product.id, drugName: product.name });\n options.onSelected?.();\n }\n\n function selectGeneralConsultation() {\n medicationStore.select({\n drugId: null,\n drugName: options.generalConsultationLabel ?? 'General Consultation',\n });\n options.onSelected?.();\n }\n\n return {\n products: catalog.products,\n weightLoss: catalog.weightLoss,\n peptides: catalog.peptides,\n selectMedication,\n selectGeneralConsultation,\n };\n}\n","/**\n * Deterministic procedural color for product categories.\n *\n * Sites want a stable color per category id without curating maps. The hash\n * is stable across reloads, so the same id always picks the same slot. Sites\n * override the palette to brand-align — default palette works out of the box.\n */\n\nfunction hashId(id: string): number {\n let h = 5381;\n for (let i = 0; i < id.length; i++) h = ((h << 5) + h + id.charCodeAt(i)) | 0;\n return Math.abs(h);\n}\n\n/** Default palette. Reads on light or dark; sites that want brand alignment\n * pass their own array (e.g. CSS var refs). */\nexport const DEFAULT_COLOR_PALETTE: readonly string[] = [\n '#4f46e5', // indigo\n '#0891b2', // cyan\n '#0d9488', // teal\n '#f59e0b', // amber\n '#e11d48', // rose\n '#10b981', // emerald\n '#8b5cf6', // violet\n '#f97316', // orange\n];\n\nexport interface CategoryColorOpts {\n palette?: readonly string[];\n}\n\nexport function categoryColor(id: string, opts: CategoryColorOpts = {}): string {\n const palette = opts.palette ?? DEFAULT_COLOR_PALETTE;\n if (palette.length === 0) return 'currentColor';\n return palette[hashId(id) % palette.length];\n}\n","import { createEffect, createSignal, onMount, type Accessor } from 'solid-js';\nimport {\n promoCodesApi,\n subscriptionsApi,\n usersApi,\n newIdempotencyKey,\n ApiError,\n type PromoValidationResponse,\n type ApiResponse,\n} from '../api/client';\nimport authStore from '../stores/auth';\nimport { useCardTokenizer } from './_internal/cardTokenizer';\nimport { formatCardNumber, formatExpiry, formatCvv } from './checkout';\nimport { getConfig } from '../config';\nimport { useAddressPair, validateAddress, firstAddressError, type AddressPair } from './address';\nimport { isLive } from './subscriptionStatus';\n\n// ── Draft persistence ───────────────────────────────────────────────\n\nconst DRAFT_TTL_MS = 7 * 24 * 3600 * 1000;\nconst MAX_RESTORABLE_STEP = 1; // Account + Address only; never restore into Payment\n\ninterface IntakeDraft {\n step?: number;\n firstName?: string;\n lastName?: string;\n dateOfBirth?: string;\n email?: string;\n phone?: string;\n street?: string;\n city?: string;\n state?: string;\n zip?: string;\n /** Idempotency key for THIS draft's create/signup attempt. Persisted so a\n * refresh mid-submit retries with the SAME key and the backend dedupes\n * instead of double-charging; rotated after a definitive rejection. */\n idempotencyKey?: string;\n savedAt?: number;\n}\n\nfunction draftKey(): string {\n return `${getConfig().storagePrefix}-subscription-intake-draft`;\n}\n\nfunction loadDraft(): IntakeDraft {\n try {\n const raw = localStorage.getItem(draftKey());\n if (!raw) return {};\n const parsed = JSON.parse(raw) as IntakeDraft;\n if (parsed.savedAt && Date.now() - parsed.savedAt > DRAFT_TTL_MS) {\n localStorage.removeItem(draftKey());\n return {};\n }\n return parsed ?? {};\n } catch {\n return {};\n }\n}\n\nfunction saveDraft(draft: IntakeDraft) {\n try {\n localStorage.setItem(draftKey(), JSON.stringify({ ...draft, savedAt: Date.now() }));\n } catch {\n // noop\n }\n}\n\nfunction clearDraft() {\n try {\n localStorage.removeItem(draftKey());\n } catch {\n // noop\n }\n}\n\n// ── Types ───────────────────────────────────────────────────────────\n\nexport interface SurveyResult {\n surveyResponseId: string;\n /**\n * v2 survey response id. When set, the Rx is linked to the Apex survey\n * snapshot and Apex generates the prescriber case notes from it (no local\n * caseNotes synthesis). Leave unset for the legacy v1 flow.\n */\n v2SurveyResponseId?: string;\n caseNotes?: string;\n drugId: string;\n drugName: string;\n dosage: string;\n}\n\nexport interface MedicationPricing {\n productId: string;\n productName: string;\n priceCents: number;\n savingsPriceCents?: number | null;\n}\n\nexport type SubscriptionIntakeOutcome =\n | { kind: 'in_progress' }\n | { kind: 'tokenizing' }\n | { kind: 'submitting' }\n /**\n * The member already holds a live subscription, so this intake must not create\n * a second one. Emitted ONLY under `singleSubscription` — without that option\n * the flow behaves exactly as before, so existing consumers that switch on\n * 'completed' alone are unaffected.\n *\n * Deliberately NOT 'completed': that kind means *this* purchase succeeded, and\n * hosts navigate onward celebrating it. This one means the member arrived\n * already subscribed and needs telling, not congratulating.\n */\n | { kind: 'already_subscribed'; productId?: string }\n | { kind: 'completed' };\n\nexport interface UseSubscriptionIntakeFlowOptions {\n surveyResult: SurveyResult;\n pricing: MedicationPricing;\n intervalDays?: number;\n /**\n * Whether the member is enrolled in the savings program — read reactively, so\n * a verification that completes mid-intake re-quotes. When true and the\n * product defines `savingsPriceCents`, that rate is quoted instead of list.\n *\n * Must track the same member the SERVER will resolve at charge time (the\n * persisted savings link), or the quote and the charge disagree.\n */\n isSavingsMember?: () => boolean;\n /**\n * Single-subscription tenants: the site sells ONE subscription program, so a\n * member may hold at most one live subscription — of ANY product.\n *\n * Widens the mount reconcile below from \"already subscribed to THIS product\"\n * to \"already subscribed to anything\", and turns the server's\n * `SUBSCRIPTION_EXISTS` rejection into an `already_subscribed` outcome instead\n * of a raw error banner. Mirrors `features.singleSubscription` on the tenant;\n * setting it here without the tenant flag still guards the common paths, but\n * the server is what actually enforces it.\n */\n singleSubscription?: boolean;\n}\n\nexport interface PromoPricing {\n baseCents: number;\n discountCents: number;\n finalCents: number;\n promoCode?: string;\n}\n\nexport interface SubscriptionIntakeFlow {\n // Step 0 = Account, 1 = Address, 2 = Payment\n step: Accessor<number>;\n stepCount: 3;\n next: () => Promise<void>;\n back: () => void;\n\n outcome: Accessor<SubscriptionIntakeOutcome>;\n error: Accessor<string | null>;\n submitting: Accessor<boolean>;\n tokenizing: Accessor<boolean>;\n /** True once the card tokenizer is ready (config loaded; for AuthNet, Accept.js loaded too). Gate submission on this. */\n tokenizerReady: Accessor<boolean>;\n /** @deprecated alias of tokenizerReady (pre-rename name). */\n acceptJsReady: Accessor<boolean>;\n /** Non-null when payment setup failed to initialize — render as a banner. */\n /** Tokenizer init failure, or null. */\n tokenizerError: Accessor<string | null>;\n /** @deprecated alias of tokenizerError (pre-rename name). */\n acceptJsError: Accessor<string | null>;\n\n // Step 0 — Account\n firstName: Accessor<string>; setFirstName: (v: string) => void;\n lastName: Accessor<string>; setLastName: (v: string) => void;\n email: Accessor<string>; setEmail: (v: string) => void;\n password: Accessor<string>; setPassword: (v: string) => void;\n dateOfBirth: Accessor<string>; setDateOfBirth: (v: string) => void;\n phone: Accessor<string>; setPhone: (v: string) => void;\n\n // Step 1 — Address (delivery + billing override; see AddressPair).\n // `address.billingSameAsShipping` is this flow's \"billing same as delivery\".\n address: AddressPair;\n\n // Step 2 — Payment\n cardNumber: Accessor<string>; setCardNumber: (v: string) => void;\n expiry: Accessor<string>; setExpiry: (v: string) => void;\n cvv: Accessor<string>; setCvv: (v: string) => void;\n\n // Promo\n promoCode: Accessor<string>; setPromoCode: (v: string) => void;\n promoValidating: Accessor<boolean>;\n promoError: Accessor<string | null>;\n promoApplied: Accessor<PromoValidationResponse | null>;\n applyPromo: () => Promise<void>;\n clearPromo: () => void;\n\n // Pricing (reflects applied promo)\n pricing: Accessor<PromoPricing>;\n\n // Context (read-only, from options)\n surveyResult: SurveyResult;\n medication: MedicationPricing;\n\n submit: () => Promise<void>;\n}\n\n// ── Hook ────────────────────────────────────────────────────────────\n\nexport function useSubscriptionIntakeFlow(\n options: UseSubscriptionIntakeFlowOptions,\n): SubscriptionIntakeFlow {\n const accept = useCardTokenizer();\n\n let restored: IntakeDraft = {};\n if (typeof window !== 'undefined') restored = loadDraft();\n\n const [step, setStep] = createSignal(Math.min(restored.step ?? 0, MAX_RESTORABLE_STEP));\n const [error, setError] = createSignal<string | null>(null);\n const [tokenizing, setTokenizing] = createSignal(false);\n const [submitting, setSubmitting] = createSignal(false);\n const [outcome, setOutcome] = createSignal<SubscriptionIntakeOutcome>({ kind: 'in_progress' });\n\n // Account\n const [firstName, setFirstName] = createSignal(restored.firstName ?? '');\n const [lastName, setLastName] = createSignal(restored.lastName ?? '');\n const [email, setEmail] = createSignal(restored.email ?? '');\n const [password, setPassword] = createSignal('');\n const [dateOfBirth, setDateOfBirth] = createSignal(restored.dateOfBirth ?? '');\n const [phone, setPhone] = createSignal(restored.phone ?? '');\n\n // Address (delivery/shipping + billing override), backed by the shared\n // useAddressPair so validation and the same-as / copy-on-uncheck behavior\n // match the checkout flow. The individual accessors below keep this flow's\n // public interface stable for consuming storefronts (no breaking change).\n const addr = useAddressPair({\n initialShipping: {\n street: restored.street ?? '',\n city: restored.city ?? '',\n state: restored.state ?? '',\n zip: restored.zip ?? '',\n },\n });\n\n // Internal shipping getters for draft persistence + payload building; the full\n // read/write surface (incl. billing override) is exposed as `address` below.\n const street = () => addr.shipping().street;\n const city = () => addr.shipping().city;\n const state = () => addr.shipping().state;\n const zip = () => addr.shipping().zip;\n\n // Effective billing address sent as the charge's billTo.\n const effectiveBillingAddress = () => {\n const b = addr.effectiveBilling();\n return { street: b.street.trim(), city: b.city.trim(), state: b.state, zip: b.zip.trim() };\n };\n\n // Payment\n const [cardNumberRaw, setCardNumberRaw] = createSignal('', { equals: false });\n const [expiryRaw, setExpiryRaw] = createSignal('', { equals: false });\n const [cvvRaw, setCvvRaw] = createSignal('', { equals: false });\n\n // Promo\n const [promoCode, setPromoCode] = createSignal('');\n const [promoValidating, setPromoValidating] = createSignal(false);\n const [promoError, setPromoError] = createSignal<string | null>(null);\n const [promoApplied, setPromoApplied] = createSignal<PromoValidationResponse | null>(null);\n\n // Idempotency key for the create/signup POST — restored with the draft so a\n // retry after a refresh presents the same key (see IntakeDraft.idempotencyKey).\n const [idemKey, setIdemKey] = createSignal(restored.idempotencyKey ?? '');\n\n // ── Auto-save draft ─────────────────────────────────────────────\n\n onMount(() => {\n createEffect(() => {\n saveDraft({\n step: step(),\n firstName: firstName(),\n lastName: lastName(),\n dateOfBirth: dateOfBirth(),\n email: email(),\n phone: phone(),\n street: street(),\n city: city(),\n state: state(),\n zip: zip(),\n idempotencyKey: idemKey() || undefined,\n });\n });\n });\n\n // ── Mount reconcile (authenticated re-subscribe path) ───────────\n //\n // The restored draft re-arms submit with no memory of a create that already\n // committed: if the subscription landed server-side but this client never saw\n // the response (refresh mid-submit, dropped connection), the user is invited\n // to subscribe — and be charged — again. Ask the server before offering the\n // form.\n //\n // Scope depends on the tenant's model:\n // default → THIS product only. A subscription to a different\n // medication is a legitimate separate purchase and\n // must not block this intake.\n // singleSubscription → any live subscription. The program IS the\n // subscription, so a second one of any product is a\n // double charge, not a second purchase.\n //\n // The unauthenticated path needs no reconcile (a committed signup makes the\n // email taken, so a re-submit fails instead of double-charging). Fails open —\n // the server refuses the duplicate regardless, and blocking a real intake on a\n // lookup blip costs a customer.\n onMount(async () => {\n if (!authStore.isAuthenticated()) return;\n try {\n const res = (await subscriptionsApi.list()) as {\n subscriptions?: Array<{ productId?: string; status?: string }>;\n } | null;\n const existing = res?.subscriptions?.find(\n (s) =>\n isLive(s.status) &&\n (options.singleSubscription || s.productId === options.pricing.productId),\n );\n if (existing) {\n clearDraft();\n // Same-product is the ambiguous-retry case this reconcile was built for:\n // the purchase this very flow was configured for already exists, so the\n // member is done. A DIFFERENT product means they came back to buy\n // something they can't have alongside what they hold — a distinct\n // outcome, and only reachable under singleSubscription.\n setOutcome(\n existing.productId === options.pricing.productId\n ? { kind: 'completed' }\n : { kind: 'already_subscribed', productId: existing.productId },\n );\n }\n } catch {\n // Reconcile is a guard, not a gate — never block intake on a lookup blip.\n }\n });\n\n // ── Pricing ─────────────────────────────────────────────────────\n\n /**\n * The base price to quote: the product's savings rate for an enrolled member,\n * otherwise list.\n *\n * `savingsPriceCents` was carried on MedicationPricing but never actually\n * read, so enrolled members were quoted (and charged) list price. This mirrors\n * the SERVER rule exactly — `resolveProductPricing` in the-backend keys off\n * the member's savings link and treats a null savings price as \"no savings\n * rate for this item\", never as free — because the server re-derives the\n * charge from the DB and ignores the amount posted here. If the two rules ever\n * disagree, the member sees one number and is charged another; that mismatch\n * is the whole reason this exists, so keep them in step.\n */\n const savingsBaseCents = (): number => {\n const list = options.pricing.priceCents;\n const savings = options.pricing.savingsPriceCents;\n return options.isSavingsMember?.() && savings != null ? savings : list;\n };\n\n const pricing = (): PromoPricing => {\n const baseCents = savingsBaseCents();\n const promo = promoApplied();\n if (!promo?.valid || !promo.discountCents) {\n return { baseCents, discountCents: 0, finalCents: baseCents };\n }\n const discountCents = Math.min(baseCents, promo.discountCents);\n return {\n baseCents,\n discountCents,\n finalCents: promo.finalCents ?? Math.max(0, baseCents - discountCents),\n promoCode: promo.promoCode?.code,\n };\n };\n\n // ── Promo code ──────────────────────────────────────────────────\n\n async function applyPromo() {\n const code = promoCode().trim();\n if (!code) {\n setPromoError('Enter a promo code.');\n return;\n }\n setPromoError(null);\n setPromoValidating(true);\n try {\n const res = await promoCodesApi.validate(code, {\n productIds: [options.pricing.productId],\n subtotalCents: options.pricing.priceCents,\n });\n if (!res.valid) {\n setPromoError(res.error ?? 'Invalid promo code.');\n setPromoApplied(null);\n } else {\n setPromoApplied(res);\n setPromoError(null);\n }\n } catch {\n setPromoError('Could not validate promo code. Please try again.');\n setPromoApplied(null);\n } finally {\n setPromoValidating(false);\n }\n }\n\n function clearPromo() {\n setPromoCode('');\n setPromoApplied(null);\n setPromoError(null);\n }\n\n // ── Validation per step ─────────────────────────────────────────\n\n function validateStep(s: number): string | null {\n if (s === 0) {\n if (!firstName().trim()) return 'First name is required.';\n if (!lastName().trim()) return 'Last name is required.';\n // Authenticated members already have an account — they don't re-enter\n // credentials; submit() subscribes their existing account instead.\n if (!authStore.isAuthenticated()) {\n if (!email().trim()) return 'Email is required.';\n if (!password().trim()) return 'Password is required.';\n if (password().length < 8) return 'Password must be at least 8 characters.';\n }\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(dateOfBirth())) return 'Enter a valid date of birth.';\n const dob = new Date(dateOfBirth() + 'T00:00:00');\n if (Number.isNaN(dob.getTime())) return 'Enter a valid date of birth.';\n const age = (Date.now() - dob.getTime()) / (365.25 * 24 * 3600 * 1000);\n if (age < 18) return 'You must be at least 18 to register.';\n if (age > 120) return 'Enter a valid date of birth.';\n } else if (s === 1) {\n return firstAddressError(validateAddress(addr.shipping(), '', { enforceAvailability: true }));\n } else if (s === 2) {\n if (!cardNumberRaw().trim()) return 'Card number is required.';\n if (!expiryRaw().trim()) return 'Expiration date is required.';\n if (!cvvRaw().trim()) return 'CVV is required.';\n }\n return null;\n }\n\n // ── Navigation ───────────────────────────────────────────────────\n\n async function next() {\n const err = validateStep(step());\n if (err) {\n setError(err);\n return;\n }\n setError(null);\n setStep((s) => s + 1);\n }\n\n function back() {\n setError(null);\n if (step() > 0) setStep((s) => s - 1);\n }\n\n // ── Submit (from Payment step) ──────────────────────────────────\n\n async function submit() {\n const finalPricing = pricing();\n const isFree = finalPricing.finalCents === 0;\n\n if (!isFree) {\n const cardErr = validateStep(2);\n if (cardErr) {\n setError(cardErr);\n return;\n }\n if (addr.billingIsOverride()) {\n const bErr = firstAddressError(validateAddress(addr.billing(), 'Billing'));\n if (bErr) { setError(bErr); return; }\n }\n }\n\n setError(null);\n\n let opaque: Record<string, unknown> | undefined;\n if (!isFree) {\n setTokenizing(true);\n setOutcome({ kind: 'tokenizing' });\n try {\n opaque = await accept.tokenize({\n cardNumber: cardNumberRaw(),\n expiry: expiryRaw(),\n cvv: cvvRaw(),\n });\n } catch (e) {\n setError(e instanceof Error ? e.message : 'Card tokenization failed.');\n setTokenizing(false);\n setOutcome({ kind: 'in_progress' });\n return;\n }\n setTokenizing(false);\n }\n\n setSubmitting(true);\n setOutcome({ kind: 'submitting' });\n\n // One key per logical purchase attempt: minted on first submit, persisted in\n // the draft (the auto-save effect tracks it), reused verbatim on retries so\n // the backend's idempotency middleware can collapse a replay of a create\n // that already committed.\n let idempotencyKey = idemKey();\n if (!idempotencyKey) {\n idempotencyKey = newIdempotencyKey();\n setIdemKey(idempotencyKey);\n }\n\n try {\n const promo = promoApplied();\n\n if (authStore.isAuthenticated()) {\n // Logged-in member (e.g. a savings member who created an account first):\n // subscribe their EXISTING account instead of creating a second one. The\n // account may be name-only, so first persist the profile entered during\n // intake, then create the subscription + Apex Rx on that account.\n await usersApi.updateProfile({\n firstName: firstName().trim(),\n lastName: lastName().trim(),\n dateOfBirth: dateOfBirth(),\n phone: phone().trim() || undefined,\n address1: street().trim(),\n city: city().trim(),\n state: state(),\n zip: zip().trim(),\n });\n\n const res = await subscriptionsApi.create({\n opaqueData: opaque,\n amountCents: finalPricing.baseCents,\n intervalDays: options.intervalDays ?? 30,\n billingAddress: effectiveBillingAddress(),\n products: [{\n productId: options.pricing.productId,\n productName: options.pricing.productName,\n quantity: 1,\n dosage: options.surveyResult.dosage,\n }],\n productId: options.pricing.productId,\n promoCode: promo?.valid ? promo.promoCode?.code : undefined,\n metadata: {\n drugId: options.surveyResult.drugId,\n selectedDosage: options.surveyResult.dosage,\n caseNotes: options.surveyResult.caseNotes,\n v2SurveyResponseId: options.surveyResult.v2SurveyResponseId,\n },\n }, { idempotencyKey });\n if ((res as ApiResponse).error) {\n throw new Error((res as ApiResponse).error || 'Subscription failed. Please try again.');\n }\n } else {\n await authStore.signupAndSubscribe({\n email: email().trim(),\n password: password(),\n member: {\n firstName: firstName().trim(),\n lastName: lastName().trim(),\n dateOfBirth: dateOfBirth(),\n phone: phone().trim() || undefined,\n address1: street().trim(),\n city: city().trim(),\n state: state(),\n zip: zip().trim(),\n },\n opaqueData: opaque,\n amountCents: finalPricing.baseCents,\n intervalDays: options.intervalDays ?? 30,\n medication: options.surveyResult.drugId,\n products: [{\n productId: options.pricing.productId,\n productName: options.pricing.productName,\n quantity: 1,\n dosage: options.surveyResult.dosage,\n }],\n billingAddress: effectiveBillingAddress(),\n surveyResponseId: options.surveyResult.surveyResponseId,\n v2SurveyResponseId: options.surveyResult.v2SurveyResponseId,\n caseNotes: options.surveyResult.caseNotes,\n promoCode: promo?.valid ? promo.promoCode?.code : undefined,\n }, { idempotencyKey });\n }\n\n clearDraft();\n setOutcome({ kind: 'completed' });\n } catch (err) {\n // The server refused because this member already holds a live\n // subscription. Not an error the member can act on by retrying — nothing\n // is wrong with what they typed — so surface it as its own outcome and\n // let the host explain, rather than as a red banner over a form that will\n // never succeed. Draft cleared so a later legitimate intake (after a\n // cancellation) starts clean.\n if (err instanceof ApiError && err.code === 'SUBSCRIPTION_EXISTS') {\n clearDraft();\n setOutcome({ kind: 'already_subscribed' });\n return;\n }\n\n // A definitive rejection (4xx: decline, validation) means nothing was\n // committed — the next attempt is a NEW operation and must not be\n // deduped against this one, so rotate the key. An AMBIGUOUS failure\n // (connection dropped, 5xx) may have committed server-side: keep the key\n // so the retry collapses into the original instead of charging twice.\n const maybeCommitted = err instanceof ApiError && err.ambiguous;\n if (!maybeCommitted) setIdemKey(newIdempotencyKey());\n\n setError(err instanceof Error ? err.message : 'Registration failed. Please try again.');\n setOutcome({ kind: 'in_progress' });\n } finally {\n setSubmitting(false);\n }\n }\n\n return {\n step,\n stepCount: 3,\n next,\n back,\n\n outcome,\n error,\n submitting,\n tokenizing,\n tokenizerReady: accept.ready,\n acceptJsReady: accept.ready,\n tokenizerError: accept.error,\n acceptJsError: accept.error,\n\n firstName, setFirstName,\n lastName, setLastName,\n email, setEmail,\n password, setPassword,\n dateOfBirth, setDateOfBirth,\n phone, setPhone,\n\n address: addr,\n\n cardNumber: cardNumberRaw,\n setCardNumber: (v) => setCardNumberRaw(formatCardNumber(v)),\n expiry: expiryRaw,\n setExpiry: (v) => setExpiryRaw(formatExpiry(v)),\n cvv: cvvRaw,\n setCvv: (v) => setCvvRaw(formatCvv(v)),\n\n promoCode,\n setPromoCode,\n promoValidating,\n promoError,\n promoApplied,\n applyPromo,\n clearPromo,\n\n pricing,\n\n surveyResult: options.surveyResult,\n medication: options.pricing,\n\n submit,\n };\n}\n","import { createEffect, createRoot, on } from 'solid-js';\nimport cartStore, { type CartItem } from '../stores/cart';\nimport { promoCodesApi } from '../api/client';\nimport {\n adoptCartId,\n fetchCartConfig,\n fetchResumedCart,\n postCartSnapshot,\n readCartToken,\n resetCartId,\n stripCartToken,\n type CartSnapshotLine,\n type ResumedCart,\n} from '../api/cart';\n\n// Abandoned-cart capture, wired to the cart store.\n//\n// Two halves, both best-effort:\n//\n// - SNAPSHOT: every cart change is mirrored to the-backend (debounced, plus a\n// flush on pagehide — a shopper leaving is exactly the moment this exists\n// for). Identity only; the server re-prices.\n// - RESTORE: a `?cart=` token in the URL is traded for the saved cart and\n// rebuilt locally, so a recovery email opened on a phone brings the basket\n// with it.\n//\n// Nothing here may block, slow or break shopping. Every failure path ends in\n// \"carry on with the cart this browser already had\".\n\nexport interface CartCaptureOptions {\n /** Debounce for snapshot writes. Quantity steppers fire fast. */\n debounceMs?: number;\n /**\n * Address for an anonymous shopper, if the site collected one outside the\n * survey's email gate (e.g. checkout step 1). Logged-in shoppers need\n * nothing here — the backend reads their email off the token.\n */\n email?: () => string | null | undefined;\n}\n\nfunction toSnapshotLines(items: CartItem[]): CartSnapshotLine[] {\n return items.map((i) => ({\n productId: i.productId,\n ...(i.dosage ? { dosage: i.dosage } : {}),\n quantity: i.quantity || 1,\n }));\n}\n\n/** Rebuild the local cart from a resumed one, replacing whatever was there. */\nfunction applyResumedCart(resumed: ResumedCart): void {\n cartStore.clear();\n for (const line of resumed.items) {\n cartStore.add({\n productId: line.productId,\n productName: line.name,\n dosage: line.dosage ?? '',\n quantity: 1,\n // The sale price when one is running — same figure the catalog shows.\n priceCents: line.salePriceCents ?? line.priceCents,\n drugId: line.productId,\n apexDrugId: line.apexDrugId,\n categories: line.categories,\n thumbnailUrl: line.thumbnailUrl ?? undefined,\n hideDoseLabel: line.hideDoseLabel || undefined,\n isSubscription: line.isSubscription || undefined,\n });\n if (line.quantity > 1) {\n cartStore.setQuantity(cartStore.itemKey(line.productId, line.dosage ?? ''), line.quantity);\n }\n }\n}\n\n/**\n * Re-apply the promo code the cart was carrying when it was abandoned.\n *\n * Re-VALIDATED, never trusted: a code can expire, get revoked, or stop\n * covering the products still in the cart between abandonment and return, and\n * showing a discount the checkout won't honour is worse than showing none.\n */\nasync function restorePromo(resumed: ResumedCart): Promise<void> {\n if (!resumed.promoCode) return;\n try {\n const res = await promoCodesApi.validate(resumed.promoCode, {\n productIds: resumed.items.map((i) => i.productId),\n subtotalCents: resumed.subtotalCents,\n });\n if (!res.valid || !res.promoCode) return;\n cartStore.setPromo({\n code: res.promoCode.code,\n discountType: res.promoCode.discountType,\n discountValueCents: res.promoCode.discountValueCents,\n discountCents: res.discountCents ?? 0,\n });\n } catch {\n /* the cart is restored either way — the code is a bonus */\n }\n}\n\nlet restoreInFlight: Promise<ResumedCart | null> | null = null;\n\n/**\n * Redeem a `?cart=` token if the URL carries one.\n *\n * Exported for sites that want to act on the restore — opening their cart\n * drawer on arrival, say, or waiting for their catalog first.\n *\n * Single-flight: `startCartCapture()` restores on its own, so a site calling\n * this directly would otherwise race it — both read the token before either\n * strips it, and the cart gets rebuilt twice. Concurrent callers share one\n * restore and one result.\n */\nexport function restoreCartFromLink(): Promise<ResumedCart | null> {\n if (!restoreInFlight) {\n restoreInFlight = runRestore().finally(() => {\n restoreInFlight = null;\n });\n }\n return restoreInFlight;\n}\n\nasync function runRestore(): Promise<ResumedCart | null> {\n const token = readCartToken();\n if (!token) return null;\n\n const resumed = await fetchResumedCart(token);\n // Strip either way: a dead token that stays in the URL re-fires this on\n // every navigation and, worse, gets shared or bookmarked.\n stripCartToken();\n if (!resumed) return null;\n\n // Keep writing to the cart the email was about, not the one this browser\n // happened to mint — otherwise the reminder history and the conversion land\n // on different rows.\n adoptCartId(resumed.cartId);\n applyResumedCart(resumed);\n void restorePromo(resumed);\n return resumed;\n}\n\nlet running = false;\n\n/**\n * Start mirroring the cart. Call once at app boot; returns a disposer.\n *\n * No-ops for tenants that never opted in (`GET /config/cart`), so it is safe to\n * call unconditionally from shared site scaffolding.\n */\nexport function startCartCapture(opts: CartCaptureOptions = {}): () => void {\n if (running) return () => {};\n running = true;\n\n const debounceMs = opts.debounceMs ?? 2000;\n let enabled: boolean | null = null;\n let pending: CartItem[] | null = null;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let lastSentEmpty = true;\n\n function flush(): void {\n if (timer) clearTimeout(timer);\n timer = undefined;\n const items = pending;\n pending = null;\n if (!items || enabled !== true) return;\n\n // An empty cart is not an abandoned one: the snapshot deletes the row, and\n // the id is retired so the next basket starts a clean one. This is also the\n // post-purchase path — checkout clears the cart — which is why converting\n // doesn't need its own wiring here.\n if (items.length === 0) {\n if (lastSentEmpty) return;\n postCartSnapshot({ items: [], promoCode: null });\n resetCartId();\n lastSentEmpty = true;\n return;\n }\n\n postCartSnapshot({\n items: toSnapshotLines(items),\n promoCode: cartStore.appliedPromo()?.code ?? null,\n email: opts.email?.() ?? null,\n });\n lastSentEmpty = false;\n }\n\n function schedule(ms: number): void {\n if (timer) clearTimeout(timer);\n timer = setTimeout(flush, ms);\n }\n\n const dispose = createRoot((disposeRoot) => {\n // `defer` so merely starting capture doesn't post the cart the shopper\n // hasn't touched; the first real change schedules the first write.\n createEffect(\n on(\n cartStore.items,\n (items) => {\n pending = items;\n if (enabled === true) schedule(debounceMs);\n },\n { defer: true },\n ),\n );\n return disposeRoot;\n });\n\n void fetchCartConfig().then((cfg) => {\n enabled = cfg.snapshot;\n if (!enabled) return;\n void restoreCartFromLink();\n if (pending) schedule(0);\n });\n\n // The shopper leaving with items in the cart is the whole point; don't let a\n // pending debounce die with the page.\n const onPageHide = () => flush();\n if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {\n window.addEventListener('pagehide', onPageHide);\n }\n\n return () => {\n if (timer) clearTimeout(timer);\n if (typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {\n window.removeEventListener('pagehide', onPageHide);\n }\n dispose();\n running = false;\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/api/cart.ts"],"names":[],"mappings":";;;;AAmBA,IAAM,QAAA,GAA8B,EAAE,QAAA,EAAU,KAAA,EAAM;AAEtD,IAAI,aAAA,GAAmD,IAAA;AAMhD,SAAS,eAAA,GAA8C;AAC5D,EAAA,IAAI,CAAC,aAAA,EAAe;AAClB,IAAA,aAAA,GAAA,CAAiB,YAAY;AAC3B,MAAA,IAAI;AACF,QAAA,MAAM,MAAM,SAAA,EAAU;AACtB,QAAA,MAAM,MAAM,MAAM,KAAA,CAAM,CAAA,EAAG,GAAA,CAAI,OAAO,CAAA,YAAA,CAAA,EAAgB;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AAA,IAAI,CAAC,GAAA,CAAI,YAAA,CAAa,GAAA,CAAI,MAAM,CAAA,EAAG;AACnC,IAAA,GAAA,CAAI,YAAA,CAAa,OAAO,MAAM,CAAA;AAC9B,IAAA,MAAA,CAAO,QAAQ,YAAA,CAAa,IAAI,EAAA,EAAI,GAAA,CAAI,UAAU,CAAA;AAAA,EACpD,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"J6KNY37T.js","sourcesContent":["import { getConfig } from '../config';\nimport { peekFunnelSessionId } from './funnel';\n\n// ── Abandoned-cart transport ────────────────────────────────────────────────\n//\n// Thin client for the-backend's cart-capture endpoints:\n// GET /config/cart → whether this tenant mirrors carts at all\n// POST /cart/snapshot → server-side mirror of the browser's cart\n// GET /cart/resume → trade an emailed token for the saved cart\n//\n// Sibling of ./funnel, and the same posture: fire-and-forget, fail-silent.\n// Cart capture is marketing instrumentation and must never break, block or\n// slow down shopping.\n\nexport interface CartCaptureConfig {\n /** Tenant opted in (features.cartRecovery); false = never send anything. */\n snapshot: boolean;\n}\n\nconst DISABLED: CartCaptureConfig = { snapshot: false };\n\nlet configPromise: Promise<CartCaptureConfig> | null = null;\n\n/**\n * The tenant's cart-capture posture, fetched once per page load and cached.\n * Fails closed: any error reads as \"off\".\n */\nexport function fetchCartConfig(): Promise<CartCaptureConfig> {\n if (!configPromise) {\n configPromise = (async () => {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/config/cart`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return DISABLED;\n const body = (await res.json()) as Partial<CartCaptureConfig>;\n return { snapshot: body.snapshot === true };\n } catch {\n return DISABLED;\n }\n })();\n }\n return configPromise;\n}\n\n/** Test seam: forget the cached config so the next fetch re-resolves. */\nexport function resetCartConfigCache(): void {\n configPromise = null;\n}\n\nconst cartIdKey = () => `${getConfig().storagePrefix}-cart-id`;\n\n/**\n * Stable id for this shopper's cart, minted on first use and kept in\n * localStorage — NOT sessionStorage like the survey session.\n *\n * A cart outlives the tab it was filled in: someone adds items, closes the\n * browser, comes back tomorrow and finds the cart still there (the cart store\n * itself persists the same way). The id has to survive with it, or every visit\n * would look like a brand-new abandoned cart and one shopper would accumulate\n * a row — and a reminder track — per session.\n */\nexport function cartId(): string {\n let id: string | null = null;\n try {\n id = localStorage.getItem(cartIdKey());\n } catch {\n /* storage unavailable (private mode) — fall through to an ephemeral id */\n }\n if (!id) {\n id =\n typeof crypto !== 'undefined' && 'randomUUID' in crypto\n ? crypto.randomUUID()\n : `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n try {\n localStorage.setItem(cartIdKey(), id);\n } catch {\n /* ephemeral it is */\n }\n }\n return id;\n}\n\n/**\n * Continue the cart a recovery email points at, instead of the one this browser\n * happens to hold. Adopting the emailed id keeps the reminder history, the\n * email address and the eventual conversion on ONE row.\n */\nexport function adoptCartId(id: string): void {\n if (!id) return;\n try {\n localStorage.setItem(cartIdKey(), id);\n } catch {\n /* storage unavailable — the adoption is ephemeral */\n }\n}\n\n/**\n * Start a fresh cart id. Called after a purchase: the old id is stamped\n * converted server-side and must never be written to again, or a new cart\n * would inherit a bought cart's row (and its silence — converted rows are\n * never nudged).\n */\nexport function resetCartId(): void {\n try {\n localStorage.removeItem(cartIdKey());\n } catch {\n /* nothing to clear */\n }\n}\n\nexport interface CartSnapshotLine {\n productId: string;\n dosage?: string;\n quantity: number;\n}\n\n/**\n * Mirror the cart server-side. Identity only — the backend re-prices from the\n * catalog and ignores anything else we send, so there is no point shipping\n * names or prices.\n *\n * `keepalive` lets the request survive the page unload that so often IS the\n * abandonment.\n */\nexport function postCartSnapshot(params: {\n items: CartSnapshotLine[];\n promoCode?: string | null;\n email?: string | null;\n}): void {\n try {\n const cfg = getConfig();\n void fetch(`${cfg.apiBase}/cart/snapshot`, {\n method: 'POST',\n keepalive: true,\n headers: {\n 'Content-Type': 'application/json',\n 'X-Tenant-Key': cfg.tenantKey,\n },\n body: JSON.stringify({\n cartId: cartId(),\n items: params.items,\n promoCode: params.promoCode ?? null,\n ...(params.email ? { email: params.email } : {}),\n // Only when a survey session already exists: it lets the backend reuse\n // the address the pre-survey email gate collected, which is often the\n // only handle we have on an anonymous shopper.\n ...(peekFunnelSessionId() ? { sessionId: peekFunnelSessionId() } : {}),\n }),\n }).catch(() => {});\n } catch {\n /* not configured yet — drop */\n }\n}\n\n/** A resumed cart line, already re-priced against today's catalog. */\nexport interface ResumedCartLine {\n productId: string;\n dosage?: string;\n quantity: number;\n name: string;\n priceCents: number;\n salePriceCents: number | null;\n thumbnailUrl: string | null;\n isSubscription: boolean;\n apexDrugId: string | null;\n categories: string[];\n hideDoseLabel: boolean;\n}\n\nexport interface ResumedCart {\n cartId: string;\n items: ResumedCartLine[];\n /** Lines whose product has since been discontinued or deactivated. */\n unavailable: Array<{ productId: string; dosage?: string; quantity: number }>;\n promoCode: string | null;\n subtotalCents: number;\n}\n\n/**\n * Exchange an emailed recovery token for the saved cart.\n *\n * The token is the ONLY thing authorizing this read — the-backend verifies its\n * HMAC before returning anything. A 404 (expired, already bought, tampered, or\n * every product gone) resolves to null so the caller simply keeps whatever cart\n * this browser already had.\n */\nexport async function fetchResumedCart(token: string): Promise<ResumedCart | null> {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/cart/resume?token=${encodeURIComponent(token)}`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return null;\n const body = (await res.json()) as Partial<ResumedCart>;\n if (!body.cartId || !Array.isArray(body.items) || body.items.length === 0) return null;\n return {\n cartId: body.cartId,\n items: body.items,\n unavailable: Array.isArray(body.unavailable) ? body.unavailable : [],\n promoCode: body.promoCode ?? null,\n subtotalCents: typeof body.subtotalCents === 'number' ? body.subtotalCents : 0,\n };\n } catch {\n return null;\n }\n}\n\n/** Read the `?cart=` token from the current URL. */\nexport function readCartToken(): string | null {\n try {\n const token = new URLSearchParams(window.location.search).get('cart');\n return token && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Drop `?cart=` from the address bar once it's been redeemed, so a refresh (or\n * a shared URL) doesn't re-run the restore over a cart the shopper has since\n * edited. History is replaced, not pushed — the token was never a page.\n */\nexport function stripCartToken(): void {\n try {\n const url = new URL(window.location.href);\n if (!url.searchParams.has('cart')) return;\n url.searchParams.delete('cart');\n window.history.replaceState({}, '', url.toString());\n } catch {\n /* no history API — leaving the param is harmless */\n }\n}\n"]}
|