@apextelemed/partner-core 0.17.0-dev.51 → 0.17.0-dev.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/index.d.ts +1 -1
- package/dist/api/index.js +3 -3
- package/dist/api/index.jsx +5 -3
- package/dist/chunk/{ANKLNWGB.js → 2HDMTWLH.js} +6 -6
- package/dist/chunk/{ANKLNWGB.js.map → 2HDMTWLH.js.map} +1 -1
- package/dist/chunk/{PHSZOZVK.jsx → 37UEVJEC.jsx} +12 -1
- package/dist/chunk/{HM5L6J62.jsx → 5HQAA4UO.jsx} +2 -2
- package/dist/chunk/{Z6PDUPOU.js → 6V7RVUXX.js} +3 -3
- package/dist/chunk/{Z6PDUPOU.js.map → 6V7RVUXX.js.map} +1 -1
- package/dist/chunk/{AXXQJC6M.js → A6FJGQIS.js} +3 -3
- package/dist/chunk/{AXXQJC6M.js.map → A6FJGQIS.js.map} +1 -1
- package/dist/chunk/{545PPOE5.jsx → BJXD2NQQ.jsx} +2 -2
- package/dist/chunk/{LFSDVMIY.js → BYDMO5RM.js} +208 -6
- package/dist/chunk/BYDMO5RM.js.map +1 -0
- package/dist/chunk/{3SPMZ7FK.jsx → FTZ52PMM.jsx} +2 -2
- package/dist/chunk/{TFA64PLK.js → FXRGPBYU.js} +3 -3
- package/dist/chunk/{TFA64PLK.js.map → FXRGPBYU.js.map} +1 -1
- package/dist/chunk/{P4NWFY4T.jsx → IQDVS3XA.jsx} +5 -5
- package/dist/chunk/{L4DFQMYM.js → O7H7DAWO.js} +959 -683
- package/dist/chunk/O7H7DAWO.js.map +1 -0
- package/dist/chunk/{ICGZXU3R.js → RDZDD5UW.js} +13 -3
- package/dist/chunk/RDZDD5UW.js.map +1 -0
- package/dist/chunk/{OZZGMI6C.jsx → T37L6JE6.jsx} +1188 -999
- package/dist/chunk/{VE5ACNFB.jsx → TLDELI22.jsx} +220 -5
- package/dist/{client-Baf1FSEp.d.ts → client-BLh8hFAu.d.ts} +35 -1
- package/dist/flows/index.d.ts +142 -2
- package/dist/flows/index.js +6 -6
- package/dist/flows/index.jsx +24 -8
- package/dist/index/index.d.ts +2 -2
- package/dist/index/index.js +7 -7
- package/dist/index/index.jsx +27 -9
- package/dist/pages/index.d.ts +1 -1
- package/dist/pages/index.js +5 -5
- package/dist/pages/index.jsx +5 -5
- package/dist/stores/index.d.ts +1 -1
- package/dist/stores/index.js +2 -2
- package/dist/stores/index.jsx +2 -2
- package/package.json +1 -1
- package/dist/chunk/ICGZXU3R.js.map +0 -1
- package/dist/chunk/L4DFQMYM.js.map +0 -1
- package/dist/chunk/LFSDVMIY.js.map +0 -1
package/dist/api/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as AddPharmacyBody, a as AddPharmacyDoseMatch, b as AddPharmacyDoseOption, c as AddPharmacyFinding, d as AddPharmacyMatchQuestion, e as AddPharmacyMatchSource, f as AddPharmacyPlan, g as AddPharmacyPrice, h as AddPharmacyResult, i as AddPharmacyStrengthAfter, j as AddPharmacyStrengthBefore, k as AddressVerifyResult, l as AdminApexDrug, m as AdminApexItemStatus, n as AdminBillingAttempt, o as AdminCategory, p as AdminCategoryInput, q as AdminCategoryUpdate, r as AdminCustomer, s as AdminCustomerFacts, t as AdminCustomerFunnel, u as AdminCustomerListParams, v as AdminCustomerOverview, w as AdminCustomerProfile, x as AdminCustomerRequest, y as AdminCustomerRow, z as AdminCustomerSupport, B as AdminCustomerSupportThread, C as AdminDashboardStats, D as AdminLifecycle, E as AdminLifecycleBucket, F as AdminListParams, G as AdminOffer, H as AdminOfferBase, I as AdminOfferGrant, J as AdminOfferGrantBase, K as AdminOfferInput, L as AdminOrderSummary, M as AdminOrphanReason, N as AdminOrphanedDosePrice, O as AdminPayment, P as AdminPaymentDetail, Q as AdminProduct, R as AdminProductOverlayField, S as AdminProductPharmacy, T as AdminProductStrength, U as AdminPromoCode, V as AdminPromoCodeInput, W as AdminRecurringPricePoint, X as AdminRecurringRevenue, Y as AdminRefundResult, Z as AdminSale, _ as AdminSaleInput, $ as AdminScheduledRefund, a0 as AdminScheduledRefundProblem, a1 as AdminSubscription, a2 as AdminSubscriptionDetail, a3 as AdminSubscriptionPatch, a4 as AdminSubscriptionWriteResult, a5 as AdminSupportCustomer, a6 as AdminSupportStats, a7 as AdminSupportThread, a8 as AdminWebhookEvent, a9 as Affiliate, aa as AffiliateAuthTokens, ab as AffiliateClickRecord, ac as AffiliateConversion, ad as AffiliateDashboardLinks, ae as AffiliateDashboardProfile, af as AffiliateDashboardStats, ag as AffiliateDownlineMember, ah as AffiliateEarningsBreakdown, ai as AffiliatePaymentMethod, aj as AffiliateProgram, ak as AffiliateRegisterInput, al as AffiliateRegisterResponse, am as AffiliateSession, an as AffiliateStatsResponse, ao as AffiliateStatus, ap as AffiliateTrackResponse, aq as ApiError, ar as ApiResponse, as as AttributionMethod, at as AuthTokens, au as BillingReminderSettings, av as CatalogAvailabilityItem, aw as CatalogAvailabilityReason, ax as CatalogAvailabilityResult, ay as CatalogClassification, az as CatalogConversionChoice, aA as CatalogConversionCommitResult, aB as CatalogConversionDose, aC as CatalogConversionDoseMatch, aD as CatalogConversionFinding, aE as CatalogConversionPointers, aF as CatalogConversionPrepareResult, aG as CatalogConversionPreview, aH as CatalogConversionRun, aI as CatalogConversionSource, aJ as CatalogConversionStage, aK as CatalogConversionTarget, aL as CatalogConversionUndoOptions, aM as CatalogConversionUndoResult, aN as CatalogDose, aO as CatalogDoseInput, aP as CatalogDoseModel, aQ as CatalogDoseSuggestion, aR as CatalogDoseSuggestions, aS as CatalogEquivalentSuggestions, aT as CatalogFulfillment, aU as CatalogFulfillmentInput, aV as CatalogItem, aW as CatalogItemInput, aX as CatalogMappableDrug, aY as CatalogMatrixCell, aZ as CatalogProduct, a_ as CatalogReadiness, a$ as CategoryMetadata, b0 as CheckoutAddress, b1 as CheckoutPayload, b2 as CheckoutResult, b3 as CommissionConfig, b4 as CommissionStatus, b5 as CompleteSurveyPayload, b6 as CreateAffiliatePayload, b7 as CreateAffiliateProgramPayload, b8 as CreateOrderPayload, b9 as CreateRequestPayload, ba as CreateSubscriptionPayload, bb as CustomTemplate, bc as CustomTemplateInput, bd as CustomerDiscountConfig, be as DeliveryInfo, bf as DiscountType, bg as EmailNotificationSettings, bh as EmailTemplatesMap, bi as LoginPayload, bj as MemberOffer, bk as MemberPrescriptionRequest, bl as MemberSurveyMode, bm as MemberSurveyResponseSummary, bn as MemberSurveyTranscript, bo as MemberSurveyTranscriptItem, bp as MemberSurveyTranscriptSection, bq as MembersMeResponse, br as OfferGrantState, bs as Order, bt as OrderItemInput, bu as PaginationParams, bv as PaymentCallbackPayload, bw as PaymentInitiatePayload, bx as PaymentType, by as PendingRenewalSurvey, bz as Placeholder, bA as PlaceholderKind, bB as ProductSaleSummary, bC as
|
|
1
|
+
export { A as AddPharmacyBody, a as AddPharmacyDoseMatch, b as AddPharmacyDoseOption, c as AddPharmacyFinding, d as AddPharmacyMatchQuestion, e as AddPharmacyMatchSource, f as AddPharmacyPlan, g as AddPharmacyPrice, h as AddPharmacyResult, i as AddPharmacyStrengthAfter, j as AddPharmacyStrengthBefore, k as AddressVerifyResult, l as AdminApexDrug, m as AdminApexItemStatus, n as AdminBillingAttempt, o as AdminCategory, p as AdminCategoryInput, q as AdminCategoryUpdate, r as AdminCustomer, s as AdminCustomerFacts, t as AdminCustomerFunnel, u as AdminCustomerListParams, v as AdminCustomerOverview, w as AdminCustomerProfile, x as AdminCustomerRequest, y as AdminCustomerRow, z as AdminCustomerSupport, B as AdminCustomerSupportThread, C as AdminDashboardStats, D as AdminLifecycle, E as AdminLifecycleBucket, F as AdminListParams, G as AdminOffer, H as AdminOfferBase, I as AdminOfferGrant, J as AdminOfferGrantBase, K as AdminOfferInput, L as AdminOrderSummary, M as AdminOrphanReason, N as AdminOrphanedDosePrice, O as AdminPayment, P as AdminPaymentDetail, Q as AdminProduct, R as AdminProductOverlayField, S as AdminProductPharmacy, T as AdminProductStrength, U as AdminPromoCode, V as AdminPromoCodeInput, W as AdminRecurringPricePoint, X as AdminRecurringRevenue, Y as AdminRefundResult, Z as AdminSale, _ as AdminSaleInput, $ as AdminScheduledRefund, a0 as AdminScheduledRefundProblem, a1 as AdminSubscription, a2 as AdminSubscriptionDetail, a3 as AdminSubscriptionPatch, a4 as AdminSubscriptionWriteResult, a5 as AdminSupportCustomer, a6 as AdminSupportStats, a7 as AdminSupportThread, a8 as AdminWebhookEvent, a9 as Affiliate, aa as AffiliateAuthTokens, ab as AffiliateClickRecord, ac as AffiliateConversion, ad as AffiliateDashboardLinks, ae as AffiliateDashboardProfile, af as AffiliateDashboardStats, ag as AffiliateDownlineMember, ah as AffiliateEarningsBreakdown, ai as AffiliatePaymentMethod, aj as AffiliateProgram, ak as AffiliateRegisterInput, al as AffiliateRegisterResponse, am as AffiliateSession, an as AffiliateStatsResponse, ao as AffiliateStatus, ap as AffiliateTrackResponse, aq as ApiError, ar as ApiResponse, as as AttributionMethod, at as AuthTokens, au as BillingReminderSettings, av as CatalogAvailabilityItem, aw as CatalogAvailabilityReason, ax as CatalogAvailabilityResult, ay as CatalogClassification, az as CatalogConversionChoice, aA as CatalogConversionCommitResult, aB as CatalogConversionDose, aC as CatalogConversionDoseMatch, aD as CatalogConversionFinding, aE as CatalogConversionPointers, aF as CatalogConversionPrepareResult, aG as CatalogConversionPreview, aH as CatalogConversionRun, aI as CatalogConversionSource, aJ as CatalogConversionStage, aK as CatalogConversionTarget, aL as CatalogConversionUndoOptions, aM as CatalogConversionUndoResult, aN as CatalogDose, aO as CatalogDoseInput, aP as CatalogDoseModel, aQ as CatalogDoseSuggestion, aR as CatalogDoseSuggestions, aS as CatalogEquivalentSuggestions, aT as CatalogFulfillment, aU as CatalogFulfillmentInput, aV as CatalogItem, aW as CatalogItemInput, aX as CatalogMappableDrug, aY as CatalogMatrixCell, aZ as CatalogProduct, a_ as CatalogReadiness, a$ as CategoryMetadata, b0 as CheckoutAddress, b1 as CheckoutPayload, b2 as CheckoutResult, b3 as CommissionConfig, b4 as CommissionStatus, b5 as CompleteSurveyPayload, b6 as CreateAffiliatePayload, b7 as CreateAffiliateProgramPayload, b8 as CreateOrderPayload, b9 as CreateRequestPayload, ba as CreateSubscriptionPayload, bb as CustomTemplate, bc as CustomTemplateInput, bd as CustomerDiscountConfig, be as DeliveryInfo, bf as DiscountType, bg as EmailNotificationSettings, bh as EmailTemplatesMap, bi as LoginPayload, bj as MemberOffer, bk as MemberPrescriptionRequest, bl as MemberSurveyMode, bm as MemberSurveyResponseSummary, bn as MemberSurveyTranscript, bo as MemberSurveyTranscriptItem, bp as MemberSurveyTranscriptSection, bq as MembersMeResponse, br as OfferGrantState, bs as Order, bt as OrderItemInput, bu as PaginationParams, bv as PaymentCallbackPayload, bw as PaymentInitiatePayload, bx as PaymentType, by as PendingRenewalSurvey, bz as Placeholder, bA as PlaceholderKind, bB as ProductSaleSummary, bC as ProductStrengthMatches, bD as PromoValidationResponse, bE as PublicCategory, bF as RegisterAndSubscribePayload, bG as RegisterPayload, bH as RenewalStatus, bI as SUPPORT_ATTACHMENT_MAX_BYTES, bJ as SUPPORT_ATTACHMENT_MIME_TYPES, bK as SelectDrugPayload, bL as SendMessagePayload, bM as SendToPharmacyPayload, bN as StrengthMatchBody, bO as StrengthMatchDoseOption, bP as StrengthMatchRow, bQ as SubscriptionPreview, bR as SubscriptionPreviewLine, bS as SubscriptionPreviewPayload, bT as SupportAttachment, bU as SupportChannel, bV as SupportChannelSettings, bW as SupportMessage, bX as SupportRealtimeToken, bY as SupportThread, bZ as SupportThreadCategory, b_ as SupportThreadStatus, b$ as SurveySubmitPayload, c0 as TemplatePlaceholdersMap, c1 as TemplateText, c2 as TenantFeature, c3 as TenantFeatureAccess, c4 as TokenTrackName, c5 as UpdateAffiliatePayload, c6 as UpdateAffiliateProgramPayload, c7 as UpdatePaymentMethodPayload, c8 as UpdateProfilePayload, c9 as User, ca as addressesApi, cb as adminAffiliatesApi, cc as adminApi, cd as adminCatalogApi, ce as adminCatalogConversionApi, cf as adminProductPharmaciesApi, cg as adminProductStrengthMatchesApi, ch as affiliateAuthStorageKey, ci as affiliatePortalApi, cj as apexApi, ck as apiFetch, cl as authApi, cm as authStorageKey, cn as catalogApi, co as clearAffiliateTokens, cp as clearTokens, cq as getAffiliateTokens, cr as getTokens, cs as membersApi, ct as messagesApi, cu as newIdempotencyKey, cv as offersApi, cw as onTokensCleared, cx as ordersApi, cy as paymentsApi, cz as productsApi, cA as promoCodesApi, cB as setAffiliateTokens, cC as setTokens, cD as subscriptionsApi, cE as supportApi, cF as usersApi } from '../client-BLh8hFAu.js';
|
|
2
2
|
export { EmbedApiError as ApexV2ApiError, EmbedApiClient, EmbedApiClientOptions, EmbedApiError, EmbedEvent, EmbedEventType, FetchLike, PatientInfo, V2Answer, V2ComposedSurvey, V2DrugResult, V2QualificationResult, V2Question, V2QuestionOption, V2Section, V2Step, V2SubmitResult, V2VisibilityCondition, createEmbedApiClient, disqualificationReasonText, disqualifiedDrugIds, qualifiedDrugIds } from '@apextelemed/survey-core';
|
|
3
3
|
export { C as CartCaptureConfig, a as CartSnapshotLine, F as FunnelConfig, b as FunnelDraftPayload, R as ResumedCart, c as ResumedCartLine, d as ResumedDraft, e as adoptCartId, f as adoptFunnelSessionId, g as captureAuthHeader, h as cartId, i as fetchCartConfig, j as fetchFunnelConfig, k as fetchResumedCart, l as fetchResumedDraft, m as funnelSessionId, p as peekFunnelSessionId, n as postCartSnapshot, o as postFunnelEvent, r as readCartToken, q as readResumeToken, s as resetCartConfigCache, t as resetCartId, u as resetFunnelConfigCache, v as saveFunnelDraft, w as stripCartToken, x as stripResumeToken } from '../cart-BwUwSzWh.js';
|
|
4
4
|
|
package/dist/api/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import '../chunk/JSHO46VZ.js';
|
|
2
|
-
export { adoptCartId, capturePromoCode, cartId, clearPromoCode, fetchCartConfig, fetchResumedCart, postCartSnapshot, readCartToken, readPromoCode, resetCartConfigCache, resetCartId, stripCartToken } from '../chunk/
|
|
2
|
+
export { adoptCartId, capturePromoCode, cartId, clearPromoCode, fetchCartConfig, fetchResumedCart, postCartSnapshot, readCartToken, readPromoCode, resetCartConfigCache, resetCartId, stripCartToken } from '../chunk/FXRGPBYU.js';
|
|
3
3
|
export { EmbedApiError2 as ApexV2ApiError, EmbedApiError, createEmbedApiClient, disqualificationReasonText, disqualifiedDrugIds, qualifiedDrugIds } from '../chunk/LZWA44KD.js';
|
|
4
|
-
export { adoptFunnelSessionId, captureAuthHeader, fetchFunnelConfig, fetchResumedDraft, funnelSessionId, peekFunnelSessionId, postFunnelEvent, readResumeToken, resetFunnelConfigCache, saveFunnelDraft, stripResumeToken } from '../chunk/
|
|
5
|
-
export { ApiError, SUPPORT_ATTACHMENT_MAX_BYTES, SUPPORT_ATTACHMENT_MIME_TYPES, addressesApi, adminAffiliatesApi, adminApi, adminCatalogApi, adminCatalogConversionApi, adminProductPharmaciesApi, affiliateAuthStorageKey, affiliatePortalApi, apexApi, apiFetch, authApi, authStorageKey, captureAffiliateRef, catalogApi, clearAffiliateRef, clearAffiliateTokens, clearTokens, getAffiliateTokens, getTokens, membersApi, messagesApi, newIdempotencyKey, offersApi, onTokensCleared, ordersApi, paymentsApi, productsApi, promoCodesApi, readAffiliateRef, setAffiliateTokens, setTokens, subscriptionsApi, supportApi, usersApi } from '../chunk/
|
|
4
|
+
export { adoptFunnelSessionId, captureAuthHeader, fetchFunnelConfig, fetchResumedDraft, funnelSessionId, peekFunnelSessionId, postFunnelEvent, readResumeToken, resetFunnelConfigCache, saveFunnelDraft, stripResumeToken } from '../chunk/6V7RVUXX.js';
|
|
5
|
+
export { ApiError, SUPPORT_ATTACHMENT_MAX_BYTES, SUPPORT_ATTACHMENT_MIME_TYPES, addressesApi, adminAffiliatesApi, adminApi, adminCatalogApi, adminCatalogConversionApi, adminProductPharmaciesApi, adminProductStrengthMatchesApi, affiliateAuthStorageKey, affiliatePortalApi, apexApi, apiFetch, authApi, authStorageKey, captureAffiliateRef, catalogApi, clearAffiliateRef, clearAffiliateTokens, clearTokens, getAffiliateTokens, getTokens, membersApi, messagesApi, newIdempotencyKey, offersApi, onTokensCleared, ordersApi, paymentsApi, productsApi, promoCodesApi, readAffiliateRef, setAffiliateTokens, setTokens, subscriptionsApi, supportApi, usersApi } from '../chunk/RDZDD5UW.js';
|
|
6
6
|
import '../chunk/2IFPDU4D.js';
|
|
7
7
|
//# sourceMappingURL=index.js.map
|
|
8
8
|
//# sourceMappingURL=index.js.map
|
package/dist/api/index.jsx
CHANGED
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
resetCartConfigCache,
|
|
13
13
|
resetCartId,
|
|
14
14
|
stripCartToken
|
|
15
|
-
} from "../chunk/
|
|
15
|
+
} from "../chunk/FTZ52PMM.jsx";
|
|
16
16
|
import {
|
|
17
17
|
EmbedApiError,
|
|
18
18
|
EmbedApiError2,
|
|
@@ -33,7 +33,7 @@ import {
|
|
|
33
33
|
resetFunnelConfigCache,
|
|
34
34
|
saveFunnelDraft,
|
|
35
35
|
stripResumeToken
|
|
36
|
-
} from "../chunk/
|
|
36
|
+
} from "../chunk/5HQAA4UO.jsx";
|
|
37
37
|
import {
|
|
38
38
|
ApiError,
|
|
39
39
|
SUPPORT_ATTACHMENT_MAX_BYTES,
|
|
@@ -44,6 +44,7 @@ import {
|
|
|
44
44
|
adminCatalogApi,
|
|
45
45
|
adminCatalogConversionApi,
|
|
46
46
|
adminProductPharmaciesApi,
|
|
47
|
+
adminProductStrengthMatchesApi,
|
|
47
48
|
affiliateAuthStorageKey,
|
|
48
49
|
affiliatePortalApi,
|
|
49
50
|
apexApi,
|
|
@@ -72,7 +73,7 @@ import {
|
|
|
72
73
|
subscriptionsApi,
|
|
73
74
|
supportApi,
|
|
74
75
|
usersApi
|
|
75
|
-
} from "../chunk/
|
|
76
|
+
} from "../chunk/37UEVJEC.jsx";
|
|
76
77
|
import "../chunk/QVZ7BRNO.jsx";
|
|
77
78
|
export {
|
|
78
79
|
EmbedApiError2 as ApexV2ApiError,
|
|
@@ -86,6 +87,7 @@ export {
|
|
|
86
87
|
adminCatalogApi,
|
|
87
88
|
adminCatalogConversionApi,
|
|
88
89
|
adminProductPharmaciesApi,
|
|
90
|
+
adminProductStrengthMatchesApi,
|
|
89
91
|
adoptCartId,
|
|
90
92
|
adoptFunnelSessionId,
|
|
91
93
|
affiliateAuthStorageKey,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { readPromoCode, clearPromoCode, readCartToken, fetchResumedCart, stripCartToken, adoptCartId, fetchCartConfig, postCartSnapshot, resetCartId } from './
|
|
2
|
-
import { useCardTokenizer, useAddressPair, useCatalogAvailability, isLive, formatCvv, formatExpiry, formatCardNumber, bestOfferDiscount, offerBeatsPromo, catalogUnavailableMessage, firstAddressError, validateAddress } from './
|
|
3
|
-
import { auth_default, cart_default } from './
|
|
4
|
-
import { promoCodesApi, subscriptionsApi, offersApi, newIdempotencyKey, usersApi, ApiError } from './
|
|
1
|
+
import { readPromoCode, clearPromoCode, readCartToken, fetchResumedCart, stripCartToken, adoptCartId, fetchCartConfig, postCartSnapshot, resetCartId } from './FXRGPBYU.js';
|
|
2
|
+
import { useCardTokenizer, useAddressPair, useCatalogAvailability, isLive, formatCvv, formatExpiry, formatCardNumber, bestOfferDiscount, offerBeatsPromo, catalogUnavailableMessage, firstAddressError, validateAddress } from './BYDMO5RM.js';
|
|
3
|
+
import { auth_default, cart_default } from './A6FJGQIS.js';
|
|
4
|
+
import { promoCodesApi, subscriptionsApi, offersApi, newIdempotencyKey, usersApi, ApiError } from './RDZDD5UW.js';
|
|
5
5
|
import { getConfig } from './2IFPDU4D.js';
|
|
6
6
|
import { createSignal, onMount, createEffect, on, createRoot } from 'solid-js';
|
|
7
7
|
|
|
@@ -603,5 +603,5 @@ function startCartCapture(opts = {}) {
|
|
|
603
603
|
}
|
|
604
604
|
|
|
605
605
|
export { OFFER_BEATS_PROMO_NOTICE, restoreCartFromLink, startCartCapture, useSubscriptionIntakeFlow, validateResumedPromo };
|
|
606
|
-
//# sourceMappingURL=
|
|
607
|
-
//# sourceMappingURL=
|
|
606
|
+
//# sourceMappingURL=2HDMTWLH.js.map
|
|
607
|
+
//# sourceMappingURL=2HDMTWLH.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/flows/subscriptionIntake.ts","../../src/flows/cartCapture.ts"],"names":["createEffect","on"],"mappings":";;;;;;;AAwBA,IAAM,YAAA,GAAe,CAAA,GAAI,EAAA,GAAK,IAAA,GAAO,GAAA;AACrC,IAAM,mBAAA,GAAsB,CAAA;AAoB5B,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,GAAM,YAAA,CAAa,OAAA,CAAQ,QAAA,EAAU,CAAA;AAC3C,IAAA,IAAI,CAAC,GAAA,EAAK,OAAO,EAAC;AAClB,IAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC7B,IAAA,IAAI,OAAO,OAAA,IAAW,IAAA,CAAK,KAAI,GAAI,MAAA,CAAO,UAAU,YAAA,EAAc;AAChE,MAAA,YAAA,CAAa,UAAA,CAAW,UAAU,CAAA;AAClC,MAAA,OAAO,EAAC;AAAA,IACV;AACA,IAAA,OAAO,UAAU,EAAC;AAAA,EACpB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACF;AAEA,SAAS,UAAU,KAAA,EAAoB;AACrC,EAAA,IAAI;AACF,IAAA,YAAA,CAAa,OAAA,CAAQ,QAAA,EAAS,EAAG,IAAA,CAAK,SAAA,CAAU,EAAE,GAAG,KAAA,EAAO,OAAA,EAAS,IAAA,CAAK,GAAA,EAAI,EAAG,CAAC,CAAA;AAAA,EACpF,CAAA,CAA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AAA,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":"ANKLNWGB.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 } from './_internal/cardTokenizer';\nimport { formatCardNumber, formatExpiry, formatCvv } from './checkout';\nimport { getConfig } from '../config';\nimport { useAddressPair, validateAddress, firstAddressError, type AddressPair } from './address';\nimport { isLive } from './subscriptionStatus';\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 /** 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 // 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 // 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 const [step, setStep] = createSignal(Math.min(restored.step ?? 0, MAX_RESTORABLE_STEP));\n const [error, setError] = createSignal<string | null>(null);\n const [tokenizing, setTokenizing] = createSignal(false);\n const [submitting, setSubmitting] = createSignal(false);\n const [outcome, setOutcome] = createSignal<SubscriptionIntakeOutcome>({ kind: 'in_progress' });\n\n // Account\n const [firstName, setFirstName] = createSignal(restored.firstName ?? '');\n const [lastName, setLastName] = createSignal(restored.lastName ?? '');\n const [email, setEmail] = createSignal(restored.email ?? '');\n const [password, setPassword] = createSignal('');\n const [dateOfBirth, setDateOfBirth] = createSignal(restored.dateOfBirth ?? '');\n const [phone, setPhone] = createSignal(restored.phone ?? '');\n\n // Address (delivery/shipping + billing override), backed by the shared\n // useAddressPair so validation and the same-as / copy-on-uncheck behavior\n // match the checkout flow. The individual accessors below keep this flow's\n // public interface stable for consuming storefronts (no breaking change).\n const addr = useAddressPair({\n initialShipping: {\n street: restored.street ?? '',\n city: restored.city ?? '',\n state: restored.state ?? '',\n zip: restored.zip ?? '',\n },\n });\n\n // Internal shipping getters for draft persistence + payload building; the full\n // read/write surface (incl. billing override) is exposed as `address` below.\n const street = () => addr.shipping().street;\n const city = () => addr.shipping().city;\n const state = () => addr.shipping().state;\n const zip = () => addr.shipping().zip;\n\n // Effective billing address sent as the charge's billTo.\n const effectiveBillingAddress = () => {\n const b = addr.effectiveBilling();\n return { street: b.street.trim(), city: b.city.trim(), state: b.state, zip: b.zip.trim() };\n };\n\n // 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 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 } else if (s === 1) {\n return firstAddressError(validateAddress(addr.shipping(), '', { enforceAvailability: true }));\n } else if (s === 2) {\n if (!cardNumberRaw().trim()) return 'Card number is required.';\n if (!expiryRaw().trim()) return 'Expiration date is required.';\n if (!cvvRaw().trim()) return 'CVV is required.';\n }\n return null;\n }\n\n // ── Navigation ───────────────────────────────────────────────────\n\n async function next() {\n const err = validateStep(step());\n if (err) {\n setError(err);\n return;\n }\n setError(null);\n setStep((s) => s + 1);\n }\n\n function back() {\n setError(null);\n if (step() > 0) setStep((s) => s - 1);\n }\n\n // ── Submit (from Payment step) ──────────────────────────────────\n\n 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 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\n if (authStore.isAuthenticated()) {\n // Logged-in member (e.g. a savings member who created an account first):\n // subscribe their EXISTING account instead of creating a second one. The\n // account may be name-only, so first persist the profile entered during\n // intake, then create the subscription + Apex Rx on that account.\n await usersApi.updateProfile({\n firstName: firstName().trim(),\n lastName: lastName().trim(),\n dateOfBirth: dateOfBirth(),\n phone: phone().trim() || undefined,\n address1: street().trim(),\n city: city().trim(),\n state: state(),\n zip: zip().trim(),\n });\n\n const res = await subscriptionsApi.create({\n opaqueData: opaque,\n amountCents: finalPricing.baseCents,\n intervalDays: options.intervalDays ?? 30,\n billingAddress: effectiveBillingAddress(),\n products: [{\n productId: options.pricing.productId,\n productName: options.pricing.productName,\n quantity: 1,\n dosage: options.surveyResult.dosage,\n }],\n productId: options.pricing.productId,\n promoCode: promo?.valid ? promo.promoCode?.code : undefined,\n metadata: {\n drugId: options.surveyResult.drugId,\n selectedDosage: options.surveyResult.dosage,\n caseNotes: options.surveyResult.caseNotes,\n v2SurveyResponseId: options.surveyResult.v2SurveyResponseId,\n },\n }, { idempotencyKey });\n if ((res as ApiResponse).error) {\n throw new Error((res as ApiResponse).error || 'Subscription failed. Please try again.');\n }\n } else {\n 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 }, { idempotencyKey });\n }\n\n clearDraft();\n setOutcome({ kind: 'completed' });\n } catch (err) {\n // The server refused because this member already holds a live\n // subscription. Not an error the member can act on by retrying — nothing\n // is wrong with what they typed — so surface it as its own outcome and\n // let the host explain, rather than as a red banner over a form that will\n // never succeed. Draft cleared so a later legitimate intake (after a\n // cancellation) starts clean.\n if (err instanceof ApiError && err.code === 'SUBSCRIPTION_EXISTS') {\n clearDraft();\n setOutcome({ kind: 'already_subscribed' });\n return;\n }\n\n // A definitive rejection (4xx: decline, validation) means nothing was\n // committed — the next attempt is a NEW operation and must not be\n // deduped against this one, so rotate the key. An AMBIGUOUS failure\n // (connection dropped, 5xx) may have committed server-side: keep the key\n // so the retry collapses into the original instead of charging twice.\n const maybeCommitted = err instanceof ApiError && err.ambiguous;\n if (!maybeCommitted) setIdemKey(newIdempotencyKey());\n\n setError(err instanceof Error ? err.message : 'Registration failed. Please try again.');\n setOutcome({ kind: 'in_progress' });\n } finally {\n setSubmitting(false);\n }\n }\n\n return {\n step,\n stepCount: 3,\n next,\n back,\n\n outcome,\n error,\n submitting,\n tokenizing,\n tokenizerReady: accept.ready,\n acceptJsReady: accept.ready,\n tokenizerError: accept.error,\n acceptJsError: accept.error,\n\n firstName, setFirstName,\n lastName, setLastName,\n email, setEmail,\n password, setPassword,\n dateOfBirth, setDateOfBirth,\n phone, setPhone,\n\n address: addr,\n availability,\n\n cardNumber: cardNumberRaw,\n setCardNumber: (v) => setCardNumberRaw(formatCardNumber(v)),\n expiry: expiryRaw,\n setExpiry: (v) => setExpiryRaw(formatExpiry(v)),\n cvv: cvvRaw,\n setCvv: (v) => setCvvRaw(formatCvv(v)),\n\n promoCode,\n setPromoCode,\n promoValidating,\n promoError,\n promoApplied,\n applyPromo,\n clearPromo,\n 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"]}
|
|
1
|
+
{"version":3,"sources":["../../src/flows/subscriptionIntake.ts","../../src/flows/cartCapture.ts"],"names":["createEffect","on"],"mappings":";;;;;;;AAwBA,IAAM,YAAA,GAAe,CAAA,GAAI,EAAA,GAAK,IAAA,GAAO,GAAA;AACrC,IAAM,mBAAA,GAAsB,CAAA;AAoB5B,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,GAAM,YAAA,CAAa,OAAA,CAAQ,QAAA,EAAU,CAAA;AAC3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AACV,UAAA,IAAI,OAAA,KAAY,IAAA,EAAM,QAAA,CAAS,UAAU,CAAA;AAAA,QAC3C,CAAA;AAAA,QACA,EAAE,OAAO,IAAA;AAAK;AAChB,KACF;AACA,IAAA,OAAO,WAAA;AAAA,EACT,CAAC,CAAA;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":"2HDMTWLH.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 } from './_internal/cardTokenizer';\nimport { formatCardNumber, formatExpiry, formatCvv } from './checkout';\nimport { getConfig } from '../config';\nimport { useAddressPair, validateAddress, firstAddressError, type AddressPair } from './address';\nimport { isLive } from './subscriptionStatus';\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 /** 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 // 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 // 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 const [step, setStep] = createSignal(Math.min(restored.step ?? 0, MAX_RESTORABLE_STEP));\n const [error, setError] = createSignal<string | null>(null);\n const [tokenizing, setTokenizing] = createSignal(false);\n const [submitting, setSubmitting] = createSignal(false);\n const [outcome, setOutcome] = createSignal<SubscriptionIntakeOutcome>({ kind: 'in_progress' });\n\n // Account\n const [firstName, setFirstName] = createSignal(restored.firstName ?? '');\n const [lastName, setLastName] = createSignal(restored.lastName ?? '');\n const [email, setEmail] = createSignal(restored.email ?? '');\n const [password, setPassword] = createSignal('');\n const [dateOfBirth, setDateOfBirth] = createSignal(restored.dateOfBirth ?? '');\n const [phone, setPhone] = createSignal(restored.phone ?? '');\n\n // Address (delivery/shipping + billing override), backed by the shared\n // useAddressPair so validation and the same-as / copy-on-uncheck behavior\n // match the checkout flow. The individual accessors below keep this flow's\n // public interface stable for consuming storefronts (no breaking change).\n const addr = useAddressPair({\n initialShipping: {\n street: restored.street ?? '',\n city: restored.city ?? '',\n state: restored.state ?? '',\n zip: restored.zip ?? '',\n },\n });\n\n // Internal shipping getters for draft persistence + payload building; the full\n // read/write surface (incl. billing override) is exposed as `address` below.\n const street = () => addr.shipping().street;\n const city = () => addr.shipping().city;\n const state = () => addr.shipping().state;\n const zip = () => addr.shipping().zip;\n\n // Effective billing address sent as the charge's billTo.\n const effectiveBillingAddress = () => {\n const b = addr.effectiveBilling();\n return { street: b.street.trim(), city: b.city.trim(), state: b.state, zip: b.zip.trim() };\n };\n\n // 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 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 } else if (s === 1) {\n return firstAddressError(validateAddress(addr.shipping(), '', { enforceAvailability: true }));\n } else if (s === 2) {\n if (!cardNumberRaw().trim()) return 'Card number is required.';\n if (!expiryRaw().trim()) return 'Expiration date is required.';\n if (!cvvRaw().trim()) return 'CVV is required.';\n }\n return null;\n }\n\n // ── Navigation ───────────────────────────────────────────────────\n\n async function next() {\n const err = validateStep(step());\n if (err) {\n setError(err);\n return;\n }\n setError(null);\n setStep((s) => s + 1);\n }\n\n function back() {\n setError(null);\n if (step() > 0) setStep((s) => s - 1);\n }\n\n // ── Submit (from Payment step) ──────────────────────────────────\n\n 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 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\n if (authStore.isAuthenticated()) {\n // Logged-in member (e.g. a savings member who created an account first):\n // subscribe their EXISTING account instead of creating a second one. The\n // account may be name-only, so first persist the profile entered during\n // intake, then create the subscription + Apex Rx on that account.\n await usersApi.updateProfile({\n firstName: firstName().trim(),\n lastName: lastName().trim(),\n dateOfBirth: dateOfBirth(),\n phone: phone().trim() || undefined,\n address1: street().trim(),\n city: city().trim(),\n state: state(),\n zip: zip().trim(),\n });\n\n const res = await subscriptionsApi.create({\n opaqueData: opaque,\n amountCents: finalPricing.baseCents,\n intervalDays: options.intervalDays ?? 30,\n billingAddress: effectiveBillingAddress(),\n products: [{\n productId: options.pricing.productId,\n productName: options.pricing.productName,\n quantity: 1,\n dosage: options.surveyResult.dosage,\n }],\n productId: options.pricing.productId,\n promoCode: promo?.valid ? promo.promoCode?.code : undefined,\n metadata: {\n drugId: options.surveyResult.drugId,\n selectedDosage: options.surveyResult.dosage,\n caseNotes: options.surveyResult.caseNotes,\n v2SurveyResponseId: options.surveyResult.v2SurveyResponseId,\n },\n }, { idempotencyKey });\n if ((res as ApiResponse).error) {\n throw new Error((res as ApiResponse).error || 'Subscription failed. Please try again.');\n }\n } else {\n 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 }, { idempotencyKey });\n }\n\n clearDraft();\n setOutcome({ kind: 'completed' });\n } catch (err) {\n // The server refused because this member already holds a live\n // subscription. Not an error the member can act on by retrying — nothing\n // is wrong with what they typed — so surface it as its own outcome and\n // let the host explain, rather than as a red banner over a form that will\n // never succeed. Draft cleared so a later legitimate intake (after a\n // cancellation) starts clean.\n if (err instanceof ApiError && err.code === 'SUBSCRIPTION_EXISTS') {\n clearDraft();\n setOutcome({ kind: 'already_subscribed' });\n return;\n }\n\n // A definitive rejection (4xx: decline, validation) means nothing was\n // committed — the next attempt is a NEW operation and must not be\n // deduped against this one, so rotate the key. An AMBIGUOUS failure\n // (connection dropped, 5xx) may have committed server-side: keep the key\n // so the retry collapses into the original instead of charging twice.\n const maybeCommitted = err instanceof ApiError && err.ambiguous;\n if (!maybeCommitted) setIdemKey(newIdempotencyKey());\n\n setError(err instanceof Error ? err.message : 'Registration failed. Please try again.');\n setOutcome({ kind: 'in_progress' });\n } finally {\n setSubmitting(false);\n }\n }\n\n return {\n step,\n stepCount: 3,\n next,\n back,\n\n outcome,\n error,\n submitting,\n tokenizing,\n tokenizerReady: accept.ready,\n acceptJsReady: accept.ready,\n tokenizerError: accept.error,\n acceptJsError: accept.error,\n\n firstName, setFirstName,\n lastName, setLastName,\n email, setEmail,\n password, setPassword,\n dateOfBirth, setDateOfBirth,\n phone, setPhone,\n\n address: addr,\n availability,\n\n cardNumber: cardNumberRaw,\n setCardNumber: (v) => setCardNumberRaw(formatCardNumber(v)),\n expiry: expiryRaw,\n setExpiry: (v) => setExpiryRaw(formatExpiry(v)),\n cvv: cvvRaw,\n setCvv: (v) => setCvvRaw(formatCvv(v)),\n\n promoCode,\n setPromoCode,\n promoValidating,\n promoError,\n promoApplied,\n applyPromo,\n clearPromo,\n 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"]}
|
|
@@ -968,6 +968,16 @@ var adminProductPharmaciesApi = {
|
|
|
968
968
|
return post(productPharmaciesPath(productId), body);
|
|
969
969
|
}
|
|
970
970
|
};
|
|
971
|
+
var strengthMatchesPath = (productId) => `/admin/products/${encodeURIComponent(productId)}/strength-matches`;
|
|
972
|
+
var adminProductStrengthMatchesApi = {
|
|
973
|
+
list(productId) {
|
|
974
|
+
return apiFetch(strengthMatchesPath(productId));
|
|
975
|
+
},
|
|
976
|
+
/** Changes one match; answers with the fresh list. Rewrites the product's stored `dosagePrices`. */
|
|
977
|
+
set(productId, body) {
|
|
978
|
+
return put(strengthMatchesPath(productId), body);
|
|
979
|
+
}
|
|
980
|
+
};
|
|
971
981
|
var adminApi = {
|
|
972
982
|
getDashboard() {
|
|
973
983
|
return apiFetch("/admin/dashboard/stats");
|
|
@@ -1557,6 +1567,7 @@ export {
|
|
|
1557
1567
|
adminCatalogApi,
|
|
1558
1568
|
adminCatalogConversionApi,
|
|
1559
1569
|
adminProductPharmaciesApi,
|
|
1570
|
+
adminProductStrengthMatchesApi,
|
|
1560
1571
|
adminApi,
|
|
1561
1572
|
adminAffiliatesApi,
|
|
1562
1573
|
affiliateAuthStorageKey,
|
|
@@ -1565,4 +1576,4 @@ export {
|
|
|
1565
1576
|
clearAffiliateTokens,
|
|
1566
1577
|
affiliatePortalApi
|
|
1567
1578
|
};
|
|
1568
|
-
//# sourceMappingURL=
|
|
1579
|
+
//# sourceMappingURL=37UEVJEC.jsx.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
getTokens
|
|
3
|
-
} from "./
|
|
3
|
+
} from "./37UEVJEC.jsx";
|
|
4
4
|
import {
|
|
5
5
|
getConfig
|
|
6
6
|
} from "./QVZ7BRNO.jsx";
|
|
@@ -154,4 +154,4 @@ export {
|
|
|
154
154
|
readResumeToken,
|
|
155
155
|
stripResumeToken
|
|
156
156
|
};
|
|
157
|
-
//# sourceMappingURL=
|
|
157
|
+
//# sourceMappingURL=5HQAA4UO.jsx.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getTokens } from './
|
|
1
|
+
import { getTokens } from './RDZDD5UW.js';
|
|
2
2
|
import { getConfig } from './2IFPDU4D.js';
|
|
3
3
|
|
|
4
4
|
// src/api/funnel.ts
|
|
@@ -138,5 +138,5 @@ function stripResumeToken() {
|
|
|
138
138
|
}
|
|
139
139
|
|
|
140
140
|
export { adoptFunnelSessionId, captureAuthHeader, fetchFunnelConfig, fetchResumedDraft, funnelSessionId, peekFunnelSessionId, postFunnelEvent, readResumeToken, resetFunnelConfigCache, saveFunnelDraft, stripResumeToken };
|
|
141
|
-
//# sourceMappingURL=
|
|
142
|
-
//# sourceMappingURL=
|
|
141
|
+
//# sourceMappingURL=6V7RVUXX.js.map
|
|
142
|
+
//# sourceMappingURL=6V7RVUXX.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/api/funnel.ts"],"names":[],"mappings":";;;;AAmBA,IAAM,WAAyB,EAAE,SAAA,EAAW,OAAO,SAAA,EAAW,KAAA,EAAO,mBAAmB,KAAA,EAAM;AAE9F,IAAI,aAAA,GAA8C,IAAA;AAM3C,SAAS,iBAAA,GAA2C;AACzD,EAAA,IAAI,CAAC,aAAA,EAAe;AAClB,IAAA,aAAA,GAAA,CAAiB,YAAY;AAC3B,MAAA,IAAI;AACF,QAAA,MAAM,MAAM,SAAA,EAAU;AACtB,QAAA,MAAM,MAAM,MAAM,KAAA,CAAM,CAAA,EAAG,GAAA,CAAI,OAAO,CAAA,cAAA,CAAA,EAAkB;AAAA,UACtD,OAAA,EAAS,EAAE,cAAA,EAAgB,GAAA,CAAI,SAAA;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EAAE,CAAA;AAAA,MACtC,SAAS,IAAA,CAAK,OAAA;AAAA,MACd,SAAS,IAAA,CAAK,OAAA;AAAA,MACd,WAAW,OAAO,IAAA,CAAK,SAAA,KAAc,QAAA,GAAW,KAAK,SAAA,GAAY;AAAA,KACnE;AAAA,EACF,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAGO,SAAS,eAAA,GAAiC;AAC/C,EAAA,IAAI;AACF,IAAA,MAAM,KAAA,GAAQ,IAAI,eAAA,CAAgB,MAAA,CAAO,SAAS,MAAM,CAAA,CAAE,IAAI,QAAQ,CAAA;AACtE,IAAA,OAAO,KAAA,IAAS,KAAA,CAAM,MAAA,GAAS,CAAA,GAAI,KAAA,GAAQ,IAAA;AAAA,EAC7C,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAYO,SAAS,gBAAA,GAAyB;AACvC,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,MAAA,CAAO,SAAS,IAAI,CAAA;AACxC,IAAA,IAAI,CAAC,GAAA,CAAI,YAAA,CAAa,GAAA,CAAI,QAAQ,CAAA,EAAG;AACrC,IAAA,GAAA,CAAI,YAAA,CAAa,OAAO,QAAQ,CAAA;AAChC,IAAA,MAAA,CAAO,QAAQ,YAAA,CAAa,IAAI,EAAA,EAAI,GAAA,CAAI,UAAU,CAAA;AAAA,EACpD,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"Z6PDUPOU.js","sourcesContent":["import { getConfig } from '../config';\nimport { getTokens } from './client';\n\n// ── Funnel telemetry transport ──────────────────────────────────────────────\n//\n// Thin client for the-backend's abandoned-funnel capture endpoints:\n// GET /config/funnel → which capture features this tenant enabled\n// POST /funnel/events → survey-session telemetry sink\n//\n// Everything here is fire-and-forget and fail-silent: funnel capture is\n// marketing instrumentation, and it must never break or slow the survey.\n\nexport interface FunnelConfig {\n telemetry: boolean;\n emailGate: boolean;\n /** When true (tenant features.funnelEmailGateRequired), the gate offers no skip. */\n emailGateRequired: boolean;\n}\n\nconst DISABLED: FunnelConfig = { telemetry: false, emailGate: false, emailGateRequired: false };\n\nlet configPromise: Promise<FunnelConfig> | null = null;\n\n/**\n * The tenant's funnel-capture posture, fetched once per page load and cached.\n * Fails closed: any error reads as \"both off\".\n */\nexport function fetchFunnelConfig(): Promise<FunnelConfig> {\n if (!configPromise) {\n configPromise = (async () => {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/config/funnel`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return DISABLED;\n const body = (await res.json()) as Partial<FunnelConfig>;\n return {\n telemetry: body.telemetry === true,\n emailGate: body.emailGate === true,\n emailGateRequired: body.emailGateRequired === true,\n };\n } catch {\n return DISABLED;\n }\n })();\n }\n return configPromise;\n}\n\n/**\n * Continue an existing funnel session (resume-from-email): the emailed link\n * identifies the session that already holds this person's email and reminder\n * history, so adopting its id keeps everything on one row instead of forking a\n * new one that looks like a brand-new visitor.\n */\nexport function adoptFunnelSessionId(id: string): void {\n if (!id) return;\n try {\n sessionStorage.setItem(sessionIdKey(), id);\n } catch {\n /* storage unavailable — the session stays ephemeral */\n }\n}\n\n/** Test seam: forget the cached config so the next fetch re-resolves. */\nexport function resetFunnelConfigCache(): void {\n configPromise = null;\n}\n\nconst sessionIdKey = () => `${getConfig().storagePrefix}-funnel-session`;\n\n/**\n * Stable id for this survey session, minted on first use and kept in\n * sessionStorage — a refresh continues the same session (matching the survey\n * draft's resume behavior); a new tab or browser session starts a new one.\n */\nexport function funnelSessionId(): string {\n let id: string | null = null;\n try {\n id = sessionStorage.getItem(sessionIdKey());\n } catch {\n /* storage unavailable (private mode) — fall through to ephemeral id */\n }\n if (!id) {\n id =\n typeof crypto !== 'undefined' && 'randomUUID' in crypto\n ? crypto.randomUUID()\n : `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n try {\n sessionStorage.setItem(sessionIdKey(), id);\n } catch {\n /* ephemeral it is */\n }\n }\n return id;\n}\n\n/**\n * The current survey session id, or null — WITHOUT minting one.\n *\n * `funnelSessionId()` creates an id on first read, which is right for the\n * survey (asking means a survey is starting) and wrong for anything else. Cart\n * capture uses this to say \"if this shopper also has a survey session, here it\n * is\" — letting the backend borrow the email the gate already collected —\n * without conjuring survey sessions on a storefront that never runs one.\n */\nexport function peekFunnelSessionId(): string | null {\n try {\n return sessionStorage.getItem(sessionIdKey());\n } catch {\n return null;\n }\n}\n\n/**\n * The member's access token, when this browser has one.\n *\n * Read raw and never refreshed: these are fire-and-forget telemetry posts, and\n * a token refresh is a real network round-trip on the unload path. An expired\n * token is not a failure either — the sinks take it with `optionalAuth`, so a\n * stale one simply reads as an anonymous visitor, which is what we had before.\n */\nexport function captureAuthHeader(): Record<string, string> {\n try {\n const token = getTokens()?.accessToken;\n return token ? { Authorization: `Bearer ${token}` } : {};\n } catch {\n return {};\n }\n}\n\n/**\n * Fire-and-forget event post. `keepalive` lets the request survive a page\n * unload — which is exactly when the `abandoned` event is sent. (This is why\n * it's `fetch` and not `navigator.sendBeacon`: beacons can't carry the\n * X-Tenant-Key header the tenant-scoped mount requires — nor the bearer token\n * below.)\n *\n * The token identifies a signed-in member to the sink. Without it a member's\n * session is stored anonymously, and the pre-survey email gate — the only\n * other writer of a session's identity — is deliberately never shown to\n * someone already signed in, so their drop-off could never be attributed to\n * them. That is the whole population of a site where the account is created\n * before the questionnaire (savings-program signups, returning members\n * starting a second intake).\n */\nexport function postFunnelEvent(type: string, data?: Record<string, unknown>): void {\n try {\n const cfg = getConfig();\n void fetch(`${cfg.apiBase}/funnel/events`, {\n method: 'POST',\n keepalive: true,\n headers: {\n 'Content-Type': 'application/json',\n 'X-Tenant-Key': cfg.tenantKey,\n ...captureAuthHeader(),\n },\n body: JSON.stringify({ sessionId: funnelSessionId(), type, data }),\n }).catch(() => {});\n } catch {\n /* not configured yet — drop */\n }\n}\n\n// ── Survey drafts (cross-device resume) ─────────────────────────────────────\n\nexport interface FunnelDraftPayload {\n answers: Array<{ questionId: string; value: unknown }>;\n stepIndex: number;\n}\n\n/**\n * Save in-progress answers to Apex (through the-backend's embed proxy) and\n * return the draft id, so the next save updates the same row.\n *\n * Answers travel to the CLINICAL system — the partner backend stores only the\n * returned pointer. Returns null on any failure: a draft is best-effort, and\n * losing one costs a retype, never correctness.\n */\nexport async function saveFunnelDraft(\n draft: FunnelDraftPayload & { draftId?: string; drugIds?: string[]; templateId?: string; mode?: string },\n): Promise<string | null> {\n try {\n const cfg = getConfig();\n if (!cfg.apexEmbedApiBase) return null;\n const res = await fetch(`${cfg.apexEmbedApiBase}/v2/embed/surveys/drafts`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json', 'X-Tenant-Key': cfg.tenantKey },\n body: JSON.stringify(draft),\n });\n if (!res.ok) return null;\n const body = (await res.json()) as { draftId?: string };\n return body.draftId ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface ResumedDraft extends FunnelDraftPayload {\n sessionId: string;\n draftId: string;\n}\n\n/**\n * Exchange an emailed resume token for the saved answers.\n *\n * The token is the ONLY thing authorizing this read — the-backend verifies its\n * HMAC before fetching from Apex with credentials the browser never sees. A\n * 404 (expired, already submitted, tampered) resolves to null so the caller\n * simply starts a fresh survey.\n */\nexport async function fetchResumedDraft(token: string): Promise<ResumedDraft | null> {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/funnel/resume?token=${encodeURIComponent(token)}`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return null;\n const body = (await res.json()) as Partial<ResumedDraft>;\n if (!body.draftId || !Array.isArray(body.answers)) return null;\n return {\n sessionId: String(body.sessionId ?? ''),\n draftId: body.draftId,\n answers: body.answers,\n stepIndex: typeof body.stepIndex === 'number' ? body.stepIndex : 0,\n };\n } catch {\n return null;\n }\n}\n\n/** Read the `?resume=` token from the current URL. */\nexport function readResumeToken(): string | null {\n try {\n const token = new URLSearchParams(window.location.search).get('resume');\n return token && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Drop `?resume=` from the address bar once it has been redeemed.\n *\n * This token authorizes a read of someone's clinical answers, so leaving it in\n * the address bar is worse than leaving the cart's there: it gets bookmarked,\n * pasted into a support chat, or captured by whatever the patient's browser\n * syncs. The answers are mirrored into local storage on redemption, so a\n * refresh resumes from this device without it. History is replaced, not\n * pushed — the token was never a page.\n */\nexport function stripResumeToken(): void {\n try {\n const url = new URL(window.location.href);\n if (!url.searchParams.has('resume')) return;\n url.searchParams.delete('resume');\n window.history.replaceState({}, '', url.toString());\n } catch {\n /* no history API — leaving the param is harmless */\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/api/funnel.ts"],"names":[],"mappings":";;;;AAmBA,IAAM,WAAyB,EAAE,SAAA,EAAW,OAAO,SAAA,EAAW,KAAA,EAAO,mBAAmB,KAAA,EAAM;AAE9F,IAAI,aAAA,GAA8C,IAAA;AAM3C,SAAS,iBAAA,GAA2C;AACzD,EAAA,IAAI,CAAC,aAAA,EAAe;AAClB,IAAA,aAAA,GAAA,CAAiB,YAAY;AAC3B,MAAA,IAAI;AACF,QAAA,MAAM,MAAM,SAAA,EAAU;AACtB,QAAA,MAAM,MAAM,MAAM,KAAA,CAAM,CAAA,EAAG,GAAA,CAAI,OAAO,CAAA,cAAA,CAAA,EAAkB;AAAA,UACtD,OAAA,EAAS,EAAE,cAAA,EAAgB,GAAA,CAAI,SAAA;AAAU,SAC1C,CAAA;AACD,QAAA,IAAI,CAAC,GAAA,CAAI,EAAA,EAAI,OAAO,QAAA;AACpB,QAAA,MAAM,IAAA,GAAQ,MAAM,GAAA,CAAI,IAAA,EAAK;AAC7B,QAAA,OAAO;AAAA,UACL,SAAA,EAAW,KAAK,SAAA,KAAc,IAAA;AAAA,UAC9B,SAAA,EAAW,KAAK,SAAA,KAAc,IAAA;AAAA,UAC9B,iBAAA,EAAmB,KAAK,iBAAA,KAAsB;AAAA,SACh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,IAAI,eAAA,CAAgB,MAAA,CAAO,SAAS,MAAM,CAAA,CAAE,IAAI,QAAQ,CAAA;AACtE,IAAA,OAAO,KAAA,IAAS,KAAA,CAAM,MAAA,GAAS,CAAA,GAAI,KAAA,GAAQ,IAAA;AAAA,EAC7C,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAYO,SAAS,gBAAA,GAAyB;AACvC,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,MAAA,CAAO,SAAS,IAAI,CAAA;AACxC,IAAA,IAAI,CAAC,GAAA,CAAI,YAAA,CAAa,GAAA,CAAI,QAAQ,CAAA,EAAG;AACrC,IAAA,GAAA,CAAI,YAAA,CAAa,OAAO,QAAQ,CAAA;AAChC,IAAA,MAAA,CAAO,QAAQ,YAAA,CAAa,IAAI,EAAA,EAAI,GAAA,CAAI,UAAU,CAAA;AAAA,EACpD,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"6V7RVUXX.js","sourcesContent":["import { getConfig } from '../config';\nimport { getTokens } from './client';\n\n// ── Funnel telemetry transport ──────────────────────────────────────────────\n//\n// Thin client for the-backend's abandoned-funnel capture endpoints:\n// GET /config/funnel → which capture features this tenant enabled\n// POST /funnel/events → survey-session telemetry sink\n//\n// Everything here is fire-and-forget and fail-silent: funnel capture is\n// marketing instrumentation, and it must never break or slow the survey.\n\nexport interface FunnelConfig {\n telemetry: boolean;\n emailGate: boolean;\n /** When true (tenant features.funnelEmailGateRequired), the gate offers no skip. */\n emailGateRequired: boolean;\n}\n\nconst DISABLED: FunnelConfig = { telemetry: false, emailGate: false, emailGateRequired: false };\n\nlet configPromise: Promise<FunnelConfig> | null = null;\n\n/**\n * The tenant's funnel-capture posture, fetched once per page load and cached.\n * Fails closed: any error reads as \"both off\".\n */\nexport function fetchFunnelConfig(): Promise<FunnelConfig> {\n if (!configPromise) {\n configPromise = (async () => {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/config/funnel`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return DISABLED;\n const body = (await res.json()) as Partial<FunnelConfig>;\n return {\n telemetry: body.telemetry === true,\n emailGate: body.emailGate === true,\n emailGateRequired: body.emailGateRequired === true,\n };\n } catch {\n return DISABLED;\n }\n })();\n }\n return configPromise;\n}\n\n/**\n * Continue an existing funnel session (resume-from-email): the emailed link\n * identifies the session that already holds this person's email and reminder\n * history, so adopting its id keeps everything on one row instead of forking a\n * new one that looks like a brand-new visitor.\n */\nexport function adoptFunnelSessionId(id: string): void {\n if (!id) return;\n try {\n sessionStorage.setItem(sessionIdKey(), id);\n } catch {\n /* storage unavailable — the session stays ephemeral */\n }\n}\n\n/** Test seam: forget the cached config so the next fetch re-resolves. */\nexport function resetFunnelConfigCache(): void {\n configPromise = null;\n}\n\nconst sessionIdKey = () => `${getConfig().storagePrefix}-funnel-session`;\n\n/**\n * Stable id for this survey session, minted on first use and kept in\n * sessionStorage — a refresh continues the same session (matching the survey\n * draft's resume behavior); a new tab or browser session starts a new one.\n */\nexport function funnelSessionId(): string {\n let id: string | null = null;\n try {\n id = sessionStorage.getItem(sessionIdKey());\n } catch {\n /* storage unavailable (private mode) — fall through to ephemeral id */\n }\n if (!id) {\n id =\n typeof crypto !== 'undefined' && 'randomUUID' in crypto\n ? crypto.randomUUID()\n : `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n try {\n sessionStorage.setItem(sessionIdKey(), id);\n } catch {\n /* ephemeral it is */\n }\n }\n return id;\n}\n\n/**\n * The current survey session id, or null — WITHOUT minting one.\n *\n * `funnelSessionId()` creates an id on first read, which is right for the\n * survey (asking means a survey is starting) and wrong for anything else. Cart\n * capture uses this to say \"if this shopper also has a survey session, here it\n * is\" — letting the backend borrow the email the gate already collected —\n * without conjuring survey sessions on a storefront that never runs one.\n */\nexport function peekFunnelSessionId(): string | null {\n try {\n return sessionStorage.getItem(sessionIdKey());\n } catch {\n return null;\n }\n}\n\n/**\n * The member's access token, when this browser has one.\n *\n * Read raw and never refreshed: these are fire-and-forget telemetry posts, and\n * a token refresh is a real network round-trip on the unload path. An expired\n * token is not a failure either — the sinks take it with `optionalAuth`, so a\n * stale one simply reads as an anonymous visitor, which is what we had before.\n */\nexport function captureAuthHeader(): Record<string, string> {\n try {\n const token = getTokens()?.accessToken;\n return token ? { Authorization: `Bearer ${token}` } : {};\n } catch {\n return {};\n }\n}\n\n/**\n * Fire-and-forget event post. `keepalive` lets the request survive a page\n * unload — which is exactly when the `abandoned` event is sent. (This is why\n * it's `fetch` and not `navigator.sendBeacon`: beacons can't carry the\n * X-Tenant-Key header the tenant-scoped mount requires — nor the bearer token\n * below.)\n *\n * The token identifies a signed-in member to the sink. Without it a member's\n * session is stored anonymously, and the pre-survey email gate — the only\n * other writer of a session's identity — is deliberately never shown to\n * someone already signed in, so their drop-off could never be attributed to\n * them. That is the whole population of a site where the account is created\n * before the questionnaire (savings-program signups, returning members\n * starting a second intake).\n */\nexport function postFunnelEvent(type: string, data?: Record<string, unknown>): void {\n try {\n const cfg = getConfig();\n void fetch(`${cfg.apiBase}/funnel/events`, {\n method: 'POST',\n keepalive: true,\n headers: {\n 'Content-Type': 'application/json',\n 'X-Tenant-Key': cfg.tenantKey,\n ...captureAuthHeader(),\n },\n body: JSON.stringify({ sessionId: funnelSessionId(), type, data }),\n }).catch(() => {});\n } catch {\n /* not configured yet — drop */\n }\n}\n\n// ── Survey drafts (cross-device resume) ─────────────────────────────────────\n\nexport interface FunnelDraftPayload {\n answers: Array<{ questionId: string; value: unknown }>;\n stepIndex: number;\n}\n\n/**\n * Save in-progress answers to Apex (through the-backend's embed proxy) and\n * return the draft id, so the next save updates the same row.\n *\n * Answers travel to the CLINICAL system — the partner backend stores only the\n * returned pointer. Returns null on any failure: a draft is best-effort, and\n * losing one costs a retype, never correctness.\n */\nexport async function saveFunnelDraft(\n draft: FunnelDraftPayload & { draftId?: string; drugIds?: string[]; templateId?: string; mode?: string },\n): Promise<string | null> {\n try {\n const cfg = getConfig();\n if (!cfg.apexEmbedApiBase) return null;\n const res = await fetch(`${cfg.apexEmbedApiBase}/v2/embed/surveys/drafts`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json', 'X-Tenant-Key': cfg.tenantKey },\n body: JSON.stringify(draft),\n });\n if (!res.ok) return null;\n const body = (await res.json()) as { draftId?: string };\n return body.draftId ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface ResumedDraft extends FunnelDraftPayload {\n sessionId: string;\n draftId: string;\n}\n\n/**\n * Exchange an emailed resume token for the saved answers.\n *\n * The token is the ONLY thing authorizing this read — the-backend verifies its\n * HMAC before fetching from Apex with credentials the browser never sees. A\n * 404 (expired, already submitted, tampered) resolves to null so the caller\n * simply starts a fresh survey.\n */\nexport async function fetchResumedDraft(token: string): Promise<ResumedDraft | null> {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/funnel/resume?token=${encodeURIComponent(token)}`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return null;\n const body = (await res.json()) as Partial<ResumedDraft>;\n if (!body.draftId || !Array.isArray(body.answers)) return null;\n return {\n sessionId: String(body.sessionId ?? ''),\n draftId: body.draftId,\n answers: body.answers,\n stepIndex: typeof body.stepIndex === 'number' ? body.stepIndex : 0,\n };\n } catch {\n return null;\n }\n}\n\n/** Read the `?resume=` token from the current URL. */\nexport function readResumeToken(): string | null {\n try {\n const token = new URLSearchParams(window.location.search).get('resume');\n return token && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Drop `?resume=` from the address bar once it has been redeemed.\n *\n * This token authorizes a read of someone's clinical answers, so leaving it in\n * the address bar is worse than leaving the cart's there: it gets bookmarked,\n * pasted into a support chat, or captured by whatever the patient's browser\n * syncs. The answers are mirrored into local storage on redemption, so a\n * refresh resumes from this device without it. History is replaced, not\n * pushed — the token was never a page.\n */\nexport function stripResumeToken(): void {\n try {\n const url = new URL(window.location.href);\n if (!url.searchParams.has('resume')) return;\n url.searchParams.delete('resume');\n window.history.replaceState({}, '', url.toString());\n } catch {\n /* no history API — leaving the param is harmless */\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { onTokensCleared, authStorageKey, getTokens, usersApi, ApiError, affiliateAuthStorageKey, getAffiliateTokens, affiliatePortalApi, clearTokens, authApi, clearAffiliateTokens, setTokens, setAffiliateTokens } from './
|
|
1
|
+
import { onTokensCleared, authStorageKey, getTokens, usersApi, ApiError, affiliateAuthStorageKey, getAffiliateTokens, affiliatePortalApi, clearTokens, authApi, clearAffiliateTokens, setTokens, setAffiliateTokens } from './RDZDD5UW.js';
|
|
2
2
|
import { onConfigured, getConfig } from './2IFPDU4D.js';
|
|
3
3
|
import { createRoot, createSignal, createMemo, batch } from 'solid-js';
|
|
4
4
|
|
|
@@ -382,5 +382,5 @@ var medicationStore = createRoot(createMedicationStore);
|
|
|
382
382
|
var medication_default = medicationStore;
|
|
383
383
|
|
|
384
384
|
export { affiliateAuth_default, auth_default, cart_default, medication_default };
|
|
385
|
-
//# sourceMappingURL=
|
|
386
|
-
//# sourceMappingURL=
|
|
385
|
+
//# sourceMappingURL=A6FJGQIS.js.map
|
|
386
|
+
//# sourceMappingURL=A6FJGQIS.js.map
|