@apextelemed/partner-core 0.26.0-dev.95 → 0.26.0-dev.97
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/chunk/{WRLY53X7.jsx → 2G5SGQLM.jsx} +6 -1
- package/dist/chunk/{7IQKUSD5.js → V5EB4OZB.js} +7 -3
- package/dist/chunk/V5EB4OZB.js.map +1 -0
- package/dist/flows/index.js +1 -1
- package/dist/flows/index.jsx +1 -1
- package/dist/index/index.js +1 -1
- package/dist/index/index.jsx +1 -1
- package/package.json +1 -1
- package/dist/chunk/7IQKUSD5.js.map +0 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
adoptCartId,
|
|
3
|
+
capturePromoCode,
|
|
3
4
|
clearPromoCode,
|
|
4
5
|
fetchCartConfig,
|
|
5
6
|
fetchResumedCart,
|
|
@@ -165,6 +166,7 @@ function useSubscriptionIntakeFlow(options) {
|
|
|
165
166
|
);
|
|
166
167
|
if (existing) {
|
|
167
168
|
clearDraft();
|
|
169
|
+
clearPromoCode();
|
|
168
170
|
setOutcome(
|
|
169
171
|
existing.productId === options.pricing.productId ? { kind: "completed" } : { kind: "already_subscribed", productId: existing.productId }
|
|
170
172
|
);
|
|
@@ -257,6 +259,7 @@ function useSubscriptionIntakeFlow(options) {
|
|
|
257
259
|
} else {
|
|
258
260
|
setPromoApplied(res);
|
|
259
261
|
setPromoError(null);
|
|
262
|
+
capturePromoCode(code);
|
|
260
263
|
}
|
|
261
264
|
} catch {
|
|
262
265
|
setPromoError("Could not validate promo code. Please try again.");
|
|
@@ -266,6 +269,7 @@ function useSubscriptionIntakeFlow(options) {
|
|
|
266
269
|
}
|
|
267
270
|
}
|
|
268
271
|
function clearPromo() {
|
|
272
|
+
clearPromoCode();
|
|
269
273
|
setPromoCode("");
|
|
270
274
|
setPromoApplied(null);
|
|
271
275
|
setPromoError(null);
|
|
@@ -448,6 +452,7 @@ function useSubscriptionIntakeFlow(options) {
|
|
|
448
452
|
}, { idempotencyKey });
|
|
449
453
|
}
|
|
450
454
|
clearDraft();
|
|
455
|
+
clearPromoCode();
|
|
451
456
|
setOutcome({ kind: "completed" });
|
|
452
457
|
} catch (err) {
|
|
453
458
|
if (err instanceof ApiError && err.code === "SUBSCRIPTION_EXISTS") {
|
|
@@ -673,4 +678,4 @@ export {
|
|
|
673
678
|
restoreCartFromLink,
|
|
674
679
|
startCartCapture
|
|
675
680
|
};
|
|
676
|
-
//# sourceMappingURL=
|
|
681
|
+
//# sourceMappingURL=2G5SGQLM.jsx.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readPromoCode, clearPromoCode, readCartToken, fetchResumedCart, stripCartToken, adoptCartId, fetchCartConfig, postCartSnapshot, resetCartId } from './WCBIY4IC.js';
|
|
1
|
+
import { readPromoCode, clearPromoCode, readCartToken, fetchResumedCart, stripCartToken, adoptCartId, fetchCartConfig, capturePromoCode, postCartSnapshot, resetCartId } from './WCBIY4IC.js';
|
|
2
2
|
import { useCardTokenizer, useSmsConsent, useAddressPair, useCatalogAvailability, isLive, formatCvv, formatExpiry, formatCardNumber, bestOfferDiscount, offerBeatsPromo, catalogUnavailableMessage, firstAddressError, validateAddress, isValidUsPhone, PHONE_ERROR } from './LIGPTJRM.js';
|
|
3
3
|
import { auth_default, cart_default } from './X4YVV27O.js';
|
|
4
4
|
import { promoCodesApi, subscriptionsApi, offersApi, newIdempotencyKey, usersApi, ApiError } from './PNQNOYWY.js';
|
|
@@ -126,6 +126,7 @@ function useSubscriptionIntakeFlow(options) {
|
|
|
126
126
|
);
|
|
127
127
|
if (existing) {
|
|
128
128
|
clearDraft();
|
|
129
|
+
clearPromoCode();
|
|
129
130
|
setOutcome(
|
|
130
131
|
existing.productId === options.pricing.productId ? { kind: "completed" } : { kind: "already_subscribed", productId: existing.productId }
|
|
131
132
|
);
|
|
@@ -218,6 +219,7 @@ function useSubscriptionIntakeFlow(options) {
|
|
|
218
219
|
} else {
|
|
219
220
|
setPromoApplied(res);
|
|
220
221
|
setPromoError(null);
|
|
222
|
+
capturePromoCode(code);
|
|
221
223
|
}
|
|
222
224
|
} catch {
|
|
223
225
|
setPromoError("Could not validate promo code. Please try again.");
|
|
@@ -227,6 +229,7 @@ function useSubscriptionIntakeFlow(options) {
|
|
|
227
229
|
}
|
|
228
230
|
}
|
|
229
231
|
function clearPromo() {
|
|
232
|
+
clearPromoCode();
|
|
230
233
|
setPromoCode("");
|
|
231
234
|
setPromoApplied(null);
|
|
232
235
|
setPromoError(null);
|
|
@@ -409,6 +412,7 @@ function useSubscriptionIntakeFlow(options) {
|
|
|
409
412
|
}, { idempotencyKey });
|
|
410
413
|
}
|
|
411
414
|
clearDraft();
|
|
415
|
+
clearPromoCode();
|
|
412
416
|
setOutcome({ kind: "completed" });
|
|
413
417
|
} catch (err) {
|
|
414
418
|
if (err instanceof ApiError && err.code === "SUBSCRIPTION_EXISTS") {
|
|
@@ -625,5 +629,5 @@ function startCartCapture(opts = {}) {
|
|
|
625
629
|
}
|
|
626
630
|
|
|
627
631
|
export { OFFER_BEATS_PROMO_NOTICE, restoreCartFromLink, startCartCapture, useSubscriptionIntakeFlow, validateResumedPromo };
|
|
628
|
-
//# sourceMappingURL=
|
|
629
|
-
//# sourceMappingURL=
|
|
632
|
+
//# sourceMappingURL=V5EB4OZB.js.map
|
|
633
|
+
//# sourceMappingURL=V5EB4OZB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/flows/subscriptionIntake.ts","../../src/flows/cartCapture.ts"],"names":["createEffect","on"],"mappings":";;;;;;;AA0BA,IAAM,YAAA,GAAe,CAAA,GAAI,EAAA,GAAK,IAAA,GAAO,GAAA;AACrC,IAAM,mBAAA,GAAsB,CAAA;AAsB5B,SAAS,QAAA,GAAmB;AAC1B,EAAA,OAAO,CAAA,EAAG,SAAA,EAAU,CAAE,aAAa,CAAA,0BAAA,CAAA;AACrC;AAEA,SAAS,SAAA,GAAyB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AAA;AAED,EAAA,KAAK,eAAA,EAAgB,CAAE,IAAA,CAAK,CAAC,GAAA,KAAQ;AACnC,IAAA,OAAA,GAAU,GAAA,CAAI,QAAA;AACd,IAAA,IAAI,CAAC,OAAA,EAAS;AACd,IAAA,KAAK,mBAAA,EAAoB;AACzB,IAAA,IAAI,OAAA,WAAkB,CAAC,CAAA;AAAA,EACzB,CAAC,CAAA;AAID,EAAA,MAAM,UAAA,GAAa,MAAM,KAAA,EAAM;AAC/B,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,IAAe,OAAO,MAAA,CAAO,qBAAqB,UAAA,EAAY;AAClF,IAAA,MAAA,CAAO,gBAAA,CAAiB,YAAY,UAAU,CAAA;AAAA,EAChD;AAEA,EAAA,OAAO,MAAM;AACX,IAAA,IAAI,KAAA,eAAoB,KAAK,CAAA;AAC7B,IAAA,IAAI,OAAO,MAAA,KAAW,WAAA,IAAe,OAAO,MAAA,CAAO,wBAAwB,UAAA,EAAY;AACrF,MAAA,MAAA,CAAO,mBAAA,CAAoB,YAAY,UAAU,CAAA;AAAA,IACnD;AACA,IAAA,OAAA,EAAQ;AACR,IAAA,aAAA,GAAgB,IAAA;AAChB,IAAA,OAAA,GAAU,KAAA;AAAA,EACZ,CAAA;AACF","file":"V5EB4OZB.js","sourcesContent":["import { createEffect, createSignal, on, onMount, type Accessor } from 'solid-js';\nimport {\n offersApi,\n promoCodesApi,\n subscriptionsApi,\n usersApi,\n newIdempotencyKey,\n ApiError,\n type MemberOffer,\n type PromoValidationResponse,\n type ApiResponse,\n} from '../api/client';\nimport { bestOfferDiscount, offerBeatsPromo } from './offers';\nimport { readPromoCode, clearPromoCode, capturePromoCode } from '../api/promoRef';\nimport authStore from '../stores/auth';\nimport { useCardTokenizer, type HostedCardField } from './_internal/cardTokenizer';\nimport { formatCardNumber, formatExpiry, formatCvv } from './checkout';\nimport { getConfig } from '../config';\nimport { PHONE_ERROR, isValidUsPhone } from './phone';\nimport { useSmsConsent, type SmsConsent } from './_internal/smsConsent';\nimport { useAddressPair, validateAddress, firstAddressError, type AddressPair } from './address';\nimport { isLive } from './subscriptionStatus';\nimport { useCatalogAvailability, catalogUnavailableMessage, type CatalogAvailabilityState } from './catalogAvailability';\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 /** Version of the text-message consent wording the visitor ticked. */\n smsConsentVersion?: 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 * The verified savings member id to send on the unauthenticated signup path,\n * so an account created AT checkout is linked and charged the savings rate\n * (the backend accepts and links `savingsMemberId` on register-and-subscribe,\n * but it was never sent). Read at submit time; null/empty sends nothing. The\n * authenticated path ignores it — the server prices off the persisted link.\n */\n savingsMemberId?: () => string | null;\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 /** What is actually taken off: the promo's discount or the offer's, never both. */\n discountCents: number;\n finalCents: number;\n /** Set when the typed promo code is the discount applied. */\n promoCode?: string;\n /**\n * Set ONLY when the member's own offer is the discount applied — it beat the\n * typed promo code, or there was none. Absent whenever `promoCode` is set.\n */\n offer?: {\n label: string;\n /** \"$10\" / \"15%\". */\n amountText: string;\n /** The last day to claim it, ready to print (\"November 11, 2026\"). */\n deadlineText: string;\n recurringIndefinite: boolean;\n /** Rebills after the first charge that carry the discount. */\n recurringCharges: number;\n discountCents: number;\n };\n}\n\n/** Shown when a typed code is valid but the member's offer is worth more. */\nexport const OFFER_BEATS_PROMO_NOTICE =\n 'Your offer is the better discount, so it is the one applied. A promo code does not combine with an offer.';\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 * Optional opt-in to text messages. `smsConsent.offer()` is null unless the\n * tenant texts customers; render the checkbox only when it isn't. Never\n * required — leaving it unticked sends nothing and the purchase proceeds. A\n * guest's grant rides the register-and-subscribe call; a signed-in member's\n * rides the profile PATCH the intake already makes.\n */\n smsConsent: SmsConsent;\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 /** Per-item deliverability for `medication.productId` in the address's\n * shipping state — a catalog item routed to a pharmacy that doesn't serve\n * that state. Per ITEM, on top of the tenant-level `unavailableStates`\n * gating the address step already applies. `submit()` refuses to charge\n * while `availability.blocking()` is true. */\n availability: CatalogAvailabilityState;\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 * True when the card is typed into the gateway's own hosted fields (NMI's\n * Collect.js) instead of cardNumber/expiry/cvv: render three containers and\n * pass each to registerCardField instead of card inputs.\n */\n hostedCardFields: Accessor<boolean>;\n /** Ref callback for a hosted card field container: `ref={(el) => flow.registerCardField('number', el)}`. */\n registerCardField: (field: HostedCardField, el: HTMLElement) => 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 * Plain words for the member when their valid promo code is NOT the discount\n * applied because their offer is worth more; null otherwise. Render it by the\n * promo field so a code that \"did nothing\" is explained.\n */\n promoNotice: Accessor<string | null>;\n\n // Pricing (reflects the applied promo or the member's offer, whichever is better)\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 // The password is never persisted, so a guest's draft always reopens on the\n // Account step to type it again (everything else is restored). Resuming past\n // it would let them reach Pay with no password and be refused by the server.\n const [step, setStep] = createSignal(\n authStore.isAuthenticated() ? Math.min(restored.step ?? 0, MAX_RESTORABLE_STEP) : 0,\n );\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 const smsConsent = useSmsConsent(phone, restored.smsConsentVersion);\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 // Single-item intake: `medication.productId` (the-backend product id) is\n // the same id the survey composed against. Runs from mount — harmless\n // before the address step, since `state` is empty and the hook skips the\n // call until it isn't.\n const availability = useCatalogAvailability(\n () => [options.pricing.productId],\n () => state(),\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 // ── Pre-fill from a `?promo=` landing ───────────────────────────\n //\n // A campaign link stashes its code (see api/promoRef). Being inside the\n // storage window says nothing about the CODE still being live — a sale can end\n // while the stash is fresh — so re-validate before showing it to anyone, and\n // drop it silently when the server says no. An expired or withdrawn code must\n // not greet a member with an error they did nothing to cause.\n //\n // A code that validates is APPLIED, not merely pre-filled. The page that\n // handed it over already showed the member a price with it taken off (the\n // savings page quotes \"an extra $X off with TRUE10\"); leaving it for them to\n // press Apply meant most were charged $X more than they were shown. The\n // validation above is the same one Apply runs, so a code the server refuses\n // — expired, or exclusive for a savings member — is dropped silently rather\n // than surfacing a refusal on arrival.\n //\n // The same stash holds a code the member applied themselves (applyPromo), so\n // a reload or a later return to checkout shows the price they were quoted\n // instead of silently dropping the discount. Removing it, or completing the\n // purchase, forgets it.\n //\n // Yields to anything already in the field: a member's own entry must never be\n // overwritten by a stale stash.\n onMount(async () => {\n if (promoCode().trim()) return;\n const stashed = readPromoCode();\n if (!stashed) return;\n try {\n const res = await promoCodesApi.validate(stashed, {\n productIds: [options.pricing.productId],\n subtotalCents: savingsBaseCents(),\n });\n if (res.valid) {\n setPromoCode(stashed);\n setPromoApplied(res);\n } else clearPromoCode();\n } catch {\n // Network/-server blip: leave the stash for the next visit rather than\n // discarding a code that may be perfectly good.\n }\n });\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 smsConsentVersion: smsConsent.draftVersion(),\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 clearPromoCode();\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 // ── The member's own offers ─────────────────────────────────────\n //\n // An offer is a discount this person holds (the-backend offers.ts). The\n // server applies it at checkout without being asked, so the total shown here\n // has to include it or the member reads one number and is charged a lower\n // one. Loaded for the session when there is one, and for a guest by the address\n // they are registering with, so nobody reaches the payment step looking at a\n // price they will not be charged. A failed read is \"no offers\": a backend from before\n // offers has no such endpoint, and a discount we cannot show must never\n // stand between a member and checkout.\n const [offers, setOffers] = createSignal<MemberOffer[]>([]);\n // Who to ask about: the session when there is one; otherwise the address a\n // guest has given, once they are past the Account step — it cannot change\n // from there on, so this asks once, not per keystroke. '' = nobody yet.\n const offerSubject = (): string => {\n if (authStore.isAuthenticated()) return 'session';\n const address = email().trim().toLowerCase();\n return step() > 0 && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(address) ? address : '';\n };\n createEffect(\n on(offerSubject, (subject) => {\n if (!subject) {\n setOffers([]);\n return;\n }\n void (async () => {\n let found: MemberOffer[] = [];\n try {\n const res = subject === 'session' ? await offersApi.mine() : await offersApi.forEmail(subject);\n if (Array.isArray(res?.offers)) found = res.offers;\n } catch {\n // No offers to show; the server still applies any they hold.\n }\n // The session or the address may have changed while this was in flight.\n setOffers(offerSubject() === subject ? found : []);\n })();\n }),\n );\n\n /**\n * One slot, two contenders: the typed promo code and the member's best offer.\n * The larger discount applies and the other is dropped — they never add up —\n * and a tie goes to the code. Same rule as the server's discount engine,\n * which is what actually prices the charge.\n */\n const pricing = (): PromoPricing => {\n const baseCents = savingsBaseCents();\n const promo = promoApplied();\n const promoCents = promo?.valid && promo.discountCents ? Math.min(baseCents, promo.discountCents) : 0;\n const best = bestOfferDiscount(offers(), { productIds: [options.pricing.productId], baseCents });\n\n if (best && offerBeatsPromo(best.discountCents, promoCents)) {\n const o = best.offer;\n return {\n baseCents,\n discountCents: best.discountCents,\n finalCents: baseCents - best.discountCents,\n offer: {\n label: o.label,\n amountText: o.amountText,\n deadlineText: o.deadlineText,\n recurringIndefinite: o.recurringIndefinite,\n recurringCharges: o.recurringCharges ?? 0,\n discountCents: best.discountCents,\n },\n };\n }\n if (promoCents === 0) {\n return { baseCents, discountCents: 0, finalCents: baseCents };\n }\n return {\n baseCents,\n discountCents: promoCents,\n finalCents: promo!.finalCents ?? Math.max(0, baseCents - promoCents),\n promoCode: promo!.promoCode?.code,\n };\n };\n\n const promoNotice = (): string | null =>\n promoApplied()?.valid && pricing().offer ? OFFER_BEATS_PROMO_NOTICE : null;\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 // The base the promo will actually be applied to. For a savings member\n // that is the savings price, not list: the server discounts the\n // savings-substituted subtotal at checkout, so quoting off list would\n // show a percentage promo as a bigger saving than it is (10% of $399\n // displayed, 10% of $280 charged). Same rule as savingsBaseCents — keep\n // the two in step.\n subtotalCents: savingsBaseCents(),\n });\n if (!res.valid) {\n setPromoError(res.error ?? 'Invalid promo code.');\n setPromoApplied(null);\n } else {\n setPromoApplied(res);\n setPromoError(null);\n // Survive a reload / a return to checkout (re-validated on mount).\n capturePromoCode(code);\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 clearPromoCode();\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 // Phone stays optional here; when one is given it has to be dialable.\n if (phone().trim() && !isValidUsPhone(phone())) return PHONE_ERROR;\n } else if (s === 1) {\n return firstAddressError(validateAddress(addr.shipping(), '', { enforceAvailability: true }));\n } else if (s === 2) {\n // Hosted fields (NMI): the card is in the gateway's iframes, which check it on submit.\n if (!accept.hostedFields()) {\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 }\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 let awaitingAvailability = false;\n\n async function submit() {\n // Never charge (or create the Rx) for an item Apex just told us can't be\n // filled at this shipping address — checked before tokenizing so a\n // blocked patient never enters a card for nothing.\n // Held across the wait: a second click while the check is pending must\n // not start a second submit (the submitting flag is only set below).\n if (awaitingAvailability) return;\n // The Account step can be stale by now (a reload drops the password, a\n // session can end): re-check it and send the patient back to it, rather\n // than tokenizing a card for a submit the server will refuse.\n const accountErr = validateStep(0);\n if (accountErr) {\n setStep(0);\n setError(accountErr);\n return;\n }\n awaitingAvailability = true;\n try {\n await availability.settled();\n } finally {\n awaitingAvailability = false;\n }\n if (availability.blocking()) {\n setError(catalogUnavailableMessage(options.pricing.productName, state()));\n return;\n }\n\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 billing: effectiveBillingAddress(),\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 const smsGrant = smsConsent.grant();\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 // Same PATCH as the phone, so the server applies the number first and\n // the grant covers it. Alongside other fields a refused grant is a\n // note in the reply, never a failed intake.\n ...(smsGrant ? { smsConsent: { ...smsGrant, source: 'intake' as const } } : {}),\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 const savingsMemberId = options.savingsMemberId?.() || undefined;\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 ...(savingsMemberId ? { savingsMemberId } : {}),\n ...(smsGrant ? { smsConsent: smsGrant } : {}),\n }, { idempotencyKey });\n }\n\n clearDraft();\n // Spent: a later intake must not arrive with this purchase's code applied.\n clearPromoCode();\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 smsConsent,\n\n address: addr,\n availability,\n\n cardNumber: cardNumberRaw,\n setCardNumber: (v) => setCardNumberRaw(formatCardNumber(v)),\n expiry: expiryRaw,\n setExpiry: (v) => setExpiryRaw(formatExpiry(v)),\n cvv: cvvRaw,\n hostedCardFields: accept.hostedFields,\n registerCardField: accept.registerHostedField,\n setCvv: (v) => setCvvRaw(formatCvv(v)),\n\n promoCode,\n setPromoCode,\n promoValidating,\n promoError,\n promoApplied,\n applyPromo,\n clearPromo,\n promoNotice,\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 core's cart store by default and to a\n// site's own basket via `options.source` (see CartSource).\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 * Where the basket lives, for a site that has no catalog cart.\n *\n * Abandonment is not a storefront-only event: a single-subscription partner\n * (mytruemeds, axiom-md) lets a patient choose a medication and a dose and\n * then walk away from the payment step, which is the same loss and the same\n * recoverable moment — but the selection lives in that site's own intake\n * state, not in `stores/cart`, so the default wiring watches an empty store\n * forever.\n *\n * Read and write are one option rather than two on purpose: a site that\n * supplies its own items must also say how a resumed cart gets back in, or\n * the `?cart=` link would rebuild into core's cart store, which such a site\n * never renders. Omit entirely to drive core's cart store (the default).\n */\n source?: CartSource;\n}\n\n/** A site's own basket, in the shape the wire already speaks. */\nexport interface CartSource {\n /** Current lines. Must be reactive — this is tracked. */\n items: () => CartSnapshotLine[];\n /** Promo code riding on the cart, if the site has one. */\n promoCode?: () => string | null | undefined;\n /**\n * Rebuild the site's own state from a cart resumed off a `?cart=` link. The\n * lines are re-priced against today's catalog; the promo code (if any) is\n * NOT re-validated for a custom source — `validateResumedPromo` does that\n * for a site that wants it.\n */\n restore: (cart: ResumedCart) => void;\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/**\n * Who a resumed cart is handed to. Default rebuilds core's cart store; a site\n * with its own basket claims it in `startCartCapture` (synchronously, before\n * anything can await), so a later `restoreCartFromLink()` reaches the right\n * place.\n */\nlet restoreTarget: ((cart: ResumedCart) => void) | null = null;\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\nexport interface ValidatedResumedPromo {\n code: string;\n discountType: 'percent' | 'fixed';\n discountValueCents: number;\n discountCents: number;\n}\n\n/**\n * Re-check the promo code a resumed cart was carrying, against today's rules\n * and today's lines. Null when there was no code, when it no longer validates,\n * or when the check itself fails — the cart is restored either way.\n *\n * Exported because a site with its own `CartSource` needs the same guarantee\n * without core's cart store: showing a discount checkout won't honor is worse\n * than showing none.\n */\nexport async function validateResumedPromo(resumed: ResumedCart): Promise<ValidatedResumedPromo | null> {\n if (!resumed.promoCode) return null;\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 null;\n return {\n code: res.promoCode.code,\n discountType: res.promoCode.discountType,\n discountValueCents: res.promoCode.discountValueCents,\n discountCents: res.discountCents ?? 0,\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Re-apply the promo code the cart was carrying when it was abandoned, to\n * core's cart store. Re-VALIDATED, never trusted: a code can expire, get\n * revoked, or stop covering the products still in the cart between abandonment\n * and return.\n */\nasync function restorePromo(resumed: ResumedCart): Promise<void> {\n const promo = await validateResumedPromo(resumed);\n if (promo) cartStore.setPromo(promo);\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 if (restoreTarget) {\n // A site with its own basket. It owns the promo too — core has no store to\n // put one in — so `validateResumedPromo` is left for it to call.\n restoreTarget(resumed);\n } else {\n applyResumedCart(resumed);\n void restorePromo(resumed);\n }\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 // Claim the restore BEFORE anything awaits, so a site that calls\n // `restoreCartFromLink()` itself can't race core's cart store into place.\n restoreTarget = opts.source?.restore ?? null;\n\n // Core's cart store is just the default source; the wire shape is the same\n // either way, so everything below reads lines, not cart items.\n const source: CartSource = opts.source ?? {\n items: () => toSnapshotLines(cartStore.items()),\n promoCode: () => cartStore.appliedPromo()?.code ?? null,\n restore: applyResumedCart,\n };\n\n const debounceMs = opts.debounceMs ?? 2000;\n let enabled: boolean | null = null;\n let pending: CartSnapshotLine[] | 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,\n promoCode: source.promoCode?.() ?? 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 source.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 restoreTarget = null;\n running = false;\n };\n}\n"]}
|
package/dist/flows/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { OFFER_BEATS_PROMO_NOTICE, restoreCartFromLink, startCartCapture, useSubscriptionIntakeFlow, validateResumedPromo } from '../chunk/
|
|
1
|
+
export { OFFER_BEATS_PROMO_NOTICE, restoreCartFromLink, startCartCapture, useSubscriptionIntakeFlow, validateResumedPromo } from '../chunk/V5EB4OZB.js';
|
|
2
2
|
import '../chunk/WCBIY4IC.js';
|
|
3
3
|
export { DEFAULT_COLOR_PALETTE, LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, MATCH_DEPENDENT_WARNINGS, MATCH_HOW_LABEL, ORPHAN_REASON, PHONE_ERROR, READINESS_LABEL, SOURCE_FIELD_NOTE, TERMINAL_SUBSCRIPTION_STATUSES, US_STATES, US_STATE_OPTIONS, 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, salePriceForBase, skuBindingModeFor, sourceKey, sourceLabel, 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, useSurveyFlow, useSurveyV2Flow, useUpdatePaymentMethodFlow, validateAddress, visibleWarnings } from '../chunk/LIGPTJRM.js';
|
|
4
4
|
import '../chunk/X4YVV27O.js';
|
package/dist/flows/index.jsx
CHANGED
package/dist/index/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import '../chunk/NVRAOAVV.js';
|
|
2
2
|
import '../chunk/XZVVZIRZ.js';
|
|
3
|
-
export { OFFER_BEATS_PROMO_NOTICE, restoreCartFromLink, startCartCapture, useSubscriptionIntakeFlow, validateResumedPromo } from '../chunk/
|
|
3
|
+
export { OFFER_BEATS_PROMO_NOTICE, restoreCartFromLink, startCartCapture, useSubscriptionIntakeFlow, validateResumedPromo } from '../chunk/V5EB4OZB.js';
|
|
4
4
|
export { adoptCartId, capturePromoCode, cartId, clearPromoCode, fetchCartConfig, fetchResumedCart, postCartSnapshot, readCartToken, readPromoCode, resetCartConfigCache, resetCartId, stripCartToken } from '../chunk/WCBIY4IC.js';
|
|
5
5
|
export { ADMIN_TAB_SEGMENTS, AFFILIATE_SUB_TAB_SEGMENTS, AcceptAdminInvitePage, AddressFields, AdminDashboard, AffiliateForgotPassword, AffiliateLogin, AffiliatePortal, AffiliateRegister, AffiliateResetPassword, CartCheckoutPage, CheckoutPage, EmailTemplates, ForgotPasswordPage, MemberPortal, PatientDashboardPreview, RegisterPage, ResetPasswordPage, SecureCardPanel, SignupPage, SmsConsentField, SubscribePage, SurveyPage, SurveyV2Page, UpdatePaymentMethod, adminTabFromPath, adminTabPath, affiliateSubTabFromPath, affiliateSubTabPath } from '../chunk/FKND7XXI.js';
|
|
6
6
|
export { EmbedApiError2 as ApexV2ApiError, EmbedApiError, createEmbedApiClient, disqualificationReasonText, disqualifiedDrugIds, qualifiedDrugIds } from '../chunk/LZWA44KD.js';
|
package/dist/index/index.jsx
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@apextelemed/partner-core",
|
|
3
|
-
"version": "0.26.0-dev.
|
|
3
|
+
"version": "0.26.0-dev.97",
|
|
4
4
|
"description": "Shared frontend library for telehealth patient portals (api client, stores, headless flows).",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"repository": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/flows/subscriptionIntake.ts","../../src/flows/cartCapture.ts"],"names":["createEffect","on"],"mappings":";;;;;;;AA0BA,IAAM,YAAA,GAAe,CAAA,GAAI,EAAA,GAAK,IAAA,GAAO,GAAA;AACrC,IAAM,mBAAA,GAAsB,CAAA;AAsB5B,SAAS,QAAA,GAAmB;AAC1B,EAAA,OAAO,CAAA,EAAG,SAAA,EAAU,CAAE,aAAa,CAAA,0BAAA,CAAA;AACrC;AAEA,SAAS,SAAA,GAAyB;AAChC,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,G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d,IAAA,KAAK,mBAAA,EAAoB;AACzB,IAAA,IAAI,OAAA,WAAkB,CAAC,CAAA;AAAA,EACzB,CAAC,CAAA;AAID,EAAA,MAAM,UAAA,GAAa,MAAM,KAAA,EAAM;AAC/B,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,IAAe,OAAO,MAAA,CAAO,qBAAqB,UAAA,EAAY;AAClF,IAAA,MAAA,CAAO,gBAAA,CAAiB,YAAY,UAAU,CAAA;AAAA,EAChD;AAEA,EAAA,OAAO,MAAM;AACX,IAAA,IAAI,KAAA,eAAoB,KAAK,CAAA;AAC7B,IAAA,IAAI,OAAO,MAAA,KAAW,WAAA,IAAe,OAAO,MAAA,CAAO,wBAAwB,UAAA,EAAY;AACrF,MAAA,MAAA,CAAO,mBAAA,CAAoB,YAAY,UAAU,CAAA;AAAA,IACnD;AACA,IAAA,OAAA,EAAQ;AACR,IAAA,aAAA,GAAgB,IAAA;AAChB,IAAA,OAAA,GAAU,KAAA;AAAA,EACZ,CAAA;AACF","file":"7IQKUSD5.js","sourcesContent":["import { createEffect, createSignal, on, onMount, type Accessor } from 'solid-js';\nimport {\n offersApi,\n promoCodesApi,\n subscriptionsApi,\n usersApi,\n newIdempotencyKey,\n ApiError,\n type MemberOffer,\n type PromoValidationResponse,\n type ApiResponse,\n} from '../api/client';\nimport { bestOfferDiscount, offerBeatsPromo } from './offers';\nimport { readPromoCode, clearPromoCode } from '../api/promoRef';\nimport authStore from '../stores/auth';\nimport { useCardTokenizer, type HostedCardField } from './_internal/cardTokenizer';\nimport { formatCardNumber, formatExpiry, formatCvv } from './checkout';\nimport { getConfig } from '../config';\nimport { PHONE_ERROR, isValidUsPhone } from './phone';\nimport { useSmsConsent, type SmsConsent } from './_internal/smsConsent';\nimport { useAddressPair, validateAddress, firstAddressError, type AddressPair } from './address';\nimport { isLive } from './subscriptionStatus';\nimport { useCatalogAvailability, catalogUnavailableMessage, type CatalogAvailabilityState } from './catalogAvailability';\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 /** Version of the text-message consent wording the visitor ticked. */\n smsConsentVersion?: 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 * The verified savings member id to send on the unauthenticated signup path,\n * so an account created AT checkout is linked and charged the savings rate\n * (the backend accepts and links `savingsMemberId` on register-and-subscribe,\n * but it was never sent). Read at submit time; null/empty sends nothing. The\n * authenticated path ignores it — the server prices off the persisted link.\n */\n savingsMemberId?: () => string | null;\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 /** What is actually taken off: the promo's discount or the offer's, never both. */\n discountCents: number;\n finalCents: number;\n /** Set when the typed promo code is the discount applied. */\n promoCode?: string;\n /**\n * Set ONLY when the member's own offer is the discount applied — it beat the\n * typed promo code, or there was none. Absent whenever `promoCode` is set.\n */\n offer?: {\n label: string;\n /** \"$10\" / \"15%\". */\n amountText: string;\n /** The last day to claim it, ready to print (\"November 11, 2026\"). */\n deadlineText: string;\n recurringIndefinite: boolean;\n /** Rebills after the first charge that carry the discount. */\n recurringCharges: number;\n discountCents: number;\n };\n}\n\n/** Shown when a typed code is valid but the member's offer is worth more. */\nexport const OFFER_BEATS_PROMO_NOTICE =\n 'Your offer is the better discount, so it is the one applied. A promo code does not combine with an offer.';\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 * Optional opt-in to text messages. `smsConsent.offer()` is null unless the\n * tenant texts customers; render the checkbox only when it isn't. Never\n * required — leaving it unticked sends nothing and the purchase proceeds. A\n * guest's grant rides the register-and-subscribe call; a signed-in member's\n * rides the profile PATCH the intake already makes.\n */\n smsConsent: SmsConsent;\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 /** Per-item deliverability for `medication.productId` in the address's\n * shipping state — a catalog item routed to a pharmacy that doesn't serve\n * that state. Per ITEM, on top of the tenant-level `unavailableStates`\n * gating the address step already applies. `submit()` refuses to charge\n * while `availability.blocking()` is true. */\n availability: CatalogAvailabilityState;\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 * True when the card is typed into the gateway's own hosted fields (NMI's\n * Collect.js) instead of cardNumber/expiry/cvv: render three containers and\n * pass each to registerCardField instead of card inputs.\n */\n hostedCardFields: Accessor<boolean>;\n /** Ref callback for a hosted card field container: `ref={(el) => flow.registerCardField('number', el)}`. */\n registerCardField: (field: HostedCardField, el: HTMLElement) => 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 * Plain words for the member when their valid promo code is NOT the discount\n * applied because their offer is worth more; null otherwise. Render it by the\n * promo field so a code that \"did nothing\" is explained.\n */\n promoNotice: Accessor<string | null>;\n\n // Pricing (reflects the applied promo or the member's offer, whichever is better)\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 // The password is never persisted, so a guest's draft always reopens on the\n // Account step to type it again (everything else is restored). Resuming past\n // it would let them reach Pay with no password and be refused by the server.\n const [step, setStep] = createSignal(\n authStore.isAuthenticated() ? Math.min(restored.step ?? 0, MAX_RESTORABLE_STEP) : 0,\n );\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 const smsConsent = useSmsConsent(phone, restored.smsConsentVersion);\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 // Single-item intake: `medication.productId` (the-backend product id) is\n // the same id the survey composed against. Runs from mount — harmless\n // before the address step, since `state` is empty and the hook skips the\n // call until it isn't.\n const availability = useCatalogAvailability(\n () => [options.pricing.productId],\n () => state(),\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 // ── Pre-fill from a `?promo=` landing ───────────────────────────\n //\n // A campaign link stashes its code (see api/promoRef). Being inside the\n // storage window says nothing about the CODE still being live — a sale can end\n // while the stash is fresh — so re-validate before showing it to anyone, and\n // drop it silently when the server says no. An expired or withdrawn code must\n // not greet a member with an error they did nothing to cause.\n //\n // A code that validates is APPLIED, not merely pre-filled. The page that\n // handed it over already showed the member a price with it taken off (the\n // savings page quotes \"an extra $X off with TRUE10\"); leaving it for them to\n // press Apply meant most were charged $X more than they were shown. The\n // validation above is the same one Apply runs, so a code the server refuses\n // — expired, or exclusive for a savings member — is dropped silently rather\n // than surfacing a refusal on arrival.\n //\n // Yields to anything already in the field. Nothing sets it before mount today\n // (the draft does not persist a promo), but a member's own entry must never be\n // overwritten by a stale link if that changes.\n onMount(async () => {\n if (promoCode().trim()) return;\n const stashed = readPromoCode();\n if (!stashed) return;\n try {\n const res = await promoCodesApi.validate(stashed, {\n productIds: [options.pricing.productId],\n subtotalCents: savingsBaseCents(),\n });\n if (res.valid) {\n setPromoCode(stashed);\n setPromoApplied(res);\n } else clearPromoCode();\n } catch {\n // Network/-server blip: leave the stash for the next visit rather than\n // discarding a code that may be perfectly good.\n }\n });\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 smsConsentVersion: smsConsent.draftVersion(),\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 // ── The member's own offers ─────────────────────────────────────\n //\n // An offer is a discount this person holds (the-backend offers.ts). The\n // server applies it at checkout without being asked, so the total shown here\n // has to include it or the member reads one number and is charged a lower\n // one. Loaded for the session when there is one, and for a guest by the address\n // they are registering with, so nobody reaches the payment step looking at a\n // price they will not be charged. A failed read is \"no offers\": a backend from before\n // offers has no such endpoint, and a discount we cannot show must never\n // stand between a member and checkout.\n const [offers, setOffers] = createSignal<MemberOffer[]>([]);\n // Who to ask about: the session when there is one; otherwise the address a\n // guest has given, once they are past the Account step — it cannot change\n // from there on, so this asks once, not per keystroke. '' = nobody yet.\n const offerSubject = (): string => {\n if (authStore.isAuthenticated()) return 'session';\n const address = email().trim().toLowerCase();\n return step() > 0 && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(address) ? address : '';\n };\n createEffect(\n on(offerSubject, (subject) => {\n if (!subject) {\n setOffers([]);\n return;\n }\n void (async () => {\n let found: MemberOffer[] = [];\n try {\n const res = subject === 'session' ? await offersApi.mine() : await offersApi.forEmail(subject);\n if (Array.isArray(res?.offers)) found = res.offers;\n } catch {\n // No offers to show; the server still applies any they hold.\n }\n // The session or the address may have changed while this was in flight.\n setOffers(offerSubject() === subject ? found : []);\n })();\n }),\n );\n\n /**\n * One slot, two contenders: the typed promo code and the member's best offer.\n * The larger discount applies and the other is dropped — they never add up —\n * and a tie goes to the code. Same rule as the server's discount engine,\n * which is what actually prices the charge.\n */\n const pricing = (): PromoPricing => {\n const baseCents = savingsBaseCents();\n const promo = promoApplied();\n const promoCents = promo?.valid && promo.discountCents ? Math.min(baseCents, promo.discountCents) : 0;\n const best = bestOfferDiscount(offers(), { productIds: [options.pricing.productId], baseCents });\n\n if (best && offerBeatsPromo(best.discountCents, promoCents)) {\n const o = best.offer;\n return {\n baseCents,\n discountCents: best.discountCents,\n finalCents: baseCents - best.discountCents,\n offer: {\n label: o.label,\n amountText: o.amountText,\n deadlineText: o.deadlineText,\n recurringIndefinite: o.recurringIndefinite,\n recurringCharges: o.recurringCharges ?? 0,\n discountCents: best.discountCents,\n },\n };\n }\n if (promoCents === 0) {\n return { baseCents, discountCents: 0, finalCents: baseCents };\n }\n return {\n baseCents,\n discountCents: promoCents,\n finalCents: promo!.finalCents ?? Math.max(0, baseCents - promoCents),\n promoCode: promo!.promoCode?.code,\n };\n };\n\n const promoNotice = (): string | null =>\n promoApplied()?.valid && pricing().offer ? OFFER_BEATS_PROMO_NOTICE : null;\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 // The base the promo will actually be applied to. For a savings member\n // that is the savings price, not list: the server discounts the\n // savings-substituted subtotal at checkout, so quoting off list would\n // show a percentage promo as a bigger saving than it is (10% of $399\n // displayed, 10% of $280 charged). Same rule as savingsBaseCents — keep\n // the two in step.\n subtotalCents: savingsBaseCents(),\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 // Phone stays optional here; when one is given it has to be dialable.\n if (phone().trim() && !isValidUsPhone(phone())) return PHONE_ERROR;\n } else if (s === 1) {\n return firstAddressError(validateAddress(addr.shipping(), '', { enforceAvailability: true }));\n } else if (s === 2) {\n // Hosted fields (NMI): the card is in the gateway's iframes, which check it on submit.\n if (!accept.hostedFields()) {\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 }\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 let awaitingAvailability = false;\n\n async function submit() {\n // Never charge (or create the Rx) for an item Apex just told us can't be\n // filled at this shipping address — checked before tokenizing so a\n // blocked patient never enters a card for nothing.\n // Held across the wait: a second click while the check is pending must\n // not start a second submit (the submitting flag is only set below).\n if (awaitingAvailability) return;\n // The Account step can be stale by now (a reload drops the password, a\n // session can end): re-check it and send the patient back to it, rather\n // than tokenizing a card for a submit the server will refuse.\n const accountErr = validateStep(0);\n if (accountErr) {\n setStep(0);\n setError(accountErr);\n return;\n }\n awaitingAvailability = true;\n try {\n await availability.settled();\n } finally {\n awaitingAvailability = false;\n }\n if (availability.blocking()) {\n setError(catalogUnavailableMessage(options.pricing.productName, state()));\n return;\n }\n\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 billing: effectiveBillingAddress(),\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 const smsGrant = smsConsent.grant();\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 // Same PATCH as the phone, so the server applies the number first and\n // the grant covers it. Alongside other fields a refused grant is a\n // note in the reply, never a failed intake.\n ...(smsGrant ? { smsConsent: { ...smsGrant, source: 'intake' as const } } : {}),\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 const savingsMemberId = options.savingsMemberId?.() || undefined;\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 ...(savingsMemberId ? { savingsMemberId } : {}),\n ...(smsGrant ? { smsConsent: smsGrant } : {}),\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 smsConsent,\n\n address: addr,\n availability,\n\n cardNumber: cardNumberRaw,\n setCardNumber: (v) => setCardNumberRaw(formatCardNumber(v)),\n expiry: expiryRaw,\n setExpiry: (v) => setExpiryRaw(formatExpiry(v)),\n cvv: cvvRaw,\n hostedCardFields: accept.hostedFields,\n registerCardField: accept.registerHostedField,\n setCvv: (v) => setCvvRaw(formatCvv(v)),\n\n promoCode,\n setPromoCode,\n promoValidating,\n promoError,\n promoApplied,\n applyPromo,\n clearPromo,\n promoNotice,\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 core's cart store by default and to a\n// site's own basket via `options.source` (see CartSource).\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 * Where the basket lives, for a site that has no catalog cart.\n *\n * Abandonment is not a storefront-only event: a single-subscription partner\n * (mytruemeds, axiom-md) lets a patient choose a medication and a dose and\n * then walk away from the payment step, which is the same loss and the same\n * recoverable moment — but the selection lives in that site's own intake\n * state, not in `stores/cart`, so the default wiring watches an empty store\n * forever.\n *\n * Read and write are one option rather than two on purpose: a site that\n * supplies its own items must also say how a resumed cart gets back in, or\n * the `?cart=` link would rebuild into core's cart store, which such a site\n * never renders. Omit entirely to drive core's cart store (the default).\n */\n source?: CartSource;\n}\n\n/** A site's own basket, in the shape the wire already speaks. */\nexport interface CartSource {\n /** Current lines. Must be reactive — this is tracked. */\n items: () => CartSnapshotLine[];\n /** Promo code riding on the cart, if the site has one. */\n promoCode?: () => string | null | undefined;\n /**\n * Rebuild the site's own state from a cart resumed off a `?cart=` link. The\n * lines are re-priced against today's catalog; the promo code (if any) is\n * NOT re-validated for a custom source — `validateResumedPromo` does that\n * for a site that wants it.\n */\n restore: (cart: ResumedCart) => void;\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/**\n * Who a resumed cart is handed to. Default rebuilds core's cart store; a site\n * with its own basket claims it in `startCartCapture` (synchronously, before\n * anything can await), so a later `restoreCartFromLink()` reaches the right\n * place.\n */\nlet restoreTarget: ((cart: ResumedCart) => void) | null = null;\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\nexport interface ValidatedResumedPromo {\n code: string;\n discountType: 'percent' | 'fixed';\n discountValueCents: number;\n discountCents: number;\n}\n\n/**\n * Re-check the promo code a resumed cart was carrying, against today's rules\n * and today's lines. Null when there was no code, when it no longer validates,\n * or when the check itself fails — the cart is restored either way.\n *\n * Exported because a site with its own `CartSource` needs the same guarantee\n * without core's cart store: showing a discount checkout won't honor is worse\n * than showing none.\n */\nexport async function validateResumedPromo(resumed: ResumedCart): Promise<ValidatedResumedPromo | null> {\n if (!resumed.promoCode) return null;\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 null;\n return {\n code: res.promoCode.code,\n discountType: res.promoCode.discountType,\n discountValueCents: res.promoCode.discountValueCents,\n discountCents: res.discountCents ?? 0,\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Re-apply the promo code the cart was carrying when it was abandoned, to\n * core's cart store. Re-VALIDATED, never trusted: a code can expire, get\n * revoked, or stop covering the products still in the cart between abandonment\n * and return.\n */\nasync function restorePromo(resumed: ResumedCart): Promise<void> {\n const promo = await validateResumedPromo(resumed);\n if (promo) cartStore.setPromo(promo);\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 if (restoreTarget) {\n // A site with its own basket. It owns the promo too — core has no store to\n // put one in — so `validateResumedPromo` is left for it to call.\n restoreTarget(resumed);\n } else {\n applyResumedCart(resumed);\n void restorePromo(resumed);\n }\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 // Claim the restore BEFORE anything awaits, so a site that calls\n // `restoreCartFromLink()` itself can't race core's cart store into place.\n restoreTarget = opts.source?.restore ?? null;\n\n // Core's cart store is just the default source; the wire shape is the same\n // either way, so everything below reads lines, not cart items.\n const source: CartSource = opts.source ?? {\n items: () => toSnapshotLines(cartStore.items()),\n promoCode: () => cartStore.appliedPromo()?.code ?? null,\n restore: applyResumedCart,\n };\n\n const debounceMs = opts.debounceMs ?? 2000;\n let enabled: boolean | null = null;\n let pending: CartSnapshotLine[] | 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,\n promoCode: source.promoCode?.() ?? 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 source.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 restoreTarget = null;\n running = false;\n };\n}\n"]}
|